file_id
stringlengths 5
9
| content
stringlengths 128
32.8k
| repo
stringlengths 9
63
| path
stringlengths 8
120
| token_length
int64 52
8.14k
| original_comment
stringlengths 5
1.83k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 111
32.8k
| excluded
float64 0
1
⌀ | tmp
float64 5
1.83k
⌀ | test
float64 0
1
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|
60464_6 | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* 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 top.continew.admin.common.constant;
/**
* UI 相关常量
*
* @author Charles7c
* @since 2023/9/17 14:12
*/
public class UiConstants {
/**
* 主色(极致蓝)
*/
public static final String COLOR_PRIMARY = "arcoblue";
/**
* 成功色(仙野绿)
*/
public static final String COLOR_SUCCESS = "green";
/**
* 警告色(活力橙)
*/
public static final String COLOR_WARNING = "orangered";
/**
* 错误色(浪漫红)
*/
public static final String COLOR_ERROR = "red";
/**
* 默认色(中性灰)
*/
public static final String COLOR_DEFAULT = "gray";
private UiConstants() {
}
} | Charles7c/continew-admin | continew-admin-common/src/main/java/top/continew/admin/common/constant/UiConstants.java | 372 | /**
* 默认色(中性灰)
*/ | block_comment | zh-cn | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* 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 top.continew.admin.common.constant;
/**
* UI 相关常量
*
* @author Charles7c
* @since 2023/9/17 14:12
*/
public class UiConstants {
/**
* 主色(极致蓝)
*/
public static final String COLOR_PRIMARY = "arcoblue";
/**
* 成功色(仙野绿)
*/
public static final String COLOR_SUCCESS = "green";
/**
* 警告色(活力橙)
*/
public static final String COLOR_WARNING = "orangered";
/**
* 错误色(浪漫红)
*/
public static final String COLOR_ERROR = "red";
/**
* 默认色 <SUF>*/
public static final String COLOR_DEFAULT = "gray";
private UiConstants() {
}
} | 0 | 27 | 0 |
32283_17 | package com.scj.beilu.app.location;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;
import com.scj.beilu.app.R;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import static android.content.Intent.URI_ALLOW_UNSAFE;
/**
* @author Mingxun
* @time on 2019/4/17 16:56
*/
public class LoctionNavigationUtil {
public final static String BAIDU_PACKAGENAME = "com.baidu.BaiduMap";
public final static String GAODE_PACKAGENAME = "com.autonavi.minimap";
/**
* 高德导航
*
* @param context
* @param location
*/
public static void gaodeGuide(Context context, double[] location) {
if (isAvilible(context, GAODE_PACKAGENAME)) {
try {
Intent intent = Intent.parseUri("androidamap://navi?sourceApplication=" +
context.getResources().getString(R.string.app_name) +
"&poiname=我的目的地" +
"&lat=" + location[0] +
"&lon=" + location[1] +
"&dev=0", URI_ALLOW_UNSAFE);
context.startActivity(intent);
} catch (URISyntaxException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
}
/**
* 百度导航
*
* @param context
* @param location location[0]纬度lat,location[1]经度lon
*/
public static void baiduGuide(Context context, double[] location) {
double[] baiduLoc = GpsUtils.gcj02_To_Bd09(location[0], location[1]);
if (isAvilible(context, "com.baidu.BaiduMap")) {//传入指定应用包名
try {
//intent = Intent.getIntent("intent://map/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving®ion=西安&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
Intent intent = Intent.getIntent("intent://map/direction?" +
//"origin=latlng:"+"34.264642646862,108.95108518068&" + //起点 此处不传值默认选择当前位置
"destination=latlng:" + baiduLoc[0] + "," + baiduLoc[1] + "|name:我的目的地" + //终点
"&mode=driving" + //导航路线方式
"®ion=" + //
"&src=" +
context.getResources().getString(R.string.app_name) +
"#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
context.startActivity(intent); //启动调用
} catch (URISyntaxException e) {
e.printStackTrace();
}
} else {//未安装
//market为路径,id为包名
//显示手机上所有的market商店
Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
}
/**
* 检查手机上是否安装了指定的软件
*
* @param context
* @param packageName:应用包名
* @return
*/
public static boolean isAvilible(Context context, String packageName) {
//获取packagemanager
final PackageManager packageManager = context.getPackageManager();
//获取所有已安装程序的包信息
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
//用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<String>();
//从pinfo中将包名字逐一取出,压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
//判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
return packageNames.contains(packageName);
}
}
| CharlesMing/beilu-android-open-project | app/src/main/java/com/scj/beilu/app/location/LoctionNavigationUtil.java | 1,202 | //获取所有已安装程序的包信息 | line_comment | zh-cn | package com.scj.beilu.app.location;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;
import com.scj.beilu.app.R;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import static android.content.Intent.URI_ALLOW_UNSAFE;
/**
* @author Mingxun
* @time on 2019/4/17 16:56
*/
public class LoctionNavigationUtil {
public final static String BAIDU_PACKAGENAME = "com.baidu.BaiduMap";
public final static String GAODE_PACKAGENAME = "com.autonavi.minimap";
/**
* 高德导航
*
* @param context
* @param location
*/
public static void gaodeGuide(Context context, double[] location) {
if (isAvilible(context, GAODE_PACKAGENAME)) {
try {
Intent intent = Intent.parseUri("androidamap://navi?sourceApplication=" +
context.getResources().getString(R.string.app_name) +
"&poiname=我的目的地" +
"&lat=" + location[0] +
"&lon=" + location[1] +
"&dev=0", URI_ALLOW_UNSAFE);
context.startActivity(intent);
} catch (URISyntaxException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
}
/**
* 百度导航
*
* @param context
* @param location location[0]纬度lat,location[1]经度lon
*/
public static void baiduGuide(Context context, double[] location) {
double[] baiduLoc = GpsUtils.gcj02_To_Bd09(location[0], location[1]);
if (isAvilible(context, "com.baidu.BaiduMap")) {//传入指定应用包名
try {
//intent = Intent.getIntent("intent://map/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving®ion=西安&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
Intent intent = Intent.getIntent("intent://map/direction?" +
//"origin=latlng:"+"34.264642646862,108.95108518068&" + //起点 此处不传值默认选择当前位置
"destination=latlng:" + baiduLoc[0] + "," + baiduLoc[1] + "|name:我的目的地" + //终点
"&mode=driving" + //导航路线方式
"®ion=" + //
"&src=" +
context.getResources().getString(R.string.app_name) +
"#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
context.startActivity(intent); //启动调用
} catch (URISyntaxException e) {
e.printStackTrace();
}
} else {//未安装
//market为路径,id为包名
//显示手机上所有的market商店
Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
}
/**
* 检查手机上是否安装了指定的软件
*
* @param context
* @param packageName:应用包名
* @return
*/
public static boolean isAvilible(Context context, String packageName) {
//获取packagemanager
final PackageManager packageManager = context.getPackageManager();
//获取 <SUF>
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
//用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<String>();
//从pinfo中将包名字逐一取出,压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
//判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
return packageNames.contains(packageName);
}
}
| 1 | 15 | 1 |
12001_93 | package com.jack.isafety;
import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jack.specialEffects.StringUtils;
import com.jack.sqlite.DBUtils;
import com.jack.sqlite.UserBean;
import com.maintabs_d_secondpages.UserActivity;
import com.nightonke.boommenu.BoomButtons.HamButton;
import com.nightonke.boommenu.BoomButtons.OnBMClickListener;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import es.dmoral.toasty.Toasty;
import io.socket.emitter.Emitter;
import xin.skingorz.Bean.User;
import xin.skingorz.internet.Search;
import xin.skingorz.internet.UpdataUser;
import xin.skingorz.utils.GlobalVariable;
import static com.jack.service.BaseService.mSocket;
import static com.jack.sqlite.UserBean.Friend;
import static com.jack.sqlite.UserBean.home;
import static com.jack.sqlite.UserBean.id;
import static com.jack.sqlite.UserBean.location;
import static com.jack.sqlite.UserBean.messageText;
import static com.jack.sqlite.UserBean.currentLocation;
import static com.jack.sqlite.UserBean.phone;
import static com.jack.sqlite.UserBean.phoneNumber;
import static com.jack.sqlite.UserBean.sex;
import static com.jack.sqlite.UserBean.signature;
import static com.jack.sqlite.UserBean.userName;
public class Maintabs_AActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener{
protected Context mContext;
//相机相关
public static final int VIDEO_REQUEST = 0;// 录像
public static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
public static final int CROP_PHOTO = 2; //相册
//照片显示区域
//private ImageView picture;
private Uri imageUri;
public static File tempFile;
private UpdataUser updataUser=new UpdataUser();
//小功能部件
private LinearLayout Header_Dial;
private LinearLayout Header_Message;
private LinearLayout Header_takePhoto;
private LinearLayout Header_Video;
private TextView Header_Show;
private TextView Body_Show;
private JSONArray jsonArray;
String email;
String rUsername;
String spUserName=id;
//获取信息
//Search search=new Search();
public Maintabs_AActivity() throws InterruptedException, JSONException {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintabs__a);
mContext=this;
//初始化部件
initView();
//picture = (ImageView) findViewById(R.id.picture);
//初始化数据
initDate();
Map<String,String> map=new HashMap<String, String>();
map.put("search",userName);
net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(map);
mSocket.emit("getInfor",jsonObject);
mSocket.on("searchResult",getInformation);
//录像与相机点击按钮
Header_takePhoto.setOnClickListener(this);
Header_Video.setOnClickListener(this);
//设置点击
Header_Dial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
call(phoneNumber);
}
});
Header_Message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message(phoneNumber,messageText,currentLocation);
}
});
Header_Show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
});
Body_Show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Maintabs_AActivity.this, "请选择您的守护者", Toast.LENGTH_SHORT).show();
}
});
//长按
Header_Dial.setOnLongClickListener(this);//注册监听
Header_Message.setOnLongClickListener(this);//注册监听
/**listview相关*/
int[] Listview_item_logo = new int[]{
R.mipmap.safergo/*, R.drawable.protect, R.color.main_color_darkblue, R.color.main_color_darkgreen, R.color.main_color_red, R.color.main_color_pink,
*/
};
String[] Listview_item_title=new String[]{
"jack"
};
String[] Listview_item_email = new String[]{
"[email protected]"
};
List<Map<String,Object>> List_item=new ArrayList<Map<String,Object>>();
for(int i=0;i<Listview_item_logo.length;i++){
Map<String,Object> map1=new HashMap<String, Object>();
map1.put("main_listview_item_logo",Listview_item_logo[i]);
map1.put("main_listview_item_title",Listview_item_title[i]);
map1.put("main_listview_item_email",Listview_item_email[i]);
List_item.add(map1);
}
//配置适配器
SimpleAdapter adapter=new SimpleAdapter(this,List_item, R.layout.maintabs_a_listview_item,new String[]{"main_listview_item_logo","main_listview_item_title","main_listview_item_email"},
new int[]{R.id.main_listview_item_logo, R.id.main_listview_item_title,R.id.main_listview_item_id});
ListView mMain_listview=findViewById(R.id.maintabs_a_listview);
mMain_listview.setAdapter(adapter);
//监听点击
mMain_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String,Object> map= (Map<String, Object>) parent.getItemAtPosition(position);
Toast.makeText(Maintabs_AActivity.this, map.get("main_listview_item_title").toString(), Toast.LENGTH_SHORT).show();
//onBackPressed();
/*switch (position){
case 0:
break;
}*/
}
});
/*mSocket.emit("GetFriend");
mSocket.on("allFriends",FriendLister);
for (int i = 0; i < Friend.length(); i++) {
//Listview_item_title = new String[userArrary.length];
//Listview_item_title[i] = userArrary[i].getUsername();
try {
Listview_item_email[i]= ((JSONObject) UserBean.Friend.get(i)).getString("friends_email");
} catch (JSONException e) {
e.printStackTrace();
}
}
//listview_item的添加
//素材数组的构建
List<Map<String, Object>> List_item = new ArrayList<Map<String, Object>>();
for (int i = 0; i < Friend.length(); i++) {
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("main_listview_item_logo", Listview_item_logo[i]);
//map.put("main_listview_item_title", userArrary[i].getUsername());
map2.put("main_listview_item_email", Listview_item_email[i]);
List_item.add(map2);
}
//配置适配器
SimpleAdapter adapter = new SimpleAdapter(this, List_item, R.layout.maintabs_a_listview_item, new String[]{"main_listview_item_logo", *//*"main_listview_item_title", *//*"main_listview_item_email"},
new int[]{R.id.main_listview_item_logo, *//*R.id.main_listview_item_title,*//* R.id.main_listview_item_id});
ListView mMain_listview = findViewById(R.id.maintabs_a_listview);
mMain_listview.setAdapter(adapter);
//监听点击
mMain_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
Toasty.info(Maintabs_AActivity.this, "好友守护", Toast.LENGTH_SHORT, true).show();
*//*Intent intent=new Intent(Maintabs_AActivity.this, com.elabs.android.chatview.MainActivity.class);
startActivity(intent);*//*
*//*for(int i=0;i<Friend.length();i++){
if (position)
position=i;
//String name=Friend[i].getUsername();
String email=Listview_item_email[i];
Intent intent=new Intent(Maintabs_AActivity.this,com.elabs.android.chatview.MainActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name",name);
bundle.putString("email",email);
intent.putExtras(bundle);
startActivity(intent);
}*//*
switch (position) {
case 0:
//GlobalVariable.handle.sendPeople(userArrary[0].getEmail());
break;
}
}
});*/
/** 悬浮按钮*/
BoomMenuButton bmb = findViewById(R.id.bmb_a);
HamButton.Builder builder = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_addperson)
.normalText("添加好友或群组!")
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.subNormalText("好友多多,守护多多~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Intent intent = new Intent(Maintabs_AActivity.this, com.maintabs_secondpages.Maintabs_a_adduser.class);
startActivity(intent);
}
});
bmb.addBuilder(builder);
HamButton.Builder builder3 = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_search)
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.normalText("查询好友或群组!")
.subNormalText("快速查找自己的守护对象~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Intent intent = new Intent(Maintabs_AActivity.this, com.maintabs_secondpages.Maintabs_a_searchuser.class);
startActivity(intent);
}
});
bmb.addBuilder(builder3);
HamButton.Builder builder2 = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_addgroup)
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.normalText("交际圈!")
.subNormalText("发现SaferGo更多有趣内容~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Intent intent = new Intent(Maintabs_AActivity.this, com.maintabs_secondpages.Maintabs_a_group.class);
startActivity(intent);
}
});
bmb.addBuilder(builder2);
HamButton.Builder builder4 = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_share)
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.normalText("分享守护!")
.subNormalText("让更多的人来守护你这个小可爱吧~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Toast.makeText(Maintabs_AActivity.this, "SaferGo", Toast.LENGTH_SHORT).show();
}
});
bmb.addBuilder(builder4);
}
private Emitter.Listener FriendLister = new Emitter.Listener() {
@Override
public void call(Object... args) {
//主线程调用
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = null;
try {
data = new JSONObject((String)args[0]);
} catch (JSONException e) {
e.printStackTrace();
}
try {
/*phoneNumber ="";
messageText = "SaferGo官方短信:您的好友发生突发情况,需要您的帮助!";
currentLocation = "发生情况位置为:北京市朝阳区";*/
Friend= data.getJSONArray("friend");
} catch (JSONException e) {
return;
}
}
});
}
};
private Emitter.Listener getInformation = new Emitter.Listener() {
@Override
public void call(Object... args) {
//主线程调用
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = null;
try {
data = new JSONObject((String)args[0]);
} catch (JSONException e) {
e.printStackTrace();
}
try {
/*phoneNumber ="";
messageText = "SaferGo官方短信:您的好友发生突发情况,需要您的帮助!";
currentLocation = "发生情况位置为:北京市朝阳区";*/
phoneNumber = data.getString("emergencyPhone");
messageText = data.getString("msgTemplate");
} catch (JSONException e) {
return;
}
}
});
}
};
//点击重写
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.maintabs_a_body_header_4: {
openCamera(this);
break;
}
case R.id.maintabs_a_body_header_3: {
openVideo(this);
break;
}
}
}
//部件初始化
private void initView() {
Header_Dial = findViewById(R.id.maintabs_a_body_header_1);
Header_Message = findViewById(R.id.maintabs_a_body_header_2);
Header_takePhoto = findViewById(R.id.maintabs_a_body_header_4);
Header_Video=findViewById(R.id.maintabs_a_body_header_3);
Header_Show=findViewById(R.id.miantabs_a_body_body_show);
Body_Show=findViewById(R.id.miantabs_a_body_body_show2);
}
//初始化数据
private void initDate() {
UserBean bean = null;
//实例化DBUtils,同时调用其方法获取个人信息资料
//bean = DBUtils.getInstance(this).getUserInfo(spUserName);
bean = DBUtils.getInstance(this).getUserInfo("username");
//如果第一次进入,数据库没有保留用户信息
if (bean == null) {
bean = new UserBean();
bean.userName = "name";
bean.messageText = "SaferGo官方短信:您的好友发生突发情况,需要您的帮助!";
bean.currentLocation = "发生情况位置为:北京市朝阳区";
//保存到数据库
DBUtils.getInstance(this).saveUserInfo(bean);
}
//setValue(bean);
}
//打电话
private void call(String phone) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(intent);
}
//发短信
private void message(String phone,String contents1,String contents2){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SENDTO); //设置动作为发送短信
intent.setData(Uri.parse("smsto:"+phone)); //设置发送的号码
intent.putExtra("sms_body",messageText+contents1+contents2); //设置发送的内容
Toast.makeText(Maintabs_AActivity.this, "跳转成功", Toast.LENGTH_SHORT).show();
startActivity(intent); //启动 Activity
}
//请求码反馈
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_REQUEST_CAREMA://调用相机
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHOTO); // 启动裁剪程序
}
break;
case VIDEO_REQUEST://调用录像
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "video/*");
//intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//startActivityForResult(intent, CROP_PHOTO); // 启动裁剪程序
}
break;
/* case CROP_PHOTO://调用相册
if (resultCode == RESULT_OK) {
try {
System.out.println(data.toString().length());
if (data.toString().length() != 11) {
Uri uri = data.getData();
imageUri = uri;
}
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break; */
}
}
//打开相机
public void openCamera(Activity activity) {
//獲取系統版本
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// 激活相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard()) {
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
String filename = timeStampFormat.format(new Date());
tempFile = new File(Environment.getExternalStorageDirectory(),
filename + ".jpg");
if (currentapiVersion < 24) {
// 从文件中创建uri
imageUri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
} else {
//兼容android7.0 使用共享文件的形式
ContentValues contentValues = new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
//检查是否有存储权限,以免崩溃
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
Toast.makeText(this, "请开启存储权限", Toast.LENGTH_SHORT).show();
return;
}
imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
}
}
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
activity.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
}
//打开录像
public void openVideo(Activity activity) {
//獲取系統版本
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// 激活相机
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard()) {
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String filename = timeStampFormat.format(new Date());
tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
filename + ".mp4");
if (currentapiVersion < 24) {
// 从文件中创建uri
imageUri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
} else {
//兼容android7.0 使用共享文件的形式
//ContentValues contentValues = new ContentValues(1);
//contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
//检查是否有存储权限,以免崩溃
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
Toast.makeText(this, "请开启存储权限", Toast.LENGTH_SHORT).show();
return;
}
//imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
}
}
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
activity.startActivityForResult(intent, VIDEO_REQUEST);
}
/*
* 判断sdcard是否被挂载
*/
public static boolean hasSdcard() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
//调用相册
/* public void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, CROP_PHOTO);
}*/
// GlobalVariable.handle.sendPeople();
private void showDialog() {
final AlertDialog mAlertDialog = new AlertDialog.Builder(this).show();
View view = LayoutInflater.from(this).inflate(R.layout.layout_maintabs_a_show,null);
mAlertDialog.setContentView(view);
mAlertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mAlertDialog.cancel();
}
});
Window window = mAlertDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(0x00000000));
}
@Override
public boolean onLongClick(View v) {
if(v == Header_Dial){//当按下的是按钮时
showPhoneDialog();
}
if(v==Header_Message){
showMessageDialog();
}
return false;
}
/**
* 显示更换电话对话框
*/
public void showPhoneDialog() {
//从服务器获取电话
//String phone = currentUser.getMobilePhoneNumber();
new MaterialDialog.Builder(mContext)
.title("好友电话")
.inputType(InputType.TYPE_CLASS_TEXT)
.inputRangeRes(0, 11, R.color.red)
.positiveColor(getResources().getColor(R.color.white))
.negativeColor(getResources().getColor(R.color.white))
.backgroundColor(getResources().getColor(R.color.colorPrimary))
.titleColor(getResources().getColor(R.color.white))
.contentColor(getResources().getColor(R.color.white))
.input("请输入预设好友电话号码", phoneNumber, (dialog, input) -> {
String inputStr=input.toString();
if (inputStr.equals("")) {
Toast.makeText(Maintabs_AActivity.this,
"内容不能为空!" + input, Toast.LENGTH_LONG).show();
} else {
if (StringUtils.checkPhoneNumber(inputStr)) {
//上传服务器
Map<String,String> map=new HashMap<String, String>();
map.put("emergencyPhone",inputStr);
net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(map);
mSocket.emit("SetInfor",jsonObject);
phoneNumber=inputStr;
setPhoneNumber(phoneNumber);
} else {
Toast.makeText(Maintabs_AActivity.this,
"请输入正确的电话号码", Toast.LENGTH_LONG).show();
}
}
})
.positiveText("确定")
.show();
}
/**
* 显示消息模板对话框
*/
public void showMessageDialog() {
new MaterialDialog.Builder(mContext)
.title("消息模板")
.inputType(InputType.TYPE_CLASS_TEXT)
.inputRangeRes(0, 80, R.color.red)
.positiveColor(getResources().getColor(R.color.white))
.negativeColor(getResources().getColor(R.color.white))
.backgroundColor(getResources().getColor(R.color.colorPrimary))
.titleColor(getResources().getColor(R.color.white))
.contentColor(getResources().getColor(R.color.white))
.input("请输入消息模板", messageText, (dialog, input) -> {
String inputStr=input.toString();
if (inputStr.equals("")) {
Toast.makeText(Maintabs_AActivity.this,
"内容不能为空!" + input, Toast.LENGTH_LONG).show();
} else {
/*设置上传服务器*/
Map<String,String> map=new HashMap<String, String>();
map.put("msgTemplate",inputStr);
net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(map);
mSocket.emit("SetInfor",jsonObject);
messageText=inputStr;
setMessageText(messageText);
}
})
.positiveText("确定")
.show();
}
private void setPhoneNumber(String Number) {
//更新数据库字段
DBUtils.getInstance(this).updateUserInfo("phoneNumber",Number, spUserName);
}
private void setMessageText(String Number) {
//更新数据库字段
DBUtils.getInstance(this).updateUserInfo("messageText",Number, spUserName);
}
}
| Charleswow/SaferGO | app/src/main/java/com/jack/isafety/Maintabs_AActivity.java | 6,717 | //更新数据库字段 | line_comment | zh-cn | package com.jack.isafety;
import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jack.specialEffects.StringUtils;
import com.jack.sqlite.DBUtils;
import com.jack.sqlite.UserBean;
import com.maintabs_d_secondpages.UserActivity;
import com.nightonke.boommenu.BoomButtons.HamButton;
import com.nightonke.boommenu.BoomButtons.OnBMClickListener;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import es.dmoral.toasty.Toasty;
import io.socket.emitter.Emitter;
import xin.skingorz.Bean.User;
import xin.skingorz.internet.Search;
import xin.skingorz.internet.UpdataUser;
import xin.skingorz.utils.GlobalVariable;
import static com.jack.service.BaseService.mSocket;
import static com.jack.sqlite.UserBean.Friend;
import static com.jack.sqlite.UserBean.home;
import static com.jack.sqlite.UserBean.id;
import static com.jack.sqlite.UserBean.location;
import static com.jack.sqlite.UserBean.messageText;
import static com.jack.sqlite.UserBean.currentLocation;
import static com.jack.sqlite.UserBean.phone;
import static com.jack.sqlite.UserBean.phoneNumber;
import static com.jack.sqlite.UserBean.sex;
import static com.jack.sqlite.UserBean.signature;
import static com.jack.sqlite.UserBean.userName;
public class Maintabs_AActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener{
protected Context mContext;
//相机相关
public static final int VIDEO_REQUEST = 0;// 录像
public static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
public static final int CROP_PHOTO = 2; //相册
//照片显示区域
//private ImageView picture;
private Uri imageUri;
public static File tempFile;
private UpdataUser updataUser=new UpdataUser();
//小功能部件
private LinearLayout Header_Dial;
private LinearLayout Header_Message;
private LinearLayout Header_takePhoto;
private LinearLayout Header_Video;
private TextView Header_Show;
private TextView Body_Show;
private JSONArray jsonArray;
String email;
String rUsername;
String spUserName=id;
//获取信息
//Search search=new Search();
public Maintabs_AActivity() throws InterruptedException, JSONException {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintabs__a);
mContext=this;
//初始化部件
initView();
//picture = (ImageView) findViewById(R.id.picture);
//初始化数据
initDate();
Map<String,String> map=new HashMap<String, String>();
map.put("search",userName);
net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(map);
mSocket.emit("getInfor",jsonObject);
mSocket.on("searchResult",getInformation);
//录像与相机点击按钮
Header_takePhoto.setOnClickListener(this);
Header_Video.setOnClickListener(this);
//设置点击
Header_Dial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
call(phoneNumber);
}
});
Header_Message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message(phoneNumber,messageText,currentLocation);
}
});
Header_Show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
});
Body_Show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Maintabs_AActivity.this, "请选择您的守护者", Toast.LENGTH_SHORT).show();
}
});
//长按
Header_Dial.setOnLongClickListener(this);//注册监听
Header_Message.setOnLongClickListener(this);//注册监听
/**listview相关*/
int[] Listview_item_logo = new int[]{
R.mipmap.safergo/*, R.drawable.protect, R.color.main_color_darkblue, R.color.main_color_darkgreen, R.color.main_color_red, R.color.main_color_pink,
*/
};
String[] Listview_item_title=new String[]{
"jack"
};
String[] Listview_item_email = new String[]{
"[email protected]"
};
List<Map<String,Object>> List_item=new ArrayList<Map<String,Object>>();
for(int i=0;i<Listview_item_logo.length;i++){
Map<String,Object> map1=new HashMap<String, Object>();
map1.put("main_listview_item_logo",Listview_item_logo[i]);
map1.put("main_listview_item_title",Listview_item_title[i]);
map1.put("main_listview_item_email",Listview_item_email[i]);
List_item.add(map1);
}
//配置适配器
SimpleAdapter adapter=new SimpleAdapter(this,List_item, R.layout.maintabs_a_listview_item,new String[]{"main_listview_item_logo","main_listview_item_title","main_listview_item_email"},
new int[]{R.id.main_listview_item_logo, R.id.main_listview_item_title,R.id.main_listview_item_id});
ListView mMain_listview=findViewById(R.id.maintabs_a_listview);
mMain_listview.setAdapter(adapter);
//监听点击
mMain_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String,Object> map= (Map<String, Object>) parent.getItemAtPosition(position);
Toast.makeText(Maintabs_AActivity.this, map.get("main_listview_item_title").toString(), Toast.LENGTH_SHORT).show();
//onBackPressed();
/*switch (position){
case 0:
break;
}*/
}
});
/*mSocket.emit("GetFriend");
mSocket.on("allFriends",FriendLister);
for (int i = 0; i < Friend.length(); i++) {
//Listview_item_title = new String[userArrary.length];
//Listview_item_title[i] = userArrary[i].getUsername();
try {
Listview_item_email[i]= ((JSONObject) UserBean.Friend.get(i)).getString("friends_email");
} catch (JSONException e) {
e.printStackTrace();
}
}
//listview_item的添加
//素材数组的构建
List<Map<String, Object>> List_item = new ArrayList<Map<String, Object>>();
for (int i = 0; i < Friend.length(); i++) {
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("main_listview_item_logo", Listview_item_logo[i]);
//map.put("main_listview_item_title", userArrary[i].getUsername());
map2.put("main_listview_item_email", Listview_item_email[i]);
List_item.add(map2);
}
//配置适配器
SimpleAdapter adapter = new SimpleAdapter(this, List_item, R.layout.maintabs_a_listview_item, new String[]{"main_listview_item_logo", *//*"main_listview_item_title", *//*"main_listview_item_email"},
new int[]{R.id.main_listview_item_logo, *//*R.id.main_listview_item_title,*//* R.id.main_listview_item_id});
ListView mMain_listview = findViewById(R.id.maintabs_a_listview);
mMain_listview.setAdapter(adapter);
//监听点击
mMain_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
Toasty.info(Maintabs_AActivity.this, "好友守护", Toast.LENGTH_SHORT, true).show();
*//*Intent intent=new Intent(Maintabs_AActivity.this, com.elabs.android.chatview.MainActivity.class);
startActivity(intent);*//*
*//*for(int i=0;i<Friend.length();i++){
if (position)
position=i;
//String name=Friend[i].getUsername();
String email=Listview_item_email[i];
Intent intent=new Intent(Maintabs_AActivity.this,com.elabs.android.chatview.MainActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name",name);
bundle.putString("email",email);
intent.putExtras(bundle);
startActivity(intent);
}*//*
switch (position) {
case 0:
//GlobalVariable.handle.sendPeople(userArrary[0].getEmail());
break;
}
}
});*/
/** 悬浮按钮*/
BoomMenuButton bmb = findViewById(R.id.bmb_a);
HamButton.Builder builder = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_addperson)
.normalText("添加好友或群组!")
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.subNormalText("好友多多,守护多多~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Intent intent = new Intent(Maintabs_AActivity.this, com.maintabs_secondpages.Maintabs_a_adduser.class);
startActivity(intent);
}
});
bmb.addBuilder(builder);
HamButton.Builder builder3 = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_search)
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.normalText("查询好友或群组!")
.subNormalText("快速查找自己的守护对象~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Intent intent = new Intent(Maintabs_AActivity.this, com.maintabs_secondpages.Maintabs_a_searchuser.class);
startActivity(intent);
}
});
bmb.addBuilder(builder3);
HamButton.Builder builder2 = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_addgroup)
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.normalText("交际圈!")
.subNormalText("发现SaferGo更多有趣内容~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Intent intent = new Intent(Maintabs_AActivity.this, com.maintabs_secondpages.Maintabs_a_group.class);
startActivity(intent);
}
});
bmb.addBuilder(builder2);
HamButton.Builder builder4 = new HamButton.Builder()
.normalImageRes(R.drawable.maintabs_a_share)
.imageRect(new Rect(35, 30, Util.dp2px(50), Util.dp2px(50)))
.normalText("分享守护!")
.subNormalText("让更多的人来守护你这个小可爱吧~")
.listener(new OnBMClickListener() {
@Override
public void onBoomButtonClick(int index) {
// When the boom-button corresponding this builder is clicked.
Toast.makeText(Maintabs_AActivity.this, "SaferGo", Toast.LENGTH_SHORT).show();
}
});
bmb.addBuilder(builder4);
}
private Emitter.Listener FriendLister = new Emitter.Listener() {
@Override
public void call(Object... args) {
//主线程调用
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = null;
try {
data = new JSONObject((String)args[0]);
} catch (JSONException e) {
e.printStackTrace();
}
try {
/*phoneNumber ="";
messageText = "SaferGo官方短信:您的好友发生突发情况,需要您的帮助!";
currentLocation = "发生情况位置为:北京市朝阳区";*/
Friend= data.getJSONArray("friend");
} catch (JSONException e) {
return;
}
}
});
}
};
private Emitter.Listener getInformation = new Emitter.Listener() {
@Override
public void call(Object... args) {
//主线程调用
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = null;
try {
data = new JSONObject((String)args[0]);
} catch (JSONException e) {
e.printStackTrace();
}
try {
/*phoneNumber ="";
messageText = "SaferGo官方短信:您的好友发生突发情况,需要您的帮助!";
currentLocation = "发生情况位置为:北京市朝阳区";*/
phoneNumber = data.getString("emergencyPhone");
messageText = data.getString("msgTemplate");
} catch (JSONException e) {
return;
}
}
});
}
};
//点击重写
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.maintabs_a_body_header_4: {
openCamera(this);
break;
}
case R.id.maintabs_a_body_header_3: {
openVideo(this);
break;
}
}
}
//部件初始化
private void initView() {
Header_Dial = findViewById(R.id.maintabs_a_body_header_1);
Header_Message = findViewById(R.id.maintabs_a_body_header_2);
Header_takePhoto = findViewById(R.id.maintabs_a_body_header_4);
Header_Video=findViewById(R.id.maintabs_a_body_header_3);
Header_Show=findViewById(R.id.miantabs_a_body_body_show);
Body_Show=findViewById(R.id.miantabs_a_body_body_show2);
}
//初始化数据
private void initDate() {
UserBean bean = null;
//实例化DBUtils,同时调用其方法获取个人信息资料
//bean = DBUtils.getInstance(this).getUserInfo(spUserName);
bean = DBUtils.getInstance(this).getUserInfo("username");
//如果第一次进入,数据库没有保留用户信息
if (bean == null) {
bean = new UserBean();
bean.userName = "name";
bean.messageText = "SaferGo官方短信:您的好友发生突发情况,需要您的帮助!";
bean.currentLocation = "发生情况位置为:北京市朝阳区";
//保存到数据库
DBUtils.getInstance(this).saveUserInfo(bean);
}
//setValue(bean);
}
//打电话
private void call(String phone) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(intent);
}
//发短信
private void message(String phone,String contents1,String contents2){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SENDTO); //设置动作为发送短信
intent.setData(Uri.parse("smsto:"+phone)); //设置发送的号码
intent.putExtra("sms_body",messageText+contents1+contents2); //设置发送的内容
Toast.makeText(Maintabs_AActivity.this, "跳转成功", Toast.LENGTH_SHORT).show();
startActivity(intent); //启动 Activity
}
//请求码反馈
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_REQUEST_CAREMA://调用相机
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHOTO); // 启动裁剪程序
}
break;
case VIDEO_REQUEST://调用录像
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "video/*");
//intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//startActivityForResult(intent, CROP_PHOTO); // 启动裁剪程序
}
break;
/* case CROP_PHOTO://调用相册
if (resultCode == RESULT_OK) {
try {
System.out.println(data.toString().length());
if (data.toString().length() != 11) {
Uri uri = data.getData();
imageUri = uri;
}
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break; */
}
}
//打开相机
public void openCamera(Activity activity) {
//獲取系統版本
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// 激活相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard()) {
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
String filename = timeStampFormat.format(new Date());
tempFile = new File(Environment.getExternalStorageDirectory(),
filename + ".jpg");
if (currentapiVersion < 24) {
// 从文件中创建uri
imageUri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
} else {
//兼容android7.0 使用共享文件的形式
ContentValues contentValues = new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
//检查是否有存储权限,以免崩溃
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
Toast.makeText(this, "请开启存储权限", Toast.LENGTH_SHORT).show();
return;
}
imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
}
}
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
activity.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
}
//打开录像
public void openVideo(Activity activity) {
//獲取系統版本
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// 激活相机
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard()) {
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String filename = timeStampFormat.format(new Date());
tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
filename + ".mp4");
if (currentapiVersion < 24) {
// 从文件中创建uri
imageUri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
} else {
//兼容android7.0 使用共享文件的形式
//ContentValues contentValues = new ContentValues(1);
//contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
//检查是否有存储权限,以免崩溃
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
Toast.makeText(this, "请开启存储权限", Toast.LENGTH_SHORT).show();
return;
}
//imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
}
}
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
activity.startActivityForResult(intent, VIDEO_REQUEST);
}
/*
* 判断sdcard是否被挂载
*/
public static boolean hasSdcard() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
//调用相册
/* public void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, CROP_PHOTO);
}*/
// GlobalVariable.handle.sendPeople();
private void showDialog() {
final AlertDialog mAlertDialog = new AlertDialog.Builder(this).show();
View view = LayoutInflater.from(this).inflate(R.layout.layout_maintabs_a_show,null);
mAlertDialog.setContentView(view);
mAlertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mAlertDialog.cancel();
}
});
Window window = mAlertDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(0x00000000));
}
@Override
public boolean onLongClick(View v) {
if(v == Header_Dial){//当按下的是按钮时
showPhoneDialog();
}
if(v==Header_Message){
showMessageDialog();
}
return false;
}
/**
* 显示更换电话对话框
*/
public void showPhoneDialog() {
//从服务器获取电话
//String phone = currentUser.getMobilePhoneNumber();
new MaterialDialog.Builder(mContext)
.title("好友电话")
.inputType(InputType.TYPE_CLASS_TEXT)
.inputRangeRes(0, 11, R.color.red)
.positiveColor(getResources().getColor(R.color.white))
.negativeColor(getResources().getColor(R.color.white))
.backgroundColor(getResources().getColor(R.color.colorPrimary))
.titleColor(getResources().getColor(R.color.white))
.contentColor(getResources().getColor(R.color.white))
.input("请输入预设好友电话号码", phoneNumber, (dialog, input) -> {
String inputStr=input.toString();
if (inputStr.equals("")) {
Toast.makeText(Maintabs_AActivity.this,
"内容不能为空!" + input, Toast.LENGTH_LONG).show();
} else {
if (StringUtils.checkPhoneNumber(inputStr)) {
//上传服务器
Map<String,String> map=new HashMap<String, String>();
map.put("emergencyPhone",inputStr);
net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(map);
mSocket.emit("SetInfor",jsonObject);
phoneNumber=inputStr;
setPhoneNumber(phoneNumber);
} else {
Toast.makeText(Maintabs_AActivity.this,
"请输入正确的电话号码", Toast.LENGTH_LONG).show();
}
}
})
.positiveText("确定")
.show();
}
/**
* 显示消息模板对话框
*/
public void showMessageDialog() {
new MaterialDialog.Builder(mContext)
.title("消息模板")
.inputType(InputType.TYPE_CLASS_TEXT)
.inputRangeRes(0, 80, R.color.red)
.positiveColor(getResources().getColor(R.color.white))
.negativeColor(getResources().getColor(R.color.white))
.backgroundColor(getResources().getColor(R.color.colorPrimary))
.titleColor(getResources().getColor(R.color.white))
.contentColor(getResources().getColor(R.color.white))
.input("请输入消息模板", messageText, (dialog, input) -> {
String inputStr=input.toString();
if (inputStr.equals("")) {
Toast.makeText(Maintabs_AActivity.this,
"内容不能为空!" + input, Toast.LENGTH_LONG).show();
} else {
/*设置上传服务器*/
Map<String,String> map=new HashMap<String, String>();
map.put("msgTemplate",inputStr);
net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(map);
mSocket.emit("SetInfor",jsonObject);
messageText=inputStr;
setMessageText(messageText);
}
})
.positiveText("确定")
.show();
}
private void setPhoneNumber(String Number) {
//更新数据库字段
DBUtils.getInstance(this).updateUserInfo("phoneNumber",Number, spUserName);
}
private void setMessageText(String Number) {
//更新 <SUF>
DBUtils.getInstance(this).updateUserInfo("messageText",Number, spUserName);
}
}
| 1 | 9 | 1 |
31079_5 | package chapter07;
public class Object01 {
public static void main(String[] args) {
/**
* 1. 类是抽象的,概念的,代表一类事物,比如人类、猫类,即它是数据类型
* 2. 对象是具体的,实际的,代表一个具体事物,即实例
* 3. 类是对象的模板,对象是类的一个个体,对应一个实例
*/
// 使用OOP面向对象解决,实例化一只猫
// 1. new Cat() 创建一只猫
// 2. Cat cat1 = new Cat(); 把创建的猫赋值给 cat1
Cat cat1 = new Cat();
cat1.name = "小白";
cat1.age = 3;
cat1.color = "橘色";
cat1.weight = 6.;
// 创建第二只猫
Cat cat2 = new Cat();
cat2.name = "小花";
cat2.age = 100;
cat2.color = "花色";
cat2.weight = 15.;
// 怎么使用对象的属性
System.out.println("第一只猫信息:" + cat1.name + " "
+ cat1.age + " " + cat1.color);
// 对象在内存中的存在形式
// 类、数组、接口、String都是引用类型
}
}
// 使用面向对象的方式
// 定义一个猫类 Cat
class Cat {
// 属性,也叫成员变量,字段field
String name;
int age;
String color;
double weight;
String[] master; // 属性可以是基本数据类型,也可以是引用类型(对象,数组)
// 行为
} | CharlieHon/Java-base | chapter07/Object01.java | 402 | // 怎么使用对象的属性 | line_comment | zh-cn | package chapter07;
public class Object01 {
public static void main(String[] args) {
/**
* 1. 类是抽象的,概念的,代表一类事物,比如人类、猫类,即它是数据类型
* 2. 对象是具体的,实际的,代表一个具体事物,即实例
* 3. 类是对象的模板,对象是类的一个个体,对应一个实例
*/
// 使用OOP面向对象解决,实例化一只猫
// 1. new Cat() 创建一只猫
// 2. Cat cat1 = new Cat(); 把创建的猫赋值给 cat1
Cat cat1 = new Cat();
cat1.name = "小白";
cat1.age = 3;
cat1.color = "橘色";
cat1.weight = 6.;
// 创建第二只猫
Cat cat2 = new Cat();
cat2.name = "小花";
cat2.age = 100;
cat2.color = "花色";
cat2.weight = 15.;
// 怎么 <SUF>
System.out.println("第一只猫信息:" + cat1.name + " "
+ cat1.age + " " + cat1.color);
// 对象在内存中的存在形式
// 类、数组、接口、String都是引用类型
}
}
// 使用面向对象的方式
// 定义一个猫类 Cat
class Cat {
// 属性,也叫成员变量,字段field
String name;
int age;
String color;
double weight;
String[] master; // 属性可以是基本数据类型,也可以是引用类型(对象,数组)
// 行为
} | 1 | 12 | 1 |
31393_5 | package com.entity;
public class ToFocus {
private int id;//Id自增
private int userId;//用户ID
private int userType;//用户类型(1:医生2:用户)
private int type;//关注类型(1:医生2:药品)
private int typeId;//关注对象Id
private String img;//展示图片
private String name;//名称
private String more;//介绍
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMore() {
return more;
}
public void setMore(String more) {
this.more = more;
}
}
| Charlottenpl/onepill_service | src/main/java/com/entity/ToFocus.java | 353 | //展示图片 | line_comment | zh-cn | package com.entity;
public class ToFocus {
private int id;//Id自增
private int userId;//用户ID
private int userType;//用户类型(1:医生2:用户)
private int type;//关注类型(1:医生2:药品)
private int typeId;//关注对象Id
private String img;//展示 <SUF>
private String name;//名称
private String more;//介绍
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMore() {
return more;
}
public void setMore(String more) {
this.more = more;
}
}
| 1 | 6 | 1 |
37338_3 | package com.charmingwong.hoopsports.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.charmingwong.hoopsports.R;
import com.charmingwong.hoopsports.activity.WebActivity;
import com.charmingwong.hoopsports.config.Data;
import com.charmingwong.hoopsports.entity.footballgame.Sheshoubang;
import com.charmingwong.hoopsports.entity.footballgame.Views;
import com.charmingwong.hoopsports.utils.BitmapUtils;
import java.util.List;
import java.util.Map;
/**
* Created by 56223 on 2017/3/8.
*/
public class FootballShooterRankingAdapter extends BaseAdapter {
private Context mContext;
private List<Sheshoubang> mData;
public FootballShooterRankingAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
mData = parseData(Data.footballGameData);
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Sheshoubang sheshoubang = mData.get(position);
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_shooter_ranking, parent, false);
holder.ranking = (TextView) convertView.findViewById(R.id.ranking);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.teamName = (TextView) convertView.findViewById(R.id.team_name);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.count = (TextView) convertView.findViewById(R.id.count);
holder.dCount = (TextView) convertView.findViewById(R.id.d_count);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, WebActivity.class);
switch (v.getId()) {
case R.id.name:
intent.setData(Uri.parse(sheshoubang.getC2L()));
mContext.startActivity(intent);
return;
case R.id.team_name:
case R.id.icon:
intent.setData(Uri.parse(sheshoubang.getC3L()));
mContext.startActivity(intent);
}
}
};
holder.icon.setOnClickListener(listener);
holder.teamName.setOnClickListener(listener);
holder.name.setOnClickListener(listener);
holder.icon.setImageBitmap(BitmapUtils.compressBitmapByResId(mContext, getTeamImageId(sheshoubang.getC3())));
holder.ranking.setText(sheshoubang.getC1());
holder.name.setText(sheshoubang.getC2());
holder.teamName.setText(sheshoubang.getC3());
holder.count.setText(sheshoubang.getC4());
holder.dCount.setText(sheshoubang.getC5());
return convertView;
}
/**
* 解析成填充列表项的数据
*
* @param data 注入的原始数据
* @return 列表项数据
*/
private List<Sheshoubang> parseData(Map<String, Object> data) {
Views views = (Views) data.get("list");
return views.getSheshoubang();
}
/**
* 根据球队名获取球队 icon id
*
* @param team 球队名
* @return 球队 icon id
*/
private int getTeamImageId(String team) {
switch (team) {
//英超
case "切尔西":
return R.drawable.yc_qex;
case "热刺":
return R.drawable.yc_rc;
case "利物浦":
return R.drawable.yc_lwp;
case "曼城":
return R.drawable.yc_mc;
case "阿森纳":
return R.drawable.yc_asn;
case "曼联":
return R.drawable.yc_ml;
case "埃弗顿":
return R.drawable.yc_afd;
case "西布朗":
return R.drawable.yc_xblwq;
case "斯托克城":
return R.drawable.yc_stkc;
case "南安普敦":
return R.drawable.yc_nadp;
case "西汉姆联":
return R.drawable.yc_xhml;
case "伯恩利":
return R.drawable.yc_bel;
case "沃特福德":
return R.drawable.yc_wtfd;
case "伯恩茅斯":
return R.drawable.yc_bems;
case "莱斯特":
return R.drawable.yc_lst;
case "斯旺西":
return R.drawable.yc_swx;
case "水晶宫":
return R.drawable.yc_sjg;
case "米德尔斯堡":
return R.drawable.yc_mdesb;
case "赫尔城":
return R.drawable.yc_hec;
case "桑德兰":
return R.drawable.yc_sdl;
//西甲
case "巴塞罗那":
return R.drawable.xj_bsln;
case "皇家马德里":
return R.drawable.xj_hjmdl;
case "塞维利亚":
return R.drawable.xj_swly;
case "皇家社会":
return R.drawable.xj_hjsh;
case "马德里竞技":
return R.drawable.xj_mdljj;
case "比利亚雷亚尔":
return R.drawable.xj_blylye;
case "埃瓦尔":
return R.drawable.xj_awe;
case "毕尔巴鄂竞技":
return R.drawable.xj_bebe;
case "西班牙人":
return R.drawable.xj_xbyr;
case "维戈塞尔塔":
return R.drawable.xj_wgset;
case "阿拉维斯":
return R.drawable.xj_alws;
case "拉斯帕尔马斯":
return R.drawable.xj_lspem;
case "瓦伦西亚":
return R.drawable.xj_wlxy;
case "皇家贝蒂斯":
return R.drawable.xj_hjbds;
case "马拉加":
return R.drawable.xj_mlj;
case "莱加内斯":
return R.drawable.xj_ljls;
case "拉科鲁尼亚":
return R.drawable.xj_lklny;
case "格拉纳达":
return R.drawable.xj_glnd;
case "希洪竞技":
return R.drawable.xj_xhjj;
case "奥萨苏纳":
return R.drawable.xj_assn;
//意甲
case "尤文图斯":
return R.drawable.yj_ywts;
case "罗马":
return R.drawable.yj_lm;
case "那不勒斯":
return R.drawable.yj_nbls;
case "亚特兰大":
return R.drawable.yj_ytld;
case "拉齐奥":
return R.drawable.yj_lqa;
case "AC米兰":
return R.drawable.yj_acml;
case "国际米兰":
return R.drawable.yj_gjml;
case "佛罗伦萨":
return R.drawable.yj_flls;
case "桑普多利亚":
return R.drawable.yj_spdly;
case "都灵":
return R.drawable.yj_dl;
case "切沃":
return R.drawable.yj_qw;
case "萨索洛":
return R.drawable.yj_ssl;
case "卡利亚里":
return R.drawable.yj_klyl;
case "乌迪内斯":
return R.drawable.yj_wdns;
case "博洛尼亚":
return R.drawable.yj_blny;
case "热那亚":
return R.drawable.yj_rny;
case "恩波利":
return R.drawable.yj_ebl;
case "巴勒莫":
return R.drawable.yj_blm;
case "克罗托内":
return R.drawable.yj_kltn;
case "佩斯卡拉":
return R.drawable.yj_pskl;
//德甲
case "拜仁慕尼黑":
return R.drawable.dj_brmnh;
case "莱比锡":
return R.drawable.dj_lbx;
case "多特蒙德":
return R.drawable.dj_dtmd;
case "霍芬海姆":
return R.drawable.dj_hfhm;
case "柏林赫塔":
return R.drawable.dj_blht;
case "法兰克福":
return R.drawable.dj_flkf;
case "科隆":
return R.drawable.dj_kl;
case "门兴":
return R.drawable.dj_mx;
case "勒沃库森":
return R.drawable.dj_lwks;
case "弗赖堡":
return R.drawable.dj_flb;
case "美因茨":
return R.drawable.dj_myc;
case "奥格斯堡":
return R.drawable.dj_agsb;
case "沙尔克04":
return R.drawable.dj_sek;
case "不莱梅":
return R.drawable.dj_ydblm;
case "沃尔夫斯堡":
return R.drawable.dj_wefsb;
case "汉堡":
return R.drawable.dj_hb;
case "因戈尔施塔特":
return R.drawable.dj_ygstt;
case "达姆施塔特":
return R.drawable.dj_dmstt;
//意甲
case "摩纳哥":
return R.drawable.fj_mng;
case "巴黎圣日耳曼":
return R.drawable.fj_blsrem;
case "尼斯":
return R.drawable.fj_ns;
case "里昂":
return R.drawable.fj_la;
case "波尔多":
return R.drawable.fj_bed;
case "圣埃蒂安":
return R.drawable.fj_sada;
case "马赛":
return R.drawable.fj_ms;
case "雷恩":
return R.drawable.fj_le;
case "昂热":
return R.drawable.fj_ar;
case "图卢兹":
return R.drawable.fj_tlz;
case "甘冈":
return R.drawable.fj_gg;
case "南特":
return R.drawable.fj_nt;
case "蒙彼利埃":
return R.drawable.fj_mbla;
case "卡昂":
return R.drawable.fj_ka;
case "梅斯":
return R.drawable.fj_ms;
case "里尔":
return R.drawable.fj_ler;
case "南锡":
return R.drawable.fj_nx;
case "第戎":
return R.drawable.fj_dr;
case "巴斯蒂亚":
return R.drawable.fj_bsdy;
case "洛里昂":
return R.drawable.fj_lla;
//中超
case "广州富力":
return R.drawable.zc_gzfl;
case "山东鲁能":
return R.drawable.zc_sdln;
case "贵州恒丰":
return R.drawable.zc_gzzc;
case "辽宁开新":
return R.drawable.zc_lnkx;
case "北京国安":
return R.drawable.zc_bjga;
case "重庆力帆":
return R.drawable.zc_cqlf;
case "广州恒大":
return R.drawable.zc_gzhd;
case "华夏幸福":
return R.drawable.zc_hxxf;
case "河北华夏":
return R.drawable.zc_hxxf;
case "河南建业":
return R.drawable.zc_hnjy;
case "江苏苏宁":
return R.drawable.zc_jssn;
case "上海上港":
return R.drawable.zc_shsg;
case "上海申花":
return R.drawable.zc_shsh;
case "延边富德":
return R.drawable.zc_ybfd;
case "天津权健":
return R.drawable.zc_tjqj;
case "天津泰达":
return R.drawable.zc_tjtd;
case "长春亚泰":
return R.drawable.zc_ccyt;
//亚太
case "水原三星":
return R.drawable.yt_sysx;
case "首尔FC":
return R.drawable.yt_sefc;
case "蔚山现代":
return R.drawable.yt_sefc;
case "济州联":
return R.drawable.yt_jzl;
case "浦和红钻":
return R.drawable.yt_phhz;
case "川崎前锋":
return R.drawable.yt_cqqf;
case "大阪钢巴":
return R.drawable.yt_dbgb;
case "鹿岛鹿角":
return R.drawable.yt_ldlj;
case "香港东方":
return R.drawable.yt_xgdf;
case "蒙通联":
return R.drawable.yt_mtl;
//其他联赛
case "圣彼得堡泽尼特":
return R.drawable.other_sbdbznt;
case "波尔图":
return R.drawable.other_bet;
case "根特":
return R.drawable.other_gt;
case "罗斯托夫":
return R.drawable.other_lstf;
case "阿尔克马尔":
return R.drawable.other_aekme;
case "基辅迪纳摩":
return R.drawable.other_jfdnm;
case "莫斯科火车头":
return R.drawable.other_mskhct;
case "克拉斯诺达尔":
return R.drawable.other_klsnde;
case "阿德莱德联":
return R.drawable.other_adldl;
case "西悉尼流浪者":
return R.drawable.other_xxnllz;
case "布里斯班狮吼":
return R.drawable.other_blsbsh;
case "墨尔本胜利":
return R.drawable.other_mebsl;
default:
return 0;
}
}
static class ViewHolder {
ImageView icon;
TextView ranking, name, teamName, count, dCount;
}
}
| CharmingW/HoopSports | app/src/main/java/com/charmingwong/hoopsports/adapter/FootballShooterRankingAdapter.java | 3,825 | //其他联赛 | line_comment | zh-cn | package com.charmingwong.hoopsports.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.charmingwong.hoopsports.R;
import com.charmingwong.hoopsports.activity.WebActivity;
import com.charmingwong.hoopsports.config.Data;
import com.charmingwong.hoopsports.entity.footballgame.Sheshoubang;
import com.charmingwong.hoopsports.entity.footballgame.Views;
import com.charmingwong.hoopsports.utils.BitmapUtils;
import java.util.List;
import java.util.Map;
/**
* Created by 56223 on 2017/3/8.
*/
public class FootballShooterRankingAdapter extends BaseAdapter {
private Context mContext;
private List<Sheshoubang> mData;
public FootballShooterRankingAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
mData = parseData(Data.footballGameData);
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Sheshoubang sheshoubang = mData.get(position);
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_shooter_ranking, parent, false);
holder.ranking = (TextView) convertView.findViewById(R.id.ranking);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.teamName = (TextView) convertView.findViewById(R.id.team_name);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.count = (TextView) convertView.findViewById(R.id.count);
holder.dCount = (TextView) convertView.findViewById(R.id.d_count);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, WebActivity.class);
switch (v.getId()) {
case R.id.name:
intent.setData(Uri.parse(sheshoubang.getC2L()));
mContext.startActivity(intent);
return;
case R.id.team_name:
case R.id.icon:
intent.setData(Uri.parse(sheshoubang.getC3L()));
mContext.startActivity(intent);
}
}
};
holder.icon.setOnClickListener(listener);
holder.teamName.setOnClickListener(listener);
holder.name.setOnClickListener(listener);
holder.icon.setImageBitmap(BitmapUtils.compressBitmapByResId(mContext, getTeamImageId(sheshoubang.getC3())));
holder.ranking.setText(sheshoubang.getC1());
holder.name.setText(sheshoubang.getC2());
holder.teamName.setText(sheshoubang.getC3());
holder.count.setText(sheshoubang.getC4());
holder.dCount.setText(sheshoubang.getC5());
return convertView;
}
/**
* 解析成填充列表项的数据
*
* @param data 注入的原始数据
* @return 列表项数据
*/
private List<Sheshoubang> parseData(Map<String, Object> data) {
Views views = (Views) data.get("list");
return views.getSheshoubang();
}
/**
* 根据球队名获取球队 icon id
*
* @param team 球队名
* @return 球队 icon id
*/
private int getTeamImageId(String team) {
switch (team) {
//英超
case "切尔西":
return R.drawable.yc_qex;
case "热刺":
return R.drawable.yc_rc;
case "利物浦":
return R.drawable.yc_lwp;
case "曼城":
return R.drawable.yc_mc;
case "阿森纳":
return R.drawable.yc_asn;
case "曼联":
return R.drawable.yc_ml;
case "埃弗顿":
return R.drawable.yc_afd;
case "西布朗":
return R.drawable.yc_xblwq;
case "斯托克城":
return R.drawable.yc_stkc;
case "南安普敦":
return R.drawable.yc_nadp;
case "西汉姆联":
return R.drawable.yc_xhml;
case "伯恩利":
return R.drawable.yc_bel;
case "沃特福德":
return R.drawable.yc_wtfd;
case "伯恩茅斯":
return R.drawable.yc_bems;
case "莱斯特":
return R.drawable.yc_lst;
case "斯旺西":
return R.drawable.yc_swx;
case "水晶宫":
return R.drawable.yc_sjg;
case "米德尔斯堡":
return R.drawable.yc_mdesb;
case "赫尔城":
return R.drawable.yc_hec;
case "桑德兰":
return R.drawable.yc_sdl;
//西甲
case "巴塞罗那":
return R.drawable.xj_bsln;
case "皇家马德里":
return R.drawable.xj_hjmdl;
case "塞维利亚":
return R.drawable.xj_swly;
case "皇家社会":
return R.drawable.xj_hjsh;
case "马德里竞技":
return R.drawable.xj_mdljj;
case "比利亚雷亚尔":
return R.drawable.xj_blylye;
case "埃瓦尔":
return R.drawable.xj_awe;
case "毕尔巴鄂竞技":
return R.drawable.xj_bebe;
case "西班牙人":
return R.drawable.xj_xbyr;
case "维戈塞尔塔":
return R.drawable.xj_wgset;
case "阿拉维斯":
return R.drawable.xj_alws;
case "拉斯帕尔马斯":
return R.drawable.xj_lspem;
case "瓦伦西亚":
return R.drawable.xj_wlxy;
case "皇家贝蒂斯":
return R.drawable.xj_hjbds;
case "马拉加":
return R.drawable.xj_mlj;
case "莱加内斯":
return R.drawable.xj_ljls;
case "拉科鲁尼亚":
return R.drawable.xj_lklny;
case "格拉纳达":
return R.drawable.xj_glnd;
case "希洪竞技":
return R.drawable.xj_xhjj;
case "奥萨苏纳":
return R.drawable.xj_assn;
//意甲
case "尤文图斯":
return R.drawable.yj_ywts;
case "罗马":
return R.drawable.yj_lm;
case "那不勒斯":
return R.drawable.yj_nbls;
case "亚特兰大":
return R.drawable.yj_ytld;
case "拉齐奥":
return R.drawable.yj_lqa;
case "AC米兰":
return R.drawable.yj_acml;
case "国际米兰":
return R.drawable.yj_gjml;
case "佛罗伦萨":
return R.drawable.yj_flls;
case "桑普多利亚":
return R.drawable.yj_spdly;
case "都灵":
return R.drawable.yj_dl;
case "切沃":
return R.drawable.yj_qw;
case "萨索洛":
return R.drawable.yj_ssl;
case "卡利亚里":
return R.drawable.yj_klyl;
case "乌迪内斯":
return R.drawable.yj_wdns;
case "博洛尼亚":
return R.drawable.yj_blny;
case "热那亚":
return R.drawable.yj_rny;
case "恩波利":
return R.drawable.yj_ebl;
case "巴勒莫":
return R.drawable.yj_blm;
case "克罗托内":
return R.drawable.yj_kltn;
case "佩斯卡拉":
return R.drawable.yj_pskl;
//德甲
case "拜仁慕尼黑":
return R.drawable.dj_brmnh;
case "莱比锡":
return R.drawable.dj_lbx;
case "多特蒙德":
return R.drawable.dj_dtmd;
case "霍芬海姆":
return R.drawable.dj_hfhm;
case "柏林赫塔":
return R.drawable.dj_blht;
case "法兰克福":
return R.drawable.dj_flkf;
case "科隆":
return R.drawable.dj_kl;
case "门兴":
return R.drawable.dj_mx;
case "勒沃库森":
return R.drawable.dj_lwks;
case "弗赖堡":
return R.drawable.dj_flb;
case "美因茨":
return R.drawable.dj_myc;
case "奥格斯堡":
return R.drawable.dj_agsb;
case "沙尔克04":
return R.drawable.dj_sek;
case "不莱梅":
return R.drawable.dj_ydblm;
case "沃尔夫斯堡":
return R.drawable.dj_wefsb;
case "汉堡":
return R.drawable.dj_hb;
case "因戈尔施塔特":
return R.drawable.dj_ygstt;
case "达姆施塔特":
return R.drawable.dj_dmstt;
//意甲
case "摩纳哥":
return R.drawable.fj_mng;
case "巴黎圣日耳曼":
return R.drawable.fj_blsrem;
case "尼斯":
return R.drawable.fj_ns;
case "里昂":
return R.drawable.fj_la;
case "波尔多":
return R.drawable.fj_bed;
case "圣埃蒂安":
return R.drawable.fj_sada;
case "马赛":
return R.drawable.fj_ms;
case "雷恩":
return R.drawable.fj_le;
case "昂热":
return R.drawable.fj_ar;
case "图卢兹":
return R.drawable.fj_tlz;
case "甘冈":
return R.drawable.fj_gg;
case "南特":
return R.drawable.fj_nt;
case "蒙彼利埃":
return R.drawable.fj_mbla;
case "卡昂":
return R.drawable.fj_ka;
case "梅斯":
return R.drawable.fj_ms;
case "里尔":
return R.drawable.fj_ler;
case "南锡":
return R.drawable.fj_nx;
case "第戎":
return R.drawable.fj_dr;
case "巴斯蒂亚":
return R.drawable.fj_bsdy;
case "洛里昂":
return R.drawable.fj_lla;
//中超
case "广州富力":
return R.drawable.zc_gzfl;
case "山东鲁能":
return R.drawable.zc_sdln;
case "贵州恒丰":
return R.drawable.zc_gzzc;
case "辽宁开新":
return R.drawable.zc_lnkx;
case "北京国安":
return R.drawable.zc_bjga;
case "重庆力帆":
return R.drawable.zc_cqlf;
case "广州恒大":
return R.drawable.zc_gzhd;
case "华夏幸福":
return R.drawable.zc_hxxf;
case "河北华夏":
return R.drawable.zc_hxxf;
case "河南建业":
return R.drawable.zc_hnjy;
case "江苏苏宁":
return R.drawable.zc_jssn;
case "上海上港":
return R.drawable.zc_shsg;
case "上海申花":
return R.drawable.zc_shsh;
case "延边富德":
return R.drawable.zc_ybfd;
case "天津权健":
return R.drawable.zc_tjqj;
case "天津泰达":
return R.drawable.zc_tjtd;
case "长春亚泰":
return R.drawable.zc_ccyt;
//亚太
case "水原三星":
return R.drawable.yt_sysx;
case "首尔FC":
return R.drawable.yt_sefc;
case "蔚山现代":
return R.drawable.yt_sefc;
case "济州联":
return R.drawable.yt_jzl;
case "浦和红钻":
return R.drawable.yt_phhz;
case "川崎前锋":
return R.drawable.yt_cqqf;
case "大阪钢巴":
return R.drawable.yt_dbgb;
case "鹿岛鹿角":
return R.drawable.yt_ldlj;
case "香港东方":
return R.drawable.yt_xgdf;
case "蒙通联":
return R.drawable.yt_mtl;
//其他 <SUF>
case "圣彼得堡泽尼特":
return R.drawable.other_sbdbznt;
case "波尔图":
return R.drawable.other_bet;
case "根特":
return R.drawable.other_gt;
case "罗斯托夫":
return R.drawable.other_lstf;
case "阿尔克马尔":
return R.drawable.other_aekme;
case "基辅迪纳摩":
return R.drawable.other_jfdnm;
case "莫斯科火车头":
return R.drawable.other_mskhct;
case "克拉斯诺达尔":
return R.drawable.other_klsnde;
case "阿德莱德联":
return R.drawable.other_adldl;
case "西悉尼流浪者":
return R.drawable.other_xxnllz;
case "布里斯班狮吼":
return R.drawable.other_blsbsh;
case "墨尔本胜利":
return R.drawable.other_mebsl;
default:
return 0;
}
}
static class ViewHolder {
ImageView icon;
TextView ranking, name, teamName, count, dCount;
}
}
| 0 | 6 | 0 |
57828_5 | ZookeeperServerMain类:
protected void initializeAndRun(String[] args) throws ConfigException, IOException {
try {
ManagedUtil.registerLog4jMBeans();
} catch (JMException e) {
LOG.warn("Unable to register log4j JMX control", e);
}
ServerConfig config = new ServerConfig();
if (args.length == 1) {
config.parse(args[0]);
} else {
config.parse(args);
}
runFromConfig(config);
}
/**
* 1.从配置文件zoo.cfg读取信息
*/
public void parse(String path) throws ConfigException {
QuorumPeerConfig config = new QuorumPeerConfig();
config.parse(path);
readFrom(config);
}
public void parse(String path) throws ConfigException {
File configFile = new File(path);
LOG.info("Reading configuration from: " + configFile);
try {
if (!configFile.exists()) {
throw new IllegalArgumentException(configFile.toString() + " file is missing");
}
Properties cfg = new Properties();
FileInputStream in = new FileInputStream(configFile);
try {
cfg.load(in);
} finally {
in.close();
}
parseProperties(cfg);
} catch (IOException e) {
throw new ConfigException("Error processing " + path, e);
} catch (IllegalArgumentException e) {
throw new ConfigException("Error processing " + path, e);
}
}
/**
* 启动
*/
public void runFromConfig(ServerConfig config) throws IOException {
LOG.info("Starting server");
FileTxnSnapLog txnLog = null;
try {
// 创建ZookeeperServer对象,并将读取的配置信息赋给ZookeeperServer的属性
ZooKeeperServer zkServer = new ZooKeeperServer();
txnLog = new FileTxnSnapLog(new File(config.dataLogDir), new File(config.dataDir));
zkServer.setTxnLogFactory(txnLog);
zkServer.setTickTime(config.tickTime);
zkServer.setMinSessionTimeout(config.minSessionTimeout);
zkServer.setMaxSessionTimeout(config.maxSessionTimeout);
// 默认创建得到NIOServerCnxnFactory类的实例
cnxnFactory = ServerCnxnFactory.createFactory();
/**
* 创建ServerSocketChannel实例,注册到Selector上,感兴趣的操作为accept
*/
cnxnFactory.configure(config.getClientPortAddress(),config.getMaxClientCnxns());
cnxnFactory.startup(zkServer);
cnxnFactory.join();
if (zkServer.isRunning()) {
zkServer.shutdown();
}
} catch (InterruptedException e) {
LOG.warn("Server interrupted", e);
} finally {
if (txnLog != null) {
txnLog.close();
}
}
}
public void startup(ZooKeeperServer zks) throws IOException,InterruptedException {
/**
* 2.启动IO主线程
*/
start();
/**
* 3.从log和snapshot恢复database和session
*/
zks.startdata();
/**
* 4.启动sessionTracker线程,初始化IO请求的处理链,并启动每个processor线程
*/
zks.startup();
setZooKeeperServer(zks);
}
public void run() {
while (!ss.socket().isClosed()) {
try {
selector.select(1000);
Set<SelectionKey> selected;
synchronized (this) {
selected = selector.selectedKeys();
}
ArrayList<SelectionKey> selectedList = new ArrayList<SelectionKey>(selected);
Collections.shuffle(selectedList);
for (SelectionKey k : selectedList) {
if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) {
SocketChannel sc = ((ServerSocketChannel) k .channel()).accept();
InetAddress ia = sc.socket().getInetAddress();
int cnxncount = getClientCnxnCount(ia);
if (maxClientCnxns > 0 && cnxncount >= maxClientCnxns){
LOG.warn("Too many connections from " + ia + " - max is " + maxClientCnxns );
sc.close();
} else {
LOG.info("Accepted socket connection from " + sc.socket().getRemoteSocketAddress());
sc.configureBlocking(false);
SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
/**
* 根据sc和sk创建NIOServerCnxn对象,并将它绑定到sk上
* 这样以后发生了读写操作时,都是调用NIOServerCnxn类里的doIO()方法进行处理
*/
NIOServerCnxn cnxn = createConnection(sc, sk);
sk.attach(cnxn);
addCnxn(cnxn);
}
} else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) {
NIOServerCnxn c = (NIOServerCnxn) k.attachment();
c.doIO(k);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Unexpected ops in select " + k.readyOps());
}
}
}
selected.clear();
} catch (RuntimeException e) {
LOG.warn("Ignoring unexpected runtime exception", e);
} catch (Exception e) {
LOG.warn("Ignoring exception", e);
}
}
closeAll();
LOG.info("NIOServerCnxn factory exited run method");
}
public void startdata() throws IOException, InterruptedException {
if (zkDb == null) {
zkDb = new ZKDatabase(this.txnLogFactory);
}
if (!zkDb.isInitialized()) {
loadData();
}
}
// '/','/zookeeper','/zookeeper/quota'3个系统节点初始化
public DataTree() {
nodes.put("", root);
nodes.put(rootZookeeper, root);
root.addChild(procChildZookeeper);
nodes.put(procZookeeper, procDataNode);
procDataNode.addChild(quotaChildZookeeper);
nodes.put(quotaZookeeper, quotaDataNode);
}
/**
* Restore sessions and data
*/
public void loadData() throws IOException, InterruptedException {
// 执行恢复,并返回最新的事务ID
if(zkDb.isInitialized()){
setZxid(zkDb.getDataTreeLastProcessedZxid());
}
else {
setZxid(zkDb.loadDataBase());
}
// 清理session
LinkedList<Long> deadSessions = new LinkedList<Long>();
for (Long session : zkDb.getSessions()) {
if (zkDb.getSessionWithTimeOuts().get(session) == null) {
deadSessions.add(session);
}
}
zkDb.setDataTreeInit(true);
for (long session : deadSessions) {
killSession(session, zkDb.getDataTreeLastProcessedZxid());
}
}
<-------结束了----->
| ChaseSuccesser/Zookeeper-SourceAnalysis | 001.zookeeper启动.java | 1,585 | /**
* 2.启动IO主线程
*/ | block_comment | zh-cn | ZookeeperServerMain类:
protected void initializeAndRun(String[] args) throws ConfigException, IOException {
try {
ManagedUtil.registerLog4jMBeans();
} catch (JMException e) {
LOG.warn("Unable to register log4j JMX control", e);
}
ServerConfig config = new ServerConfig();
if (args.length == 1) {
config.parse(args[0]);
} else {
config.parse(args);
}
runFromConfig(config);
}
/**
* 1.从配置文件zoo.cfg读取信息
*/
public void parse(String path) throws ConfigException {
QuorumPeerConfig config = new QuorumPeerConfig();
config.parse(path);
readFrom(config);
}
public void parse(String path) throws ConfigException {
File configFile = new File(path);
LOG.info("Reading configuration from: " + configFile);
try {
if (!configFile.exists()) {
throw new IllegalArgumentException(configFile.toString() + " file is missing");
}
Properties cfg = new Properties();
FileInputStream in = new FileInputStream(configFile);
try {
cfg.load(in);
} finally {
in.close();
}
parseProperties(cfg);
} catch (IOException e) {
throw new ConfigException("Error processing " + path, e);
} catch (IllegalArgumentException e) {
throw new ConfigException("Error processing " + path, e);
}
}
/**
* 启动
*/
public void runFromConfig(ServerConfig config) throws IOException {
LOG.info("Starting server");
FileTxnSnapLog txnLog = null;
try {
// 创建ZookeeperServer对象,并将读取的配置信息赋给ZookeeperServer的属性
ZooKeeperServer zkServer = new ZooKeeperServer();
txnLog = new FileTxnSnapLog(new File(config.dataLogDir), new File(config.dataDir));
zkServer.setTxnLogFactory(txnLog);
zkServer.setTickTime(config.tickTime);
zkServer.setMinSessionTimeout(config.minSessionTimeout);
zkServer.setMaxSessionTimeout(config.maxSessionTimeout);
// 默认创建得到NIOServerCnxnFactory类的实例
cnxnFactory = ServerCnxnFactory.createFactory();
/**
* 创建ServerSocketChannel实例,注册到Selector上,感兴趣的操作为accept
*/
cnxnFactory.configure(config.getClientPortAddress(),config.getMaxClientCnxns());
cnxnFactory.startup(zkServer);
cnxnFactory.join();
if (zkServer.isRunning()) {
zkServer.shutdown();
}
} catch (InterruptedException e) {
LOG.warn("Server interrupted", e);
} finally {
if (txnLog != null) {
txnLog.close();
}
}
}
public void startup(ZooKeeperServer zks) throws IOException,InterruptedException {
/**
* 2.启 <SUF>*/
start();
/**
* 3.从log和snapshot恢复database和session
*/
zks.startdata();
/**
* 4.启动sessionTracker线程,初始化IO请求的处理链,并启动每个processor线程
*/
zks.startup();
setZooKeeperServer(zks);
}
public void run() {
while (!ss.socket().isClosed()) {
try {
selector.select(1000);
Set<SelectionKey> selected;
synchronized (this) {
selected = selector.selectedKeys();
}
ArrayList<SelectionKey> selectedList = new ArrayList<SelectionKey>(selected);
Collections.shuffle(selectedList);
for (SelectionKey k : selectedList) {
if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) {
SocketChannel sc = ((ServerSocketChannel) k .channel()).accept();
InetAddress ia = sc.socket().getInetAddress();
int cnxncount = getClientCnxnCount(ia);
if (maxClientCnxns > 0 && cnxncount >= maxClientCnxns){
LOG.warn("Too many connections from " + ia + " - max is " + maxClientCnxns );
sc.close();
} else {
LOG.info("Accepted socket connection from " + sc.socket().getRemoteSocketAddress());
sc.configureBlocking(false);
SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
/**
* 根据sc和sk创建NIOServerCnxn对象,并将它绑定到sk上
* 这样以后发生了读写操作时,都是调用NIOServerCnxn类里的doIO()方法进行处理
*/
NIOServerCnxn cnxn = createConnection(sc, sk);
sk.attach(cnxn);
addCnxn(cnxn);
}
} else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) {
NIOServerCnxn c = (NIOServerCnxn) k.attachment();
c.doIO(k);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Unexpected ops in select " + k.readyOps());
}
}
}
selected.clear();
} catch (RuntimeException e) {
LOG.warn("Ignoring unexpected runtime exception", e);
} catch (Exception e) {
LOG.warn("Ignoring exception", e);
}
}
closeAll();
LOG.info("NIOServerCnxn factory exited run method");
}
public void startdata() throws IOException, InterruptedException {
if (zkDb == null) {
zkDb = new ZKDatabase(this.txnLogFactory);
}
if (!zkDb.isInitialized()) {
loadData();
}
}
// '/','/zookeeper','/zookeeper/quota'3个系统节点初始化
public DataTree() {
nodes.put("", root);
nodes.put(rootZookeeper, root);
root.addChild(procChildZookeeper);
nodes.put(procZookeeper, procDataNode);
procDataNode.addChild(quotaChildZookeeper);
nodes.put(quotaZookeeper, quotaDataNode);
}
/**
* Restore sessions and data
*/
public void loadData() throws IOException, InterruptedException {
// 执行恢复,并返回最新的事务ID
if(zkDb.isInitialized()){
setZxid(zkDb.getDataTreeLastProcessedZxid());
}
else {
setZxid(zkDb.loadDataBase());
}
// 清理session
LinkedList<Long> deadSessions = new LinkedList<Long>();
for (Long session : zkDb.getSessions()) {
if (zkDb.getSessionWithTimeOuts().get(session) == null) {
deadSessions.add(session);
}
}
zkDb.setDataTreeInit(true);
for (long session : deadSessions) {
killSession(session, zkDb.getDataTreeLastProcessedZxid());
}
}
<-------结束了----->
| 1 | 36 | 1 |
22548_11 | package com.sicnu.cheer.generalmodule.bean;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
* 登录信息
* Created by cheer on 2016/11/7.
*/
public class LoginInfo implements Serializable {
private String office;//办公室
private String birthday;//生日
private String sex;//性别
private String headPic;//头像相对路径
private String officePhone;//办公电话
private String checkPhone;//校验手机号
private String jobNumber;//工号
private String jobTitle;//职务
@SerializedName("username")
private String userName;//用户帐号
private String mobilePhone;//手机号码
private String token;//令牌号
private String email;//邮箱
private String userId;//用户编号
@SerializedName("realname")
private String realName;//用户真实姓名
private String qq;//QQ号码
private List<Department> departs;//用户所在部门
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public String getOfficePhone() {
return officePhone;
}
public void setOfficePhone(String officePhone) {
this.officePhone = officePhone;
}
public String getCheckPhone() {
return checkPhone;
}
public void setCheckPhone(String checkPhone) {
this.checkPhone = checkPhone;
}
public String getJobNumber() {
return jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public List<Department> getDeparts() {
return departs;
}
public void setDeparts(List<Department> departs) {
this.departs = departs;
}
}
| CheerQY/LeaugeBar_Android | generalmodule/src/main/java/com/sicnu/cheer/generalmodule/bean/LoginInfo.java | 803 | //用户所在部门 | line_comment | zh-cn | package com.sicnu.cheer.generalmodule.bean;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
* 登录信息
* Created by cheer on 2016/11/7.
*/
public class LoginInfo implements Serializable {
private String office;//办公室
private String birthday;//生日
private String sex;//性别
private String headPic;//头像相对路径
private String officePhone;//办公电话
private String checkPhone;//校验手机号
private String jobNumber;//工号
private String jobTitle;//职务
@SerializedName("username")
private String userName;//用户帐号
private String mobilePhone;//手机号码
private String token;//令牌号
private String email;//邮箱
private String userId;//用户编号
@SerializedName("realname")
private String realName;//用户真实姓名
private String qq;//QQ号码
private List<Department> departs;//用户 <SUF>
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public String getOfficePhone() {
return officePhone;
}
public void setOfficePhone(String officePhone) {
this.officePhone = officePhone;
}
public String getCheckPhone() {
return checkPhone;
}
public void setCheckPhone(String checkPhone) {
this.checkPhone = checkPhone;
}
public String getJobNumber() {
return jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public List<Department> getDeparts() {
return departs;
}
public void setDeparts(List<Department> departs) {
this.departs = departs;
}
}
| 1 | 8 | 1 |
43168_52 | package com.tqkj.retrofitrxjavahttp.otherwebsocket;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.tqkj.retrofitrxjavahttp.MainActivity;
import com.tqkj.retrofitrxjavahttp.R;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
/**
* author : CYS
* e-mail : [email protected]
* date : 2020/10/17 0:36
* desc :
* version : 1.0
*/
public class JWebSocketClientService extends Service {
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
private static final int GRAY_SERVICE_ID = 1001;
//灰色保活
public static class GrayInnerService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(GRAY_SERVICE_ID, new Notification());
stopForeground(true);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
PowerManager.WakeLock wakeLock;
@SuppressLint("InvalidWakeLockTag")
private void acquireWakeLock() {
if (null == wakeLock) {
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, "PostLocationService");
if (null != wakeLock) {
wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);//自己加的时间限制
}
}
}
//用于Activity和service通讯
public class JWebSocketClientBinder extends Binder {
public JWebSocketClientService getService() {
return JWebSocketClientService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//初始化websocket
initSocketClient();
mHandler.postDelayed(mRunnable, HEART_BEAT_RATE);//开启心跳检测
//设置service为前台服务,提高优先级
if (Build.VERSION.SDK_INT < 18) {
//Android4.3以下 ,隐藏Notification上的图标
startForeground(GRAY_SERVICE_ID, new Notification());
} else if (Build.VERSION.SDK_INT > 18 && Build.VERSION.SDK_INT < 25) {
//Android4.3 - Android7.0,隐藏Notification上的图标
Intent innerIntent = new Intent(this, GrayInnerService.class);
startService(innerIntent);
startForeground(GRAY_SERVICE_ID, new Notification());
} else {
//Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
startForeground(GRAY_SERVICE_ID, sendNotification("第一次发送的监测通知"));//这里不能直接new Notification();会因为缺少信道报错
}
acquireWakeLock();
return START_STICKY;
}
private void initSocketClient() {
Log.e("JWebSocketClientService", "正在初始化");
//URI uri = URI.create("ws://192.168.1.147:8080/examples/websocket/chat");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号
URI uri = URI.create("ws://echo.websocket.org");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Log.e("JWebSocketClientService", "收到的消息:" + message);
Intent intent = new Intent();
intent.setAction("com.tqkj.retrofitrxjavahttp.otherwebsocket.JWebSocketClientService");//待修改
intent.putExtra("message", message);
sendBroadcast(intent);//发送广播
checkLockAndShowNotification(message);//发出通知
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.e("JWebSocketClientService", "websocketOnOpen连接成功");
}
@Override
public void onError(Exception ex) {
super.onError(ex);
Log.e("JWebSocketClientService", ex.getMessage());
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
Log.e("JWebSocketClientService", reason);
}
};
connect();
}
/**
* 连接websocket
*/
private void connect() {
new Thread() {
@Override
public void run() {
try {
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
Log.e("JWebSocketClientService", "正在连接到服务器");
client.connectBlocking();
} catch (Exception e) {
e.printStackTrace();
Log.e("JWebSocketClientService", e.getMessage());
}
}
}.start();
}
/**
* * 发送消息
* *
*/
public void sendMessage(String msg) {
if (null != client) {
client.send(msg);//发送消息的服务器
//测试了好久都不起作用。(测试设备的是小米10和vivoNex)
// if (client.getReadyState().equals(ReadyState.OPEN)) {
// Log.e("JWebSocketClientService", "发送的消息:" + msg);
// client.send(msg);//发送消息的服务器
// } else {
// Log.e("JWebSocketClientService", "不处于开启状态");
// }
}
}
/**
* 断开连接
*/
private void closeConnect() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("JWebSocketClientService", e.getMessage());
} finally {
client = null;
}
}
// -----------------------------------消息通知--------------------------------------------------------
/**
* 检查锁屏状态,如果锁屏,先点亮屏幕
*
* @param message
*/
@SuppressLint("InvalidWakeLockTag")
private void checkLockAndShowNotification(String message) {
//管理锁屏的一个服务
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode()) {//锁屏
//获取电源管理器对象
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
if (!pm.isInteractive()) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
wl.acquire(10 * 60 * 1000L /*10 minutes*/); //点亮屏幕
wl.release(); //任务结束后释放
}
sendNotification(message);
} else {
sendNotification(message);
}
}
/**
* 发送通知
* 8.1以上系统开启通知闪退问题,是因为通知要添加信道才行了。
*
* @param message
*/
private Notification sendNotification(String message) {
String ChannelId = "webTestId";
String ChannelName = "webServiceTest";
NotificationChannel notificationChannel;
Notification notification;
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//添加信道以只会安卓8.1以上消息通知,创建信道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(
ChannelId, ChannelName, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);//是否显示角标
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
//描述
notificationChannel.setDescription("websocket");
notificationManager.createNotificationChannel(notificationChannel);
//创建通知
notification = new NotificationCompat.Builder(this, ChannelId)//必须添加信道id
.setAutoCancel(true)
// 设置该通知优先级
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher_background)//在android8.0之后的通知没有SmallIcon也会报错。必须加上
.setContentTitle("服务器")
.setContentText(message)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
// 向通知添加声音、闪灯和振动效果
.setDefaults(Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.build();
} else {
notification = new Notification.Builder(this)
.setAutoCancel(true)
// 设置该通知优先级
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("服务器")
.setContentText(message)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
// 向通知添加声音、闪灯和振动效果
.setDefaults(Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.build();
}
//notification.flags |= Notification.FLAG_NO_CLEAR;
//通知开始唤醒
//startForeground(100001, notification);//前台通知,和下面的二取一
notificationManager.notify(100001, notification);//id要保证唯一
return notification;
}
//-------------------------------------websocket心跳检测------------------------------------------------
private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测
private final Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
@Override
public void run() {
Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
if (client != null) {
if (client.isClosed()) {
reconnectWs();
Log.e("JWebSocketClientService", "client是关闭的");
} else if (client.isOpen()) {
Log.e("JWebSocketClientService", "client是开启的");
} else if (client.isClosing()) {
Log.e("JWebSocketClientService", "client是isClosing");
} else if (client.isFlushAndClose()) {
Log.e("JWebSocketClientService", "client是isFlushAndClose");
} else if (client.isReuseAddr()) {
Log.e("JWebSocketClientService", "client是isReuseAddr");
} else if (client.isTcpNoDelay()) {
Log.e("JWebSocketClientService", "client是isTcpNoDelay");
} else {
Log.e("JWebSocketClientService", "client不知道在干吗");
}
} else {
//如果client已为空,重新初始化连接
client = null;
initSocketClient();
Log.e("JWebSocketClientService", "client是空的");
}
//每隔一定的时间,对长连接进行一次心跳检测
mHandler.postDelayed(mRunnable, HEART_BEAT_RATE);
}
};
/**
* 开启重连
*/
private void reconnectWs() {
mHandler.removeCallbacks(mRunnable);
//子线程异步
new Thread() {
@Override
public void run() {
try {
Log.e("JWebSocketClientService", "开启重连");
client.reconnectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
Log.e("JWebSocketClientService", e.getMessage());
}
}
}.start();
}
@Override
public void onDestroy() {
Log.e("JWebSocketClientService", "onDestroy");
closeConnect();
super.onDestroy();
}
public JWebSocketClientService() {
}
}
| ChenBabys/RetrofitRxJavaHttp | app/src/main/java/com/tqkj/retrofitrxjavahttp/otherwebsocket/JWebSocketClientService.java | 3,129 | //如果client已为空,重新初始化连接 | line_comment | zh-cn | package com.tqkj.retrofitrxjavahttp.otherwebsocket;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.tqkj.retrofitrxjavahttp.MainActivity;
import com.tqkj.retrofitrxjavahttp.R;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
/**
* author : CYS
* e-mail : [email protected]
* date : 2020/10/17 0:36
* desc :
* version : 1.0
*/
public class JWebSocketClientService extends Service {
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
private static final int GRAY_SERVICE_ID = 1001;
//灰色保活
public static class GrayInnerService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(GRAY_SERVICE_ID, new Notification());
stopForeground(true);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
PowerManager.WakeLock wakeLock;
@SuppressLint("InvalidWakeLockTag")
private void acquireWakeLock() {
if (null == wakeLock) {
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, "PostLocationService");
if (null != wakeLock) {
wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);//自己加的时间限制
}
}
}
//用于Activity和service通讯
public class JWebSocketClientBinder extends Binder {
public JWebSocketClientService getService() {
return JWebSocketClientService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//初始化websocket
initSocketClient();
mHandler.postDelayed(mRunnable, HEART_BEAT_RATE);//开启心跳检测
//设置service为前台服务,提高优先级
if (Build.VERSION.SDK_INT < 18) {
//Android4.3以下 ,隐藏Notification上的图标
startForeground(GRAY_SERVICE_ID, new Notification());
} else if (Build.VERSION.SDK_INT > 18 && Build.VERSION.SDK_INT < 25) {
//Android4.3 - Android7.0,隐藏Notification上的图标
Intent innerIntent = new Intent(this, GrayInnerService.class);
startService(innerIntent);
startForeground(GRAY_SERVICE_ID, new Notification());
} else {
//Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
startForeground(GRAY_SERVICE_ID, sendNotification("第一次发送的监测通知"));//这里不能直接new Notification();会因为缺少信道报错
}
acquireWakeLock();
return START_STICKY;
}
private void initSocketClient() {
Log.e("JWebSocketClientService", "正在初始化");
//URI uri = URI.create("ws://192.168.1.147:8080/examples/websocket/chat");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号
URI uri = URI.create("ws://echo.websocket.org");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Log.e("JWebSocketClientService", "收到的消息:" + message);
Intent intent = new Intent();
intent.setAction("com.tqkj.retrofitrxjavahttp.otherwebsocket.JWebSocketClientService");//待修改
intent.putExtra("message", message);
sendBroadcast(intent);//发送广播
checkLockAndShowNotification(message);//发出通知
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.e("JWebSocketClientService", "websocketOnOpen连接成功");
}
@Override
public void onError(Exception ex) {
super.onError(ex);
Log.e("JWebSocketClientService", ex.getMessage());
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
Log.e("JWebSocketClientService", reason);
}
};
connect();
}
/**
* 连接websocket
*/
private void connect() {
new Thread() {
@Override
public void run() {
try {
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
Log.e("JWebSocketClientService", "正在连接到服务器");
client.connectBlocking();
} catch (Exception e) {
e.printStackTrace();
Log.e("JWebSocketClientService", e.getMessage());
}
}
}.start();
}
/**
* * 发送消息
* *
*/
public void sendMessage(String msg) {
if (null != client) {
client.send(msg);//发送消息的服务器
//测试了好久都不起作用。(测试设备的是小米10和vivoNex)
// if (client.getReadyState().equals(ReadyState.OPEN)) {
// Log.e("JWebSocketClientService", "发送的消息:" + msg);
// client.send(msg);//发送消息的服务器
// } else {
// Log.e("JWebSocketClientService", "不处于开启状态");
// }
}
}
/**
* 断开连接
*/
private void closeConnect() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("JWebSocketClientService", e.getMessage());
} finally {
client = null;
}
}
// -----------------------------------消息通知--------------------------------------------------------
/**
* 检查锁屏状态,如果锁屏,先点亮屏幕
*
* @param message
*/
@SuppressLint("InvalidWakeLockTag")
private void checkLockAndShowNotification(String message) {
//管理锁屏的一个服务
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode()) {//锁屏
//获取电源管理器对象
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
if (!pm.isInteractive()) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
wl.acquire(10 * 60 * 1000L /*10 minutes*/); //点亮屏幕
wl.release(); //任务结束后释放
}
sendNotification(message);
} else {
sendNotification(message);
}
}
/**
* 发送通知
* 8.1以上系统开启通知闪退问题,是因为通知要添加信道才行了。
*
* @param message
*/
private Notification sendNotification(String message) {
String ChannelId = "webTestId";
String ChannelName = "webServiceTest";
NotificationChannel notificationChannel;
Notification notification;
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//添加信道以只会安卓8.1以上消息通知,创建信道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(
ChannelId, ChannelName, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);//是否显示角标
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
//描述
notificationChannel.setDescription("websocket");
notificationManager.createNotificationChannel(notificationChannel);
//创建通知
notification = new NotificationCompat.Builder(this, ChannelId)//必须添加信道id
.setAutoCancel(true)
// 设置该通知优先级
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher_background)//在android8.0之后的通知没有SmallIcon也会报错。必须加上
.setContentTitle("服务器")
.setContentText(message)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
// 向通知添加声音、闪灯和振动效果
.setDefaults(Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.build();
} else {
notification = new Notification.Builder(this)
.setAutoCancel(true)
// 设置该通知优先级
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("服务器")
.setContentText(message)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
// 向通知添加声音、闪灯和振动效果
.setDefaults(Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.build();
}
//notification.flags |= Notification.FLAG_NO_CLEAR;
//通知开始唤醒
//startForeground(100001, notification);//前台通知,和下面的二取一
notificationManager.notify(100001, notification);//id要保证唯一
return notification;
}
//-------------------------------------websocket心跳检测------------------------------------------------
private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测
private final Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
@Override
public void run() {
Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
if (client != null) {
if (client.isClosed()) {
reconnectWs();
Log.e("JWebSocketClientService", "client是关闭的");
} else if (client.isOpen()) {
Log.e("JWebSocketClientService", "client是开启的");
} else if (client.isClosing()) {
Log.e("JWebSocketClientService", "client是isClosing");
} else if (client.isFlushAndClose()) {
Log.e("JWebSocketClientService", "client是isFlushAndClose");
} else if (client.isReuseAddr()) {
Log.e("JWebSocketClientService", "client是isReuseAddr");
} else if (client.isTcpNoDelay()) {
Log.e("JWebSocketClientService", "client是isTcpNoDelay");
} else {
Log.e("JWebSocketClientService", "client不知道在干吗");
}
} else {
//如果 <SUF>
client = null;
initSocketClient();
Log.e("JWebSocketClientService", "client是空的");
}
//每隔一定的时间,对长连接进行一次心跳检测
mHandler.postDelayed(mRunnable, HEART_BEAT_RATE);
}
};
/**
* 开启重连
*/
private void reconnectWs() {
mHandler.removeCallbacks(mRunnable);
//子线程异步
new Thread() {
@Override
public void run() {
try {
Log.e("JWebSocketClientService", "开启重连");
client.reconnectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
Log.e("JWebSocketClientService", e.getMessage());
}
}
}.start();
}
@Override
public void onDestroy() {
Log.e("JWebSocketClientService", "onDestroy");
closeConnect();
super.onDestroy();
}
public JWebSocketClientService() {
}
}
| 1 | 21 | 1 |
59341_1 | package state;
/**
* 这个类可能用不到了
* @author Ann
*
*/
@Deprecated
public enum AccountType {
//还会改,比如应该是司机啊什么之类的
COURIER("快递员"),
GENERAL_MANAGER("总经理"),
INVENTORY_MANAGER("库存管理人员"),
FINANCE_MANAGER("财务人员"),
BRANCH_COUNTERMAN("营业厅业务员"),
TRANSFER_CONTERMAN("中转中心业务员"),
ADMIN("管理员"),
DRIVER("司机");
public final String value;
AccountType(String value) {
this.value = value;
}
}
| ChenErTong/SE2 | server/src/main/java/state/AccountType.java | 164 | //还会改,比如应该是司机啊什么之类的 | line_comment | zh-cn | package state;
/**
* 这个类可能用不到了
* @author Ann
*
*/
@Deprecated
public enum AccountType {
//还会 <SUF>
COURIER("快递员"),
GENERAL_MANAGER("总经理"),
INVENTORY_MANAGER("库存管理人员"),
FINANCE_MANAGER("财务人员"),
BRANCH_COUNTERMAN("营业厅业务员"),
TRANSFER_CONTERMAN("中转中心业务员"),
ADMIN("管理员"),
DRIVER("司机");
public final String value;
AccountType(String value) {
this.value = value;
}
}
| 0 | 19 | 0 |
40841_6 | /* Leetcode 241. Different Ways to Add Parentheses
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group
numbers and operators. You may return the answer in any order.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.
Example 1:
Input: expression = "2-1-1"
Output: [0,2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: expression = "2*3-4*5"
Output: [-34,-14,-10,-10,10]
Explanation:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Constraints:
1 <= expression.length <= 20
expression consists of digits and the operator '+', '-', and '*'.
All the integer values in the input expression are in the range [0, 99].
*/
/* 思路: Divide Conquer algorithm 分治 + recursion 递归
这是一道非常经典的分支题目,题意是考虑括号的位置,找出和计算所有放入一个括号之后得到的数值
类似于一个二叉树的形式,每当遇到一个符号的时候,就进行分解 Divide 同时递归
==》 if(c == '+' || c == '*' || c == '-') ==》
==》 List<Integer> leftP = diffWaysToCompute(expression.substring(0, i));//开头到符号左边
List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部
这样可以把一个长式子,不停的划分为短的,
然后再一个一个计算, 计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗)
for(int leftNumber : leftP){ for(int rightNumber : rightP){}}
==> 每次取出一个数,再根据划分时的符号 进行计算 ==》最后得到一个结果,存入list中。
当遍历完成 就能得到所有加入一个括号之后的总值
*/
//Time: O(nlogn) Space: O(n)
class Solution {
//Divide Conquer algorithm + recursion
public List<Integer> diffWaysToCompute(String expression) {
//base case
if(expression == null || expression.length() == 0){
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
//travser all the element from expression
for(int i = 0; i < expression.length(); i++){
char c = expression.charAt(i);
//当遇到任意符号的时候停止 ==> 开始进行divide(分开)
if(c == '+' || c == '*' || c == '-'){
List<Integer> leftP = diffWaysToCompute(expression.substring(0, i)); //开头到符号左边
List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部
//计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗)
for(int leftNumber : leftP){
for(int rightNumber : rightP){
//计算两边的值 和 中间的符号 ==》得到一个总的结果 然后存入res的list中
if(c == '+'){ //符号为 '+'
res.add(leftNumber + rightNumber);
}else if(c == '-'){ //符号 '-'
res.add(leftNumber - rightNumber);
}else if(c == '*'){ //符号 '*'
res.add(leftNumber * rightNumber);
}
}
}
}
}
//如果字符串中没有任何的符号存在,直接存入字符串的integer值
if(res.size() == 0){
res.add(Integer.valueOf(expression));
}
return res;
}
}
| ChenHCY/AlgorithmsQuestion | Math Question/241 Different Ways to Add Parentheses.java | 1,026 | //当遇到任意符号的时候停止 ==> 开始进行divide(分开) | line_comment | zh-cn | /* Leetcode 241. Different Ways to Add Parentheses
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group
numbers and operators. You may return the answer in any order.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.
Example 1:
Input: expression = "2-1-1"
Output: [0,2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: expression = "2*3-4*5"
Output: [-34,-14,-10,-10,10]
Explanation:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Constraints:
1 <= expression.length <= 20
expression consists of digits and the operator '+', '-', and '*'.
All the integer values in the input expression are in the range [0, 99].
*/
/* 思路: Divide Conquer algorithm 分治 + recursion 递归
这是一道非常经典的分支题目,题意是考虑括号的位置,找出和计算所有放入一个括号之后得到的数值
类似于一个二叉树的形式,每当遇到一个符号的时候,就进行分解 Divide 同时递归
==》 if(c == '+' || c == '*' || c == '-') ==》
==》 List<Integer> leftP = diffWaysToCompute(expression.substring(0, i));//开头到符号左边
List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部
这样可以把一个长式子,不停的划分为短的,
然后再一个一个计算, 计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗)
for(int leftNumber : leftP){ for(int rightNumber : rightP){}}
==> 每次取出一个数,再根据划分时的符号 进行计算 ==》最后得到一个结果,存入list中。
当遍历完成 就能得到所有加入一个括号之后的总值
*/
//Time: O(nlogn) Space: O(n)
class Solution {
//Divide Conquer algorithm + recursion
public List<Integer> diffWaysToCompute(String expression) {
//base case
if(expression == null || expression.length() == 0){
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
//travser all the element from expression
for(int i = 0; i < expression.length(); i++){
char c = expression.charAt(i);
//当遇 <SUF>
if(c == '+' || c == '*' || c == '-'){
List<Integer> leftP = diffWaysToCompute(expression.substring(0, i)); //开头到符号左边
List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部
//计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗)
for(int leftNumber : leftP){
for(int rightNumber : rightP){
//计算两边的值 和 中间的符号 ==》得到一个总的结果 然后存入res的list中
if(c == '+'){ //符号为 '+'
res.add(leftNumber + rightNumber);
}else if(c == '-'){ //符号 '-'
res.add(leftNumber - rightNumber);
}else if(c == '*'){ //符号 '*'
res.add(leftNumber * rightNumber);
}
}
}
}
}
//如果字符串中没有任何的符号存在,直接存入字符串的integer值
if(res.size() == 0){
res.add(Integer.valueOf(expression));
}
return res;
}
}
| 1 | 33 | 1 |
58280_8 | import java.util.Scanner;
import ChessMap.ChessMap;
import java.util.concurrent.TimeUnit;
import java.lang.Runtime;
import settings.AppSettings;
public class App {
public static boolean Flag = true;
public static ChessMap map = new ChessMap(AppSettings.mapSize);
public static int Languane = 0 ;
/**
* @param args 用不着;
* @throws Exception 也用不着
* 程序的入口
*/
public static void main(String[] args) throws Exception {
Languane = input("Languae:(0-EN/1-CH)");
//get runtime
Runtime rt = Runtime.getRuntime();
// 输出title
print("===", AppSettings.title[Languane] , "===\n");
// 等待3秒
for (int i = 3; i >= 0; i--) {
print(i, "\r");
TimeUnit.SECONDS.sleep(1);
}
// 变量初始化
char Iswin = map.isWin();
long startTime, endTime, usedTime;
// 主循环
while (Flag) {
Iswin = map.isWin();
/** 获取当前系统时间 */
startTime = System.currentTimeMillis();
// 输出地图,输入棋子坐标 IO
map.mapOut();
getIn('r');
// 判断是否获胜
if (Iswin != 'n') {
Flag = false;
print(Iswin);
print(AppSettings.winPrommpt[Languane]);
Flag = input(AppSettings.countinuePrompt[Languane]) == 0;
map.setUpMap();
Iswin = map.isWin();
continue;
}
// 结束计时
endTime = System.currentTimeMillis();
usedTime = (endTime - startTime) / 1000;
print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n");
startTime = System.currentTimeMillis();
// 输出地图,输入棋子坐标 IO
map.mapOut();
getIn('b');
// 判断是否获胜
if (Iswin != 'n') {
Flag = false;
print(Iswin);
print(AppSettings.winPrommpt[Languane]);
Flag = input(AppSettings.countinuePrompt[Languane]) == 0;
map.setUpMap();
Iswin = map.isWin();
continue;
}
/** 获取当前的系统时间,与初始时间相减就是程序运行的毫秒数,除以1000就是秒数 */
endTime = System.currentTimeMillis();
usedTime = (endTime - startTime) / 1000;
print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n");
}
print(AppSettings.sayGoodBye[Languane]);
Runtime.getRuntime().exec("clear");
}
/**
* @param prompt 输出一个字符串为提示
* @return 返回输入的Int数据
* 类比 python 的 input
*/
private static int input(String prompt) {
// 临时变量
int temp;
// 打印提示语
print(prompt, ":");
// 新建扫描器,输入
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
temp = scanner.nextInt();
} else {
temp = -2147483647;
}
return temp;
}
/**
* @param args 要打印的字符
* 类比 python 的 print
*/
private static void print(Object... args) {
for (Object string : args) {
System.out.print(string);
}
}
/**
* @param who 落子者
* 用来输入 x , y 坐标
*/
public static void getIn(char who) {
if (!(map.downChess(input(AppSettings.getInPrompt[Languane][0]), input(AppSettings.getInPrompt[Languane][0]), who))) {
print("\033[31m", AppSettings.getInErrorPrompt[Languane], "\n", "\033[m");
getIn(who);
return;
}
return;
}
} | ChenHongMing666/Gobang | src/App.java | 996 | // 判断是否获胜 | line_comment | zh-cn | import java.util.Scanner;
import ChessMap.ChessMap;
import java.util.concurrent.TimeUnit;
import java.lang.Runtime;
import settings.AppSettings;
public class App {
public static boolean Flag = true;
public static ChessMap map = new ChessMap(AppSettings.mapSize);
public static int Languane = 0 ;
/**
* @param args 用不着;
* @throws Exception 也用不着
* 程序的入口
*/
public static void main(String[] args) throws Exception {
Languane = input("Languae:(0-EN/1-CH)");
//get runtime
Runtime rt = Runtime.getRuntime();
// 输出title
print("===", AppSettings.title[Languane] , "===\n");
// 等待3秒
for (int i = 3; i >= 0; i--) {
print(i, "\r");
TimeUnit.SECONDS.sleep(1);
}
// 变量初始化
char Iswin = map.isWin();
long startTime, endTime, usedTime;
// 主循环
while (Flag) {
Iswin = map.isWin();
/** 获取当前系统时间 */
startTime = System.currentTimeMillis();
// 输出地图,输入棋子坐标 IO
map.mapOut();
getIn('r');
// 判断 <SUF>
if (Iswin != 'n') {
Flag = false;
print(Iswin);
print(AppSettings.winPrommpt[Languane]);
Flag = input(AppSettings.countinuePrompt[Languane]) == 0;
map.setUpMap();
Iswin = map.isWin();
continue;
}
// 结束计时
endTime = System.currentTimeMillis();
usedTime = (endTime - startTime) / 1000;
print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n");
startTime = System.currentTimeMillis();
// 输出地图,输入棋子坐标 IO
map.mapOut();
getIn('b');
// 判断是否获胜
if (Iswin != 'n') {
Flag = false;
print(Iswin);
print(AppSettings.winPrommpt[Languane]);
Flag = input(AppSettings.countinuePrompt[Languane]) == 0;
map.setUpMap();
Iswin = map.isWin();
continue;
}
/** 获取当前的系统时间,与初始时间相减就是程序运行的毫秒数,除以1000就是秒数 */
endTime = System.currentTimeMillis();
usedTime = (endTime - startTime) / 1000;
print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n");
}
print(AppSettings.sayGoodBye[Languane]);
Runtime.getRuntime().exec("clear");
}
/**
* @param prompt 输出一个字符串为提示
* @return 返回输入的Int数据
* 类比 python 的 input
*/
private static int input(String prompt) {
// 临时变量
int temp;
// 打印提示语
print(prompt, ":");
// 新建扫描器,输入
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
temp = scanner.nextInt();
} else {
temp = -2147483647;
}
return temp;
}
/**
* @param args 要打印的字符
* 类比 python 的 print
*/
private static void print(Object... args) {
for (Object string : args) {
System.out.print(string);
}
}
/**
* @param who 落子者
* 用来输入 x , y 坐标
*/
public static void getIn(char who) {
if (!(map.downChess(input(AppSettings.getInPrompt[Languane][0]), input(AppSettings.getInPrompt[Languane][0]), who))) {
print("\033[31m", AppSettings.getInErrorPrompt[Languane], "\n", "\033[m");
getIn(who);
return;
}
return;
}
} | 1 | 9 | 1 |
45313_3 | import simbad.sim.Agent;
import simbad.sim.LampActuator;
import simbad.sim.RangeSensorBelt;
import simbad.sim.RobotFactory;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector2d;
import javax.vecmath.Vector3d;
/**
* Created by jiajianchen
* on 2019/1/7
* 用于定义警察机器人
*/
public class PoliceRobot extends Agent {
RangeSensorBelt sonars;
RangeSensorBelt bumpers;
LampActuator lamp;//灯
private MyEnv ev; // 环境实例,用于获取环境中的因素
private double velocity = 0.5; // 速度
private boolean debug = false; // 调试状态
private boolean isLeader = false; // 是否为领航机器人
private Vector2d targetPoint = new Vector2d(0, 0); // 目标点
private static int freeze_time = 0;
private static Color3f mLeaderColor = new Color3f(60, 60, 60);
private static Color3f mCommonColor = new Color3f(20, 20, 20);
public PoliceRobot(Vector3d position, String name) {
super(position,name);
sonars = RobotFactory.addSonarBeltSensor(this, 8);
bumpers = RobotFactory.addBumperBeltSensor(this);
lamp = RobotFactory.addLamp(this);
setColor(new Color3f(20, 20, 20));
}
public void initBehavior() {}
void setParams(MyEnv ev, double velocity, boolean debug) {
this.ev = ev;
this.velocity = velocity;
this.debug = debug;
}
/**
* 运动算法
*/
public void performBehavior() {
if ((getCounter() % 10) == 0) {
if (isLeader)
setColor(mLeaderColor);
else
setColor(mCommonColor);
if (ev.getThiefState() == 2) {
if (debug)
System.out.println("盗贼被抓住了!!!");
setRotationalVelocity(0);
setTranslationalVelocity(0);
} else {
if (ev.getThiefState() == 0)
walkWithGoal(targetPoint);
else walkWithGoal(ev.getThiefRobot().getPosition());
}
}
}
/**
* 获取当前位置
*/
Vector2d getPosition() {
Point3d p = new Point3d();
getCoords(p);
return new Vector2d(p.z, p.x);
}
/**
* 设置领航状态
*/
void setIsLeader(boolean status) {
isLeader = status;
}
/**
* 设置目标点
*/
void setTargetPoint(Vector2d targetPoint) {
this.targetPoint = targetPoint;
}
Vector2d getTargetPoint() {
return targetPoint;
}
/**
* 判断是否长期静止
*/
private boolean isStopForLong(Vector2d pre, Vector2d cur) {
if (cur.equals(pre)) {
if (freeze_time == 30)
// 如果边界设置太小会影响正常的碰撞处理
return true;
else {
freeze_time++;
return false;
}
} else {
freeze_time = 0;
return false;
}
}
/**
* 向目标移动,避开障碍物
* 人工势场法
*/
private void walkWithGoal(Vector2d goal) {
setTranslationalVelocity(this.velocity);
// 获取速度
Vector3d velocity = this.linearVelocity;
// 获取当前运动方向
Vector2d direct = new Vector2d(velocity.z, velocity.x);
// 获取当前运动位置
Point3d p = new Point3d();
getCoords(p);
Vector2d pos = new Vector2d(p.z, p.x);
//获取三方个障碍物的距离
double d0 = sonars.getMeasurement(0);// front声纳,正前方
double d1 = sonars.getMeasurement(1);// frontleft声纳,左前方
double d2 = sonars.getMeasurement(7);// frontright声纳,右前方
// 计算三个方向障碍物的斥力
double rf0 = MyUtil.repelForce(d0);
double rf1 = MyUtil.repelForce(d1);
double rf2 = MyUtil.repelForce(d2);
//计算三个方向障碍物斥力的合力
double k1 = Math.cos(2 * Math.PI / 9);
double k2 = Math.sin(2 * Math.PI / 9);
Vector2d vf0 = new Vector2d(0 - rf0, 0);
Vector2d vf1 = new Vector2d((0 - rf1 * k1), (0 - rf1 * k2));
Vector2d vf2 = new Vector2d((rf2 * k1), (rf2 * k2));
Vector2d composition = new Vector2d();
composition.setX(vf0.x + vf1.x + vf2.x);
composition.setY(vf0.y + vf1.y + vf2.y);
if (debug)
System.out.println("(" + composition.x + ","
+ composition.y);
//给定斥力合力向量
Vector2d repelForceVector = MyUtil.transform(direct, composition);
// 计算目标的对机器人的引力
Vector2d toGoal = new Vector2d((goal.x - pos.x),
(goal.y - pos.y));
double disGoal = toGoal.length();//和目的的距离
if (debug)
System.out.println("distance to goal:" + disGoal);
double goalForce = MyUtil.attractForce(disGoal);//计算引力
if (debug)
System.out.println("attract force from goal:" + goalForce);
Vector2d goalForceVector = new Vector2d(
(goalForce * toGoal.x / disGoal),
(goalForce * toGoal.y / disGoal));
// 计算斥力和引力的合力
double x = repelForceVector.x + goalForceVector.x;
double y = repelForceVector.y + goalForceVector.y;
Vector2d allForces = new Vector2d(x, y);
if (debug) {
System.out.println("total force(" + allForces.x + ","
+ allForces.y + ")");
System.out.println("force direct(" + direct.x + ","
+ direct.y + ")");
}
// 根据合力的方向和当前运动方向的夹角来判断当前转动角度
double angle = MyUtil.getAngle(direct, allForces);
if (debug)
System.out.println("angle:" + angle);
// 判断转动方向
if (angle < Math.PI) {
setRotationalVelocity(angle);
} else if (angle > Math.PI) {
setRotationalVelocity((angle - 2 * Math.PI));
}
// 是否到达目标点
if (checkGoal(new Point3d(goal.x, 0, goal.y))) {
// 到达目标点,亮绿灯 停止运动
setTranslationalVelocity(0);
setRotationalVelocity(0);
// lamp.setOn(true);
return;
} else {
// lamp.setOn(false);
setTranslationalVelocity(0.5);
}
// 检测是否碰撞
if (bumpers.oneHasHit()) {
// 机器人身体三个方向和障碍物的距离
double left = sonars.getFrontLeftQuadrantMeasurement();
double right = sonars.getFrontRightQuadrantMeasurement();
double front = sonars.getFrontQuadrantMeasurement();
// 如果接近障碍物
if ((front < 0.7) || (left < 0.7) || (right < 0.7)) {
setTranslationalVelocity(0);
if (left < right) {
setRotationalVelocity(-1 - (0.1 * Math.random()));// 随机向右转
} else {
setRotationalVelocity(1 - (0.1 * Math.random()));// 随机向左转
}
}
}
// 判断是否一直不动
// 获取前一次运动位置
getCoords(p);
Vector2d cur_pos = new Vector2d(p.z, p.x);
if (isStopForLong(pos, cur_pos)) {
if (debug)
System.out.println(this.name + "卡住了!!!");
setTranslationalVelocity(0);
setRotationalVelocity(Math.PI);
freeze_time = 0;
}
}
/**
* 检查是否到达目标
*/
private boolean checkGoal(Point3d goal3d) {
// 当前位置
Point3d currentPos = new Point3d();
getCoords(currentPos);
Point3d goalPos = new Point3d(goal3d.x, goal3d.y, goal3d.z);
// 如果当前距离目标点小于0.5那么即认为是到达
return currentPos.distance(goalPos) <= 0.5;
}
}
| ChenJiaJian96/HuntingGame | main/src/PoliceRobot.java | 2,236 | // 是否为领航机器人 | line_comment | zh-cn | import simbad.sim.Agent;
import simbad.sim.LampActuator;
import simbad.sim.RangeSensorBelt;
import simbad.sim.RobotFactory;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector2d;
import javax.vecmath.Vector3d;
/**
* Created by jiajianchen
* on 2019/1/7
* 用于定义警察机器人
*/
public class PoliceRobot extends Agent {
RangeSensorBelt sonars;
RangeSensorBelt bumpers;
LampActuator lamp;//灯
private MyEnv ev; // 环境实例,用于获取环境中的因素
private double velocity = 0.5; // 速度
private boolean debug = false; // 调试状态
private boolean isLeader = false; // 是否 <SUF>
private Vector2d targetPoint = new Vector2d(0, 0); // 目标点
private static int freeze_time = 0;
private static Color3f mLeaderColor = new Color3f(60, 60, 60);
private static Color3f mCommonColor = new Color3f(20, 20, 20);
public PoliceRobot(Vector3d position, String name) {
super(position,name);
sonars = RobotFactory.addSonarBeltSensor(this, 8);
bumpers = RobotFactory.addBumperBeltSensor(this);
lamp = RobotFactory.addLamp(this);
setColor(new Color3f(20, 20, 20));
}
public void initBehavior() {}
void setParams(MyEnv ev, double velocity, boolean debug) {
this.ev = ev;
this.velocity = velocity;
this.debug = debug;
}
/**
* 运动算法
*/
public void performBehavior() {
if ((getCounter() % 10) == 0) {
if (isLeader)
setColor(mLeaderColor);
else
setColor(mCommonColor);
if (ev.getThiefState() == 2) {
if (debug)
System.out.println("盗贼被抓住了!!!");
setRotationalVelocity(0);
setTranslationalVelocity(0);
} else {
if (ev.getThiefState() == 0)
walkWithGoal(targetPoint);
else walkWithGoal(ev.getThiefRobot().getPosition());
}
}
}
/**
* 获取当前位置
*/
Vector2d getPosition() {
Point3d p = new Point3d();
getCoords(p);
return new Vector2d(p.z, p.x);
}
/**
* 设置领航状态
*/
void setIsLeader(boolean status) {
isLeader = status;
}
/**
* 设置目标点
*/
void setTargetPoint(Vector2d targetPoint) {
this.targetPoint = targetPoint;
}
Vector2d getTargetPoint() {
return targetPoint;
}
/**
* 判断是否长期静止
*/
private boolean isStopForLong(Vector2d pre, Vector2d cur) {
if (cur.equals(pre)) {
if (freeze_time == 30)
// 如果边界设置太小会影响正常的碰撞处理
return true;
else {
freeze_time++;
return false;
}
} else {
freeze_time = 0;
return false;
}
}
/**
* 向目标移动,避开障碍物
* 人工势场法
*/
private void walkWithGoal(Vector2d goal) {
setTranslationalVelocity(this.velocity);
// 获取速度
Vector3d velocity = this.linearVelocity;
// 获取当前运动方向
Vector2d direct = new Vector2d(velocity.z, velocity.x);
// 获取当前运动位置
Point3d p = new Point3d();
getCoords(p);
Vector2d pos = new Vector2d(p.z, p.x);
//获取三方个障碍物的距离
double d0 = sonars.getMeasurement(0);// front声纳,正前方
double d1 = sonars.getMeasurement(1);// frontleft声纳,左前方
double d2 = sonars.getMeasurement(7);// frontright声纳,右前方
// 计算三个方向障碍物的斥力
double rf0 = MyUtil.repelForce(d0);
double rf1 = MyUtil.repelForce(d1);
double rf2 = MyUtil.repelForce(d2);
//计算三个方向障碍物斥力的合力
double k1 = Math.cos(2 * Math.PI / 9);
double k2 = Math.sin(2 * Math.PI / 9);
Vector2d vf0 = new Vector2d(0 - rf0, 0);
Vector2d vf1 = new Vector2d((0 - rf1 * k1), (0 - rf1 * k2));
Vector2d vf2 = new Vector2d((rf2 * k1), (rf2 * k2));
Vector2d composition = new Vector2d();
composition.setX(vf0.x + vf1.x + vf2.x);
composition.setY(vf0.y + vf1.y + vf2.y);
if (debug)
System.out.println("(" + composition.x + ","
+ composition.y);
//给定斥力合力向量
Vector2d repelForceVector = MyUtil.transform(direct, composition);
// 计算目标的对机器人的引力
Vector2d toGoal = new Vector2d((goal.x - pos.x),
(goal.y - pos.y));
double disGoal = toGoal.length();//和目的的距离
if (debug)
System.out.println("distance to goal:" + disGoal);
double goalForce = MyUtil.attractForce(disGoal);//计算引力
if (debug)
System.out.println("attract force from goal:" + goalForce);
Vector2d goalForceVector = new Vector2d(
(goalForce * toGoal.x / disGoal),
(goalForce * toGoal.y / disGoal));
// 计算斥力和引力的合力
double x = repelForceVector.x + goalForceVector.x;
double y = repelForceVector.y + goalForceVector.y;
Vector2d allForces = new Vector2d(x, y);
if (debug) {
System.out.println("total force(" + allForces.x + ","
+ allForces.y + ")");
System.out.println("force direct(" + direct.x + ","
+ direct.y + ")");
}
// 根据合力的方向和当前运动方向的夹角来判断当前转动角度
double angle = MyUtil.getAngle(direct, allForces);
if (debug)
System.out.println("angle:" + angle);
// 判断转动方向
if (angle < Math.PI) {
setRotationalVelocity(angle);
} else if (angle > Math.PI) {
setRotationalVelocity((angle - 2 * Math.PI));
}
// 是否到达目标点
if (checkGoal(new Point3d(goal.x, 0, goal.y))) {
// 到达目标点,亮绿灯 停止运动
setTranslationalVelocity(0);
setRotationalVelocity(0);
// lamp.setOn(true);
return;
} else {
// lamp.setOn(false);
setTranslationalVelocity(0.5);
}
// 检测是否碰撞
if (bumpers.oneHasHit()) {
// 机器人身体三个方向和障碍物的距离
double left = sonars.getFrontLeftQuadrantMeasurement();
double right = sonars.getFrontRightQuadrantMeasurement();
double front = sonars.getFrontQuadrantMeasurement();
// 如果接近障碍物
if ((front < 0.7) || (left < 0.7) || (right < 0.7)) {
setTranslationalVelocity(0);
if (left < right) {
setRotationalVelocity(-1 - (0.1 * Math.random()));// 随机向右转
} else {
setRotationalVelocity(1 - (0.1 * Math.random()));// 随机向左转
}
}
}
// 判断是否一直不动
// 获取前一次运动位置
getCoords(p);
Vector2d cur_pos = new Vector2d(p.z, p.x);
if (isStopForLong(pos, cur_pos)) {
if (debug)
System.out.println(this.name + "卡住了!!!");
setTranslationalVelocity(0);
setRotationalVelocity(Math.PI);
freeze_time = 0;
}
}
/**
* 检查是否到达目标
*/
private boolean checkGoal(Point3d goal3d) {
// 当前位置
Point3d currentPos = new Point3d();
getCoords(currentPos);
Point3d goalPos = new Point3d(goal3d.x, goal3d.y, goal3d.z);
// 如果当前距离目标点小于0.5那么即认为是到达
return currentPos.distance(goalPos) <= 0.5;
}
}
| 1 | 11 | 1 |
35470_12 | import java.util.ArrayList;
import java.util.List;
public class Code059_MaxHappy {
// 派对的最大快乐值
// 公司的每个员工都符合 Employee 类的描述。
// 整个公司的人员结构可以看作是一棵标准的、 没有环的多叉树。
// 树的头节点是公司唯一的老板。除老板之外的每个员工都有唯一的直接上级。
// 叶节点是没有任何下属的基层员工(nexts列表为空),除基层员工外,每个员工都有一个或多个直接下级。
// 这个公司现在要办party,你可以决定哪些员工来,哪些员工不来.
// 规则:
// 1.如果某个员工来了,那么这个员工的所有直接下级都不能来
// 2.派对的整体快乐值是所有到场员工快乐值的累加
// 3.你的目标是让派对的整体快乐值尽量大
// 给定一棵多叉树的头节点boss,
// 请返回派对的最大快乐值。
public static class Employee {
public int happy; // 这名员工可以带来的快乐值
public List<Employee> nexts; // 这名员工有哪些直接下级
public Employee(int happy) {
this.happy = happy;
// List要在构造器创建
nexts = new ArrayList<>();
}
}
public static int maxHappy1(Employee boss) {
if (boss == null) {
return 0;
}
return process1(boss, false);
}
// 当前来到的节点叫cur,
// up表示cur的上级是否来,
// 该函数含义:
// 如果up为true,表示在cur上级已经确定来的情况下,cur整棵树能够提供最大的快乐值是多少?
// 如果up为false,表示在cur上级已经确定不来的情况下,cur整棵树能够提供最大的快乐值是多少?
public static int process1(Employee cur, boolean up) {
if (up) { // 如果cur的上级来的话,cur没得选,只能不来
int ans = 0;
for (Employee next : cur.nexts) {
ans += process1(next, false);
}
return ans;
} else { // 如果cur的上级不来的话,cur可以选,可以来也可以不来
int p1 = cur.happy; // cur 来
int p2 = 0; // cur 不来
for (Employee next : cur.nexts) {
p1 += process1(next, true);
p2 += process1(next, false);
}
return Math.max(p1, p2);
}
}
public static int maxHappy2(Employee head) {
Info allInfo = process2(head);
return Math.max(allInfo.no, allInfo.yes);
}
public static class Info {
public int no; // 当前头节点不来的最大快乐值
public int yes; // 当前头节点来的最大快乐值
public Info(int no, int yes) {
this.no = no;
this.yes = yes;
}
}
public static Info process2(Employee head) {
if (head == null) {
return new Info(0, 0);
}
int no = 0; // 当前节点不选
int yes = head.happy; // 当前节点选中
for (Employee next : head.nexts) {
Info nextInfo = process2(next);
no += Math.max(nextInfo.no, nextInfo.yes);
yes += nextInfo.no;
}
return new Info(no, yes);
}
// for test
public static Employee generateBoss(int maxLevel, int maxNexts, int maxHappy) {
if (Math.random() < 0.05) {
return null;
}
Employee boss = new Employee((int) (Math.random() * (maxHappy + 1)));
generateNexts(boss, 1, maxLevel, maxNexts, maxHappy);
return boss;
}
// for test
public static void generateNexts(Employee boss, int level, int maxLevel, int maxNexts, int maxHappy) {
if (level > maxLevel) {
return;
}
int nextsSize = (int) (Math.random() * (maxNexts + 1));
for (int i = 0; i < nextsSize; i++) {
Employee next = new Employee((int) (Math.random() * (maxHappy + 1)));
boss.nexts.add(next);
generateNexts(next, level + 1, maxLevel, maxNexts, maxHappy);
}
}
// for test
public static void main(String[] args) {
int maxLevel = 5;
int maxNexts = 5;
int maxHappy = 100;
int testTimes = 1000;
for (int i = 0; i < testTimes; i++) {
Employee boss = generateBoss(maxLevel, maxNexts, maxHappy);
if (maxHappy1(boss) != maxHappy2(boss)){
System.out.println("Oops!");
}
}
System.out.println("finish!");
}
}
| ChengYuAlex/algorithm | src/Code059_MaxHappy.java | 1,250 | // 这名员工可以带来的快乐值 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.List;
public class Code059_MaxHappy {
// 派对的最大快乐值
// 公司的每个员工都符合 Employee 类的描述。
// 整个公司的人员结构可以看作是一棵标准的、 没有环的多叉树。
// 树的头节点是公司唯一的老板。除老板之外的每个员工都有唯一的直接上级。
// 叶节点是没有任何下属的基层员工(nexts列表为空),除基层员工外,每个员工都有一个或多个直接下级。
// 这个公司现在要办party,你可以决定哪些员工来,哪些员工不来.
// 规则:
// 1.如果某个员工来了,那么这个员工的所有直接下级都不能来
// 2.派对的整体快乐值是所有到场员工快乐值的累加
// 3.你的目标是让派对的整体快乐值尽量大
// 给定一棵多叉树的头节点boss,
// 请返回派对的最大快乐值。
public static class Employee {
public int happy; // 这名 <SUF>
public List<Employee> nexts; // 这名员工有哪些直接下级
public Employee(int happy) {
this.happy = happy;
// List要在构造器创建
nexts = new ArrayList<>();
}
}
public static int maxHappy1(Employee boss) {
if (boss == null) {
return 0;
}
return process1(boss, false);
}
// 当前来到的节点叫cur,
// up表示cur的上级是否来,
// 该函数含义:
// 如果up为true,表示在cur上级已经确定来的情况下,cur整棵树能够提供最大的快乐值是多少?
// 如果up为false,表示在cur上级已经确定不来的情况下,cur整棵树能够提供最大的快乐值是多少?
public static int process1(Employee cur, boolean up) {
if (up) { // 如果cur的上级来的话,cur没得选,只能不来
int ans = 0;
for (Employee next : cur.nexts) {
ans += process1(next, false);
}
return ans;
} else { // 如果cur的上级不来的话,cur可以选,可以来也可以不来
int p1 = cur.happy; // cur 来
int p2 = 0; // cur 不来
for (Employee next : cur.nexts) {
p1 += process1(next, true);
p2 += process1(next, false);
}
return Math.max(p1, p2);
}
}
public static int maxHappy2(Employee head) {
Info allInfo = process2(head);
return Math.max(allInfo.no, allInfo.yes);
}
public static class Info {
public int no; // 当前头节点不来的最大快乐值
public int yes; // 当前头节点来的最大快乐值
public Info(int no, int yes) {
this.no = no;
this.yes = yes;
}
}
public static Info process2(Employee head) {
if (head == null) {
return new Info(0, 0);
}
int no = 0; // 当前节点不选
int yes = head.happy; // 当前节点选中
for (Employee next : head.nexts) {
Info nextInfo = process2(next);
no += Math.max(nextInfo.no, nextInfo.yes);
yes += nextInfo.no;
}
return new Info(no, yes);
}
// for test
public static Employee generateBoss(int maxLevel, int maxNexts, int maxHappy) {
if (Math.random() < 0.05) {
return null;
}
Employee boss = new Employee((int) (Math.random() * (maxHappy + 1)));
generateNexts(boss, 1, maxLevel, maxNexts, maxHappy);
return boss;
}
// for test
public static void generateNexts(Employee boss, int level, int maxLevel, int maxNexts, int maxHappy) {
if (level > maxLevel) {
return;
}
int nextsSize = (int) (Math.random() * (maxNexts + 1));
for (int i = 0; i < nextsSize; i++) {
Employee next = new Employee((int) (Math.random() * (maxHappy + 1)));
boss.nexts.add(next);
generateNexts(next, level + 1, maxLevel, maxNexts, maxHappy);
}
}
// for test
public static void main(String[] args) {
int maxLevel = 5;
int maxNexts = 5;
int maxHappy = 100;
int testTimes = 1000;
for (int i = 0; i < testTimes; i++) {
Employee boss = generateBoss(maxLevel, maxNexts, maxHappy);
if (maxHappy1(boss) != maxHappy2(boss)){
System.out.println("Oops!");
}
}
System.out.println("finish!");
}
}
| 1 | 15 | 1 |
16455_99 | package com.bn.Begin;
import com.bn.driversystem_android.MainActivity;
import com.bn.driversystem_android.R;
import com.bn.fyq.Constant.ResetConstant;
import com.bn.util.DBUtil;
import com.bn.util.DataUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("HandlerLeak")
public class ChooseCar extends Activity{
private String ChooseCar_Get;
public static int Car_Down=0; //记录小车按钮是否被按下 未按下为0 按下为1
public static int Huo_Down=0; //货车
public static int Ke_Down=0; //客车
public static int Mo_Down=0; //摩托
public static int KeYun_Down=0; //客车运输
public static int HuoYun_Down=0; //货车运输
public static int Wei_Down=0; //危险品
public static int Jiao_Down=0; //教练证
public static int ChooseCar=0;//是否从滑动界面进入的标志位
public static String GetCarTypeByCunCu;//得到存储的数据
public static boolean CunCuOkOrNot=false;//是否存储标志位
public static int chexing;
//int diyicijiazai_car=0;//加载选项 看看是不是第一次加载 0是没有加载
String gettestmsg_car;
String testmsg_car;
public static boolean NetIsOk_Car;//判断网络是否连接标志位
Handler handler_car=new Handler()
{
Bundle b;
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch(msg.what)
{
case ResetConstant.TESTCONNECT://测试连接成功0
//获取消息中的数据
b=msg.getData();
//获取内容字符串
gettestmsg_car=b.getString("msg");
if(gettestmsg_car.equals("success"))
{
NetIsOk_Car=true;
}
break;
case ResetConstant.TESTCONNECTERROR://测试连接失败1
NetIsOk_Car=false;
Toast.makeText(ChooseCar.this,"连接服务器失败,请打开WiFi连接服务器.",
Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.choosecar);
testConnectThread();//实现标识位转换
//返回按钮
ImageView subject_two_kaogui_title;
subject_two_kaogui_title=(ImageView)findViewById(R.id.button_subject_two_kaogui_title);
subject_two_kaogui_title.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//相当于手机的返回按钮
ChooseCar.this.finish();
}
}
);
//定义8个汽车的图片按钮
final Button button1;
final Button button2;
final Button button3;
final Button button4;
final Button button5;
final Button button6;
final Button button7;
final Button button8;
//Button image;
//初始化Button
button1 = (Button)findViewById(R.id.ChooseCar_Button01);
button2 = (Button)findViewById(R.id.ChooseCar_Button02);
button3 = (Button)findViewById(R.id.ChooseCar_Button03);
button4 = (Button)findViewById(R.id.ChooseCar_Button04);
button5 = (Button)findViewById(R.id.ChooseCar_Button05);
button6 = (Button)findViewById(R.id.ChooseCar_Button06);
button7 = (Button)findViewById(R.id.ChooseCar_Button07);
button8 = (Button)findViewById(R.id.ChooseCar_Button08);
//以下分别为每个按钮设置事件监听 setOnTouchListener
//小车
button1.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.xiaoche_p));
Car_Down=1;
//小车按下后 其他车辆还原
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.xiaoche_p));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
//设置题库 等待3s后
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "正在获取试题信息...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "01");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "01");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
//ChooseCar.this.finish();
//this.
}
}, 2000);
dialog.show();
}
//dialog.cancel();
}
return false;
}
});
//货车
button2.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.huoche_p));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
//button2.setBackgroundResource((R.drawable.huoche));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Huo_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.huoche_p));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "02");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "02");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
//((button)v).setBackgroundResource((R.drawable.huoche));
return false;
}
});
//客车
button3.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.keche_p));
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
//button3.setBackgroundResource((R.drawable.keche));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Ke_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.keche_p));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "03");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "03");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//摩托车
button4.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.motuoanxia));
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
//button4.setBackgroundResource((R.drawable.muotuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Mo_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.motuoanxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=1;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "04");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "04");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//客运
button5.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.keyunanxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
//button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
KeYun_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.keyunanxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "05");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "05");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//货运
button6.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.huoyunanxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
//button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
HuoYun_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.huoyunanxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "06");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "06");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//危险
button7.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.weixiananxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
//button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Wei_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.weixiananxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "07");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "07");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//教练
button8.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.jiaoliananxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
//button8.setBackgroundResource((R.drawable.jiaolian));
Jiao_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.jiaoliananxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "08");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "08");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//==========Button监听END================
//=========Button完成按钮=====Begin===
Button buttonOk;
buttonOk=(Button)findViewById(R.id.button01);
buttonOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(Car_Down==1||Huo_Down==1||Ke_Down==1||Mo_Down==1||
KeYun_Down==1||HuoYun_Down==1||Wei_Down==1||Jiao_Down==1)
{
ChooseCar=1;
//设置题库 等待3s后跳转
CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "正在设置题库中...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
CustomProgressDialog.mAnimation.stop();
Intent intent=new Intent();
intent.setClass(ChooseCar.this, MainActivity.class);
if(Car_Down==1)
{
ChooseCar_Get="小车";
}
else if(Huo_Down==1)
{
ChooseCar_Get="货车";
}
else if(Ke_Down==1)
{
ChooseCar_Get="客车";
}
else if(Mo_Down==1)
{
ChooseCar_Get="摩托车";
}
else if(KeYun_Down==1)
{
ChooseCar_Get="客运";
}
else if(HuoYun_Down==1)
{
ChooseCar_Get="货运";
}
else if(Wei_Down==1)
{
ChooseCar_Get="危险品";
}
else
{
ChooseCar_Get="教练";
}
DBUtil.deleteCar();//删除
DBUtil.insertCar(ChooseCar_Get);//插入
//有储存 把储存的标志位设为 真
CunCuOkOrNot=true;
//loadData(ChooseCar.this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG设置
startActivity(intent);
ChooseCar.this.finish();
}
}, 2000);
dialog.show();
//ChooseCar.this.finish();
}
else
{
Toast toast=Toast.makeText(getApplicationContext(), "请选择所报车型", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
//发送消息的进程
public void testConnectThread()//每次运行都调用此方法 实现判断是否联网
{
//开启线程进行判断
new Thread()
{
@Override
public void run()
{
try
{
DataUtil.testConnect(handler_car);
}
catch (Exception e)
{//如果捕获到异常就发送handler
Message msg=new Message();
msg.what=0;
Bundle b=new Bundle();
b.putString("msg","网络未连接,请检查您的网络后重新登陆");
msg.setData(b);
handler_car.sendMessage(msg);
return;
}
}
}.start();
}
// /*
// * 此处为设置完全退出程序后 再次进入 保留自己所选择的车型
// */
// //数据读取方法
// private void loadData(Context context) {
// SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
// //Toast.makeText(this, sp.getString("content", "").toString(), 0).show();
// GetCarTypeByCunCu=sp.getString("content", "").toString();
// }
// //对数据进行存储
// private void saveData(Context context,String string){
// SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
// Editor editor = sp.edit();
// editor.putString("content", string);
// editor.commit();
// }
}
| ChengYuRen/DrivingTest_Android | app/src/main/java/com/bn/Begin/ChooseCar.java | 7,613 | //选中后需要从数据库获取数据 | line_comment | zh-cn | package com.bn.Begin;
import com.bn.driversystem_android.MainActivity;
import com.bn.driversystem_android.R;
import com.bn.fyq.Constant.ResetConstant;
import com.bn.util.DBUtil;
import com.bn.util.DataUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("HandlerLeak")
public class ChooseCar extends Activity{
private String ChooseCar_Get;
public static int Car_Down=0; //记录小车按钮是否被按下 未按下为0 按下为1
public static int Huo_Down=0; //货车
public static int Ke_Down=0; //客车
public static int Mo_Down=0; //摩托
public static int KeYun_Down=0; //客车运输
public static int HuoYun_Down=0; //货车运输
public static int Wei_Down=0; //危险品
public static int Jiao_Down=0; //教练证
public static int ChooseCar=0;//是否从滑动界面进入的标志位
public static String GetCarTypeByCunCu;//得到存储的数据
public static boolean CunCuOkOrNot=false;//是否存储标志位
public static int chexing;
//int diyicijiazai_car=0;//加载选项 看看是不是第一次加载 0是没有加载
String gettestmsg_car;
String testmsg_car;
public static boolean NetIsOk_Car;//判断网络是否连接标志位
Handler handler_car=new Handler()
{
Bundle b;
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch(msg.what)
{
case ResetConstant.TESTCONNECT://测试连接成功0
//获取消息中的数据
b=msg.getData();
//获取内容字符串
gettestmsg_car=b.getString("msg");
if(gettestmsg_car.equals("success"))
{
NetIsOk_Car=true;
}
break;
case ResetConstant.TESTCONNECTERROR://测试连接失败1
NetIsOk_Car=false;
Toast.makeText(ChooseCar.this,"连接服务器失败,请打开WiFi连接服务器.",
Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.choosecar);
testConnectThread();//实现标识位转换
//返回按钮
ImageView subject_two_kaogui_title;
subject_two_kaogui_title=(ImageView)findViewById(R.id.button_subject_two_kaogui_title);
subject_two_kaogui_title.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//相当于手机的返回按钮
ChooseCar.this.finish();
}
}
);
//定义8个汽车的图片按钮
final Button button1;
final Button button2;
final Button button3;
final Button button4;
final Button button5;
final Button button6;
final Button button7;
final Button button8;
//Button image;
//初始化Button
button1 = (Button)findViewById(R.id.ChooseCar_Button01);
button2 = (Button)findViewById(R.id.ChooseCar_Button02);
button3 = (Button)findViewById(R.id.ChooseCar_Button03);
button4 = (Button)findViewById(R.id.ChooseCar_Button04);
button5 = (Button)findViewById(R.id.ChooseCar_Button05);
button6 = (Button)findViewById(R.id.ChooseCar_Button06);
button7 = (Button)findViewById(R.id.ChooseCar_Button07);
button8 = (Button)findViewById(R.id.ChooseCar_Button08);
//以下分别为每个按钮设置事件监听 setOnTouchListener
//小车
button1.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.xiaoche_p));
Car_Down=1;
//小车按下后 其他车辆还原
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.xiaoche_p));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
//设置题库 等待3s后
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "正在获取试题信息...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "01");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "01");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
//ChooseCar.this.finish();
//this.
}
}, 2000);
dialog.show();
}
//dialog.cancel();
}
return false;
}
});
//货车
button2.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.huoche_p));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
//button2.setBackgroundResource((R.drawable.huoche));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Huo_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.huoche_p));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "02");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "02");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
//((button)v).setBackgroundResource((R.drawable.huoche));
return false;
}
});
//客车
button3.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.keche_p));
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
//button3.setBackgroundResource((R.drawable.keche));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Ke_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.keche_p));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "03");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "03");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//摩托车
button4.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.motuoanxia));
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
//button4.setBackgroundResource((R.drawable.muotuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Mo_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.motuoanxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=1;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "04");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "04");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//客运
button5.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.keyunanxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
//button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
KeYun_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.keyunanxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "05");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "05");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//货运
button6.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.huoyunanxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
//button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
HuoYun_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.huoyunanxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "06");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "06");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//危险
button7.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.weixiananxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
//button7.setBackgroundResource((R.drawable.weixian));
button8.setBackgroundResource((R.drawable.jiaolian));
Wei_Down=1;
//选中 <SUF>
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.weixiananxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "07");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "07");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//教练
button8.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
//重新设置按下时的背景图片
((Button)v).setBackgroundResource((R.drawable.jiaoliananxia));
//当此车按下时 其他还原
button1.setBackgroundResource((R.drawable.xiaoche_n));
button2.setBackgroundResource((R.drawable.huoche_n));
button3.setBackgroundResource((R.drawable.keche_n));
button4.setBackgroundResource((R.drawable.motuo));
button5.setBackgroundResource((R.drawable.keyun));
button6.setBackgroundResource((R.drawable.huoyun));
button7.setBackgroundResource((R.drawable.weixian));
//button8.setBackgroundResource((R.drawable.jiaolian));
Jiao_Down=1;
//选中后需要从数据库获取数据
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
//手势抬起 将数据统计表清空
DBUtil.deleteAllSJTJ();
//再修改为抬起时的正常图片
((Button)v).setBackgroundResource((R.drawable.jiaoliananxia));
testConnectThread();//实现标识位转换
if(NetIsOk_Car==false)
{
Toast.makeText(ChooseCar.this,"暂时未能连接到服务器,请您检查您的网络连接",Toast.LENGTH_SHORT).show();
}
else
{
chexing=2;
//设置题库 等待3s后跳转
final CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "客官,请稍等...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//获取小车科一题目数目
String userinfo_one=null;
userinfo_one=DBUtil.getquanbucount("科目一", "08");
//获取小车 科目四 数目
String userinfo_four=null;
userinfo_four=DBUtil.getquanbucount("科目四", "08");
TextView shiti_shumu=(TextView)findViewById(R.id.textView_Shitishu);
shiti_shumu.setText("科目一共"+userinfo_one+"题,科目四共"+userinfo_four+"题");
dialog.cancel();//过三秒让框消失
}
}, 2000);
dialog.show();
}
}
return false;
}
});
//==========Button监听END================
//=========Button完成按钮=====Begin===
Button buttonOk;
buttonOk=(Button)findViewById(R.id.button01);
buttonOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(Car_Down==1||Huo_Down==1||Ke_Down==1||Mo_Down==1||
KeYun_Down==1||HuoYun_Down==1||Wei_Down==1||Jiao_Down==1)
{
ChooseCar=1;
//设置题库 等待3s后跳转
CustomProgressDialog dialog =new CustomProgressDialog(ChooseCar.this, "正在设置题库中...",R.anim.frame);
//计时后结束 并跳转
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
CustomProgressDialog.mAnimation.stop();
Intent intent=new Intent();
intent.setClass(ChooseCar.this, MainActivity.class);
if(Car_Down==1)
{
ChooseCar_Get="小车";
}
else if(Huo_Down==1)
{
ChooseCar_Get="货车";
}
else if(Ke_Down==1)
{
ChooseCar_Get="客车";
}
else if(Mo_Down==1)
{
ChooseCar_Get="摩托车";
}
else if(KeYun_Down==1)
{
ChooseCar_Get="客运";
}
else if(HuoYun_Down==1)
{
ChooseCar_Get="货运";
}
else if(Wei_Down==1)
{
ChooseCar_Get="危险品";
}
else
{
ChooseCar_Get="教练";
}
DBUtil.deleteCar();//删除
DBUtil.insertCar(ChooseCar_Get);//插入
//有储存 把储存的标志位设为 真
CunCuOkOrNot=true;
//loadData(ChooseCar.this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG设置
startActivity(intent);
ChooseCar.this.finish();
}
}, 2000);
dialog.show();
//ChooseCar.this.finish();
}
else
{
Toast toast=Toast.makeText(getApplicationContext(), "请选择所报车型", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
//发送消息的进程
public void testConnectThread()//每次运行都调用此方法 实现判断是否联网
{
//开启线程进行判断
new Thread()
{
@Override
public void run()
{
try
{
DataUtil.testConnect(handler_car);
}
catch (Exception e)
{//如果捕获到异常就发送handler
Message msg=new Message();
msg.what=0;
Bundle b=new Bundle();
b.putString("msg","网络未连接,请检查您的网络后重新登陆");
msg.setData(b);
handler_car.sendMessage(msg);
return;
}
}
}.start();
}
// /*
// * 此处为设置完全退出程序后 再次进入 保留自己所选择的车型
// */
// //数据读取方法
// private void loadData(Context context) {
// SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
// //Toast.makeText(this, sp.getString("content", "").toString(), 0).show();
// GetCarTypeByCunCu=sp.getString("content", "").toString();
// }
// //对数据进行存储
// private void saveData(Context context,String string){
// SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
// Editor editor = sp.edit();
// editor.putString("content", string);
// editor.commit();
// }
}
| 1 | 15 | 1 |
56686_0 | package com.meituan.duplicateimage.bean;
import java.io.File;
/**
* 一个对象对应一个图片文件
*/
public class ImageFile {
public String name;
public File mFile;
public String mHash;//pHash算法生成的hash值
public float[] mHistogramData;// TODO xiayong 比较耗内存,是否有优化空间 采用分治之类?
public int mHeight = -1;
public int mWidth = -1;
public ImageFile(final File file) {
mFile = file;
if (!mFile.exists()) {
throw new IllegalArgumentException("input file does not exist,please check the path");
}
name = mFile.getName();
}
}
| Chengdu-RD/DuplicateImages | src/com/meituan/duplicateimage/bean/ImageFile.java | 168 | /**
* 一个对象对应一个图片文件
*/ | block_comment | zh-cn | package com.meituan.duplicateimage.bean;
import java.io.File;
/**
* 一个对 <SUF>*/
public class ImageFile {
public String name;
public File mFile;
public String mHash;//pHash算法生成的hash值
public float[] mHistogramData;// TODO xiayong 比较耗内存,是否有优化空间 采用分治之类?
public int mHeight = -1;
public int mWidth = -1;
public ImageFile(final File file) {
mFile = file;
if (!mFile.exists()) {
throw new IllegalArgumentException("input file does not exist,please check the path");
}
name = mFile.getName();
}
}
| 1 | 23 | 1 |
41143_0 | import static java.lang.Thread.sleep;
/**
* 多个人玩球,多线程
* 互相传球,球是 对象监视器
*/
class Game implements Runnable{
private int round = 1;
private Object ball = new Object();
@Override
public void run() {
while (true){
synchronized (ball){
ball.notify();
if(round<=20){
System.out.println(Thread.currentThread().getName()+
"get the ball at "+String.valueOf(round)+"round");
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
round ++;
try {
ball.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else break;
}
}
}
}
public class PlayBall {
public static void main(String[] args) {
Game g = new Game();
Thread t1 = new Thread(g);
Thread t2 = new Thread(g);
Thread t3 = new Thread(g);
Thread t4 = new Thread(g);
t1.setName("队长");
t1.setPriority(10);
t2.setName("球员2");
t3.setName("球员3");
t4.setName("球员4");
t4.setPriority(1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
| ChengkaiYang2022/javaLearn | JavaBasic/javaSenior/day02/src/main/java2/PlayBall.java | 336 | /**
* 多个人玩球,多线程
* 互相传球,球是 对象监视器
*/ | block_comment | zh-cn | import static java.lang.Thread.sleep;
/**
* 多个人 <SUF>*/
class Game implements Runnable{
private int round = 1;
private Object ball = new Object();
@Override
public void run() {
while (true){
synchronized (ball){
ball.notify();
if(round<=20){
System.out.println(Thread.currentThread().getName()+
"get the ball at "+String.valueOf(round)+"round");
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
round ++;
try {
ball.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else break;
}
}
}
}
public class PlayBall {
public static void main(String[] args) {
Game g = new Game();
Thread t1 = new Thread(g);
Thread t2 = new Thread(g);
Thread t3 = new Thread(g);
Thread t4 = new Thread(g);
t1.setName("队长");
t1.setPriority(10);
t2.setName("球员2");
t3.setName("球员3");
t4.setName("球员4");
t4.setPriority(1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
| 0 | 37 | 0 |
25869_0 | import java.util.Scanner;
public class ACM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = 100010; // 假设数组大小最多为100010
int[] w = new int[N];
int n = scanner.nextInt(); // 读取数组大小
for (int i = 0; i < n; i++) {
w[i] = scanner.nextInt(); // 读取n个整数
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += w[i];
}
System.out.println(sum); // 输出元素和k
/*
* import java.util.Scanner;
* public class Main{
* public static void main(String args[]){
* Scanner sc = new Scanner(System.in);
* int n = sc.nextInt();
* }
* }
*/
}
| Chennian-Zhao/JavaSE_Journey | ACM.java | 226 | // 假设数组大小最多为100010 | line_comment | zh-cn | import java.util.Scanner;
public class ACM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = 100010; // 假设 <SUF>
int[] w = new int[N];
int n = scanner.nextInt(); // 读取数组大小
for (int i = 0; i < n; i++) {
w[i] = scanner.nextInt(); // 读取n个整数
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += w[i];
}
System.out.println(sum); // 输出元素和k
/*
* import java.util.Scanner;
* public class Main{
* public static void main(String args[]){
* Scanner sc = new Scanner(System.in);
* int n = sc.nextInt();
* }
* }
*/
}
| 1 | 18 | 1 |
60134_6 | package con;
/**
* 静态代码块 > 构造代码块 > 构造方法
*/
public class CodeBlockTest {
public static void main(String[] args) {
// Window window3= new Window("window3");
// House house = new House(window3);
System.out.println("数量是" + Window.getWindowCount()) ;
}
}
class House{
//构造代码块
static Window window1;
Window window2;
Window window3;
//静态代码块
static{
System.out.println("1c");
window1 = new Window("window1");
System.out.println(window1);
}
//构造代码块
{
System.out.println("2c");
window2 = new Window("window2");
System.out.println(window2);
}
//方法
public House(){}
public House(Window window3){
System.out.println("3c");
this.window3 = window3;
System.out.println(window3);
}
}
class Window{
private static int WindowCount;
private String name;
public void setname(String name){
this.name = name;
}
public String getname(){
return name;
}
//构造代码块
{
WindowCount++;
}
public static int getWindowCount(){
return WindowCount;
}
public Window(){
}
public Window(String name){
this.name = name;
}
/**
* 重写toString方法
*/
@Override
public String toString(){
return "房屋窗户信息{"+ "窗户名称'" + name +'\''+'}';
}
}
| Chenpeel/Codes | Java/NT/src/inherit/con/CodeBlockTest.java | 387 | //构造代码块 | line_comment | zh-cn | package con;
/**
* 静态代码块 > 构造代码块 > 构造方法
*/
public class CodeBlockTest {
public static void main(String[] args) {
// Window window3= new Window("window3");
// House house = new House(window3);
System.out.println("数量是" + Window.getWindowCount()) ;
}
}
class House{
//构造代码块
static Window window1;
Window window2;
Window window3;
//静态代码块
static{
System.out.println("1c");
window1 = new Window("window1");
System.out.println(window1);
}
//构造代码块
{
System.out.println("2c");
window2 = new Window("window2");
System.out.println(window2);
}
//方法
public House(){}
public House(Window window3){
System.out.println("3c");
this.window3 = window3;
System.out.println(window3);
}
}
class Window{
private static int WindowCount;
private String name;
public void setname(String name){
this.name = name;
}
public String getname(){
return name;
}
//构造 <SUF>
{
WindowCount++;
}
public static int getWindowCount(){
return WindowCount;
}
public Window(){
}
public Window(String name){
this.name = name;
}
/**
* 重写toString方法
*/
@Override
public String toString(){
return "房屋窗户信息{"+ "窗户名称'" + name +'\''+'}';
}
}
| 1 | 7 | 1 |
15265_22 | package com.GUI;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
public class CityBtn extends JButton {
private int xOld = 0;
private int yOld = 0;
public Timer timer;
private int clickTimes = 0;
private boolean isPressed = false;
private int btnWidth = 30;
private int btnHeight = 30;
private RoundPanel parent;
private int startX = 0;
private int startY = 0;
private int lastX = 0;
private int lastY = 0;
private int id = 0;
private String strCityInfo = new String();
public ArrayList<ArcInfo> listArcInfo = new ArrayList<>();
public MainWindow frameMainWindow;
public JLabel labelCityName;
private boolean isClicked = false;
public String getStrCityInfo() {
return strCityInfo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setStrCityInfo(String strCityInfo) {
this.strCityInfo = strCityInfo;
}
public void setClicked(boolean clicked) {
isClicked = clicked;
}
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("time on");
if (clickTimes < 2) {
clickTimes = 0;//如果时间到了还没双击那就不算了,此次双击失效
timer.stop();
}
}
};
CityBtn(MainWindow frameMainWindow, int id) {
super();
//初始化定时器
this.id = id;
timer = new Timer(300, taskPerformer);
this.frameMainWindow = frameMainWindow;
parent = (RoundPanel) this.getParent();
labelCityName = new JLabel();
setPreferredSize(new Dimension(btnWidth, btnHeight));
setSize(btnWidth, btnHeight);
Font font = new Font("微软雅黑", Font.BOLD, 14);
labelCityName.setFont(font);
labelCityName.setForeground(new Color(116, 169, 181));
labelCityName.setVisible(true);
setContentAreaFilled(false);
this.setBorderPainted(false); // 不绘制边框
this.setFocusPainted(false); // 不绘制焦点状态
this.setSelected(true);
labelCityName.setHorizontalAlignment(SwingConstants.CENTER);
CityBtn that = this;
//鼠标单击点击事件
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1) {
clickTimes++;//每点一次点击次数加1
xOld = e.getX();//记录鼠标按下时的坐标
yOld = e.getY();
if (!timer.isRunning()) ;//如果定时器未启动就启动
timer.start();
if (frameMainWindow.paintPad.isSettingArc()) {//在设置边的情况下按钮被点击了说明被点击的这个按钮是终点
clickTimes = 0;
if (that.id == frameMainWindow.cityBtnCurrent.id) {
frameMainWindow.logToWindow("不能设置自己到自己");
frameMainWindow.paintPad.setSettingArc(false);
return;
}
//添加边到当前城市
if (frameMainWindow.cityBtnCurrent.addArcToVel(that, 0, true)) {
frameMainWindow.logToWindow("添加成功");
that.addArcToVel(frameMainWindow.cityBtnCurrent, 0, false);//添加成功则添加反向的边
} else {
frameMainWindow.logToWindow("边重复");
}
;
frameMainWindow.paintPad.setSettingArc(false);
} else {
frameMainWindow.cityBtnCurrent = that;
frameMainWindow.textFieldCityName.setText(labelCityName.getText());
frameMainWindow.roundTextArea.textAreaReal.setText(strCityInfo);
Component cp = (Component) e.getSource(); //获取事件e的触发源
//当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置
//System.out.println(cp.getX() + " "+cp.getY());
if (getParent().getBounds().contains(xOld, yOld)) {
xOld = cp.getX();
yOld = cp.getY();
startX = e.getXOnScreen();
startY = e.getYOnScreen();
isPressed = true;
}
frameMainWindow.paintPad.repaint();
if (clickTimes == 2) {//如果检测到双击
//这里执行双击事件
//System.out.println("检测到双击");
//System.out.println(getBounds());
//System.out.println(xOld + " : " + yOld);
if (getBounds().contains(xOld, yOld)) {
//检测到画板内双击
doubleClick();
}
timer.stop();
clickTimes = 0;
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
isPressed = false;
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
//System.out.println(isPressed);
if(isPressed){
int xOnScr = e.getXOnScreen();
int yOnScr = e.getYOnScreen();
int xx = (xOnScr - startX) + xOld;
int yy = (yOnScr - startY) + yOld;
//如果太靠近边界应该触发保护,防止城市丢失
Rectangle r = getParent().getBounds();
int shrinkPixel = 10;//缩小一周的宽度
r.x += shrinkPixel;
r.y += shrinkPixel;
r.width -= 2 * shrinkPixel;
r.height -= 2 * shrinkPixel;
if (!r.contains(xx + getWidth() / 2, yy + getHeight() / 2)) {
CityBtn.this.setLocation(lastX, lastY);
return;
}
CityBtn.this.setLocation(xx, yy);//设置拖拽后,窗口的位置
labelCityName.setLocation(xx - 25, yy + getHeight() / 2 + 5);//设置文本拖拽后的位置
lastX = xx;
lastY = yy;
}
}
});
}
public void doubleClick() {
frameMainWindow.paintPad.setSettingArc(true);
frameMainWindow.paintPad.setPointStart(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2));
frameMainWindow.paintPad.setPointEndLast(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2));
}
protected void paintComponent(Graphics g) {
//设置抗锯齿
Graphics2D g2d = (Graphics2D) g;
//System.out.println(w.getGraphics());
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (getModel().isArmed()) {
g.setColor(Color.lightGray); // 点击时高亮
} else if (frameMainWindow.cityBtnCurrent == this) {
g.setColor(Color.YELLOW);
} else {
g.setColor(getBackground());
}
// fillOval方法画一个矩形的内切椭圆,并且填充这个椭圆,
// 当矩形为正方形时,画出的椭圆便是圆
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
super.paintComponent(g);
}
// 用简单的弧画按钮的边界。
protected void paintBorder(Graphics g) {
g.setColor(Color.white);
// drawOval方法画矩形的内切椭圆,但不填充。只画出一个边界
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
}
// shape对象用于保存按钮的形状,有助于侦听点击按钮事件
Shape shape;
public boolean contains(int x, int y) {
if ((shape == null) || (!shape.getBounds().equals(getBounds()))) {
// 构造一个椭圆形对象
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
// 判断鼠标的x、y坐标是否落在按钮形状内。
return shape.contains(x, y);
}
private boolean addArcToVel(CityBtn target, int distance, boolean ifDraw) { //将info无重复地加到btn内
ArcInfo arcInfo = new ArcInfo(this, target, ifDraw, 0);
//将画板的指针给到输入框这样输入框输入时画板不会刷新
if (ifDraw)
arcInfo.setTextFieldOnArc(new TextFieldOnArc(frameMainWindow, arcInfo));
for (ArcInfo tempArc :
this.listArcInfo) {
if (tempArc.equal(arcInfo)) {//已经添加过这条边,就不加了
System.out.println("已经添加过这条边");
frameMainWindow.paintPad.setSettingArc(false);
frameMainWindow.paintPad.setInputing(true);
return false;
}
}
this.listArcInfo.add(arcInfo);
return true;
}
public String toString() {
return this.labelCityName.getText();
}
public boolean isNearOrigin(CityBtn another){
for (ArcInfo cityBtnTemp : another.listArcInfo){
if (cityBtnTemp.getmStart().equals(this)){
return true;
}
}
return false;
}
}
| Cheny5863/Pedlar | src/com/GUI/CityBtn.java | 2,500 | //如果太靠近边界应该触发保护,防止城市丢失 | line_comment | zh-cn | package com.GUI;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
public class CityBtn extends JButton {
private int xOld = 0;
private int yOld = 0;
public Timer timer;
private int clickTimes = 0;
private boolean isPressed = false;
private int btnWidth = 30;
private int btnHeight = 30;
private RoundPanel parent;
private int startX = 0;
private int startY = 0;
private int lastX = 0;
private int lastY = 0;
private int id = 0;
private String strCityInfo = new String();
public ArrayList<ArcInfo> listArcInfo = new ArrayList<>();
public MainWindow frameMainWindow;
public JLabel labelCityName;
private boolean isClicked = false;
public String getStrCityInfo() {
return strCityInfo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setStrCityInfo(String strCityInfo) {
this.strCityInfo = strCityInfo;
}
public void setClicked(boolean clicked) {
isClicked = clicked;
}
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("time on");
if (clickTimes < 2) {
clickTimes = 0;//如果时间到了还没双击那就不算了,此次双击失效
timer.stop();
}
}
};
CityBtn(MainWindow frameMainWindow, int id) {
super();
//初始化定时器
this.id = id;
timer = new Timer(300, taskPerformer);
this.frameMainWindow = frameMainWindow;
parent = (RoundPanel) this.getParent();
labelCityName = new JLabel();
setPreferredSize(new Dimension(btnWidth, btnHeight));
setSize(btnWidth, btnHeight);
Font font = new Font("微软雅黑", Font.BOLD, 14);
labelCityName.setFont(font);
labelCityName.setForeground(new Color(116, 169, 181));
labelCityName.setVisible(true);
setContentAreaFilled(false);
this.setBorderPainted(false); // 不绘制边框
this.setFocusPainted(false); // 不绘制焦点状态
this.setSelected(true);
labelCityName.setHorizontalAlignment(SwingConstants.CENTER);
CityBtn that = this;
//鼠标单击点击事件
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1) {
clickTimes++;//每点一次点击次数加1
xOld = e.getX();//记录鼠标按下时的坐标
yOld = e.getY();
if (!timer.isRunning()) ;//如果定时器未启动就启动
timer.start();
if (frameMainWindow.paintPad.isSettingArc()) {//在设置边的情况下按钮被点击了说明被点击的这个按钮是终点
clickTimes = 0;
if (that.id == frameMainWindow.cityBtnCurrent.id) {
frameMainWindow.logToWindow("不能设置自己到自己");
frameMainWindow.paintPad.setSettingArc(false);
return;
}
//添加边到当前城市
if (frameMainWindow.cityBtnCurrent.addArcToVel(that, 0, true)) {
frameMainWindow.logToWindow("添加成功");
that.addArcToVel(frameMainWindow.cityBtnCurrent, 0, false);//添加成功则添加反向的边
} else {
frameMainWindow.logToWindow("边重复");
}
;
frameMainWindow.paintPad.setSettingArc(false);
} else {
frameMainWindow.cityBtnCurrent = that;
frameMainWindow.textFieldCityName.setText(labelCityName.getText());
frameMainWindow.roundTextArea.textAreaReal.setText(strCityInfo);
Component cp = (Component) e.getSource(); //获取事件e的触发源
//当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置
//System.out.println(cp.getX() + " "+cp.getY());
if (getParent().getBounds().contains(xOld, yOld)) {
xOld = cp.getX();
yOld = cp.getY();
startX = e.getXOnScreen();
startY = e.getYOnScreen();
isPressed = true;
}
frameMainWindow.paintPad.repaint();
if (clickTimes == 2) {//如果检测到双击
//这里执行双击事件
//System.out.println("检测到双击");
//System.out.println(getBounds());
//System.out.println(xOld + " : " + yOld);
if (getBounds().contains(xOld, yOld)) {
//检测到画板内双击
doubleClick();
}
timer.stop();
clickTimes = 0;
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
isPressed = false;
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
//System.out.println(isPressed);
if(isPressed){
int xOnScr = e.getXOnScreen();
int yOnScr = e.getYOnScreen();
int xx = (xOnScr - startX) + xOld;
int yy = (yOnScr - startY) + yOld;
//如果 <SUF>
Rectangle r = getParent().getBounds();
int shrinkPixel = 10;//缩小一周的宽度
r.x += shrinkPixel;
r.y += shrinkPixel;
r.width -= 2 * shrinkPixel;
r.height -= 2 * shrinkPixel;
if (!r.contains(xx + getWidth() / 2, yy + getHeight() / 2)) {
CityBtn.this.setLocation(lastX, lastY);
return;
}
CityBtn.this.setLocation(xx, yy);//设置拖拽后,窗口的位置
labelCityName.setLocation(xx - 25, yy + getHeight() / 2 + 5);//设置文本拖拽后的位置
lastX = xx;
lastY = yy;
}
}
});
}
public void doubleClick() {
frameMainWindow.paintPad.setSettingArc(true);
frameMainWindow.paintPad.setPointStart(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2));
frameMainWindow.paintPad.setPointEndLast(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2));
}
protected void paintComponent(Graphics g) {
//设置抗锯齿
Graphics2D g2d = (Graphics2D) g;
//System.out.println(w.getGraphics());
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (getModel().isArmed()) {
g.setColor(Color.lightGray); // 点击时高亮
} else if (frameMainWindow.cityBtnCurrent == this) {
g.setColor(Color.YELLOW);
} else {
g.setColor(getBackground());
}
// fillOval方法画一个矩形的内切椭圆,并且填充这个椭圆,
// 当矩形为正方形时,画出的椭圆便是圆
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
super.paintComponent(g);
}
// 用简单的弧画按钮的边界。
protected void paintBorder(Graphics g) {
g.setColor(Color.white);
// drawOval方法画矩形的内切椭圆,但不填充。只画出一个边界
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
}
// shape对象用于保存按钮的形状,有助于侦听点击按钮事件
Shape shape;
public boolean contains(int x, int y) {
if ((shape == null) || (!shape.getBounds().equals(getBounds()))) {
// 构造一个椭圆形对象
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
// 判断鼠标的x、y坐标是否落在按钮形状内。
return shape.contains(x, y);
}
private boolean addArcToVel(CityBtn target, int distance, boolean ifDraw) { //将info无重复地加到btn内
ArcInfo arcInfo = new ArcInfo(this, target, ifDraw, 0);
//将画板的指针给到输入框这样输入框输入时画板不会刷新
if (ifDraw)
arcInfo.setTextFieldOnArc(new TextFieldOnArc(frameMainWindow, arcInfo));
for (ArcInfo tempArc :
this.listArcInfo) {
if (tempArc.equal(arcInfo)) {//已经添加过这条边,就不加了
System.out.println("已经添加过这条边");
frameMainWindow.paintPad.setSettingArc(false);
frameMainWindow.paintPad.setInputing(true);
return false;
}
}
this.listArcInfo.add(arcInfo);
return true;
}
public String toString() {
return this.labelCityName.getText();
}
public boolean isNearOrigin(CityBtn another){
for (ArcInfo cityBtnTemp : another.listArcInfo){
if (cityBtnTemp.getmStart().equals(this)){
return true;
}
}
return false;
}
}
| 1 | 22 | 1 |
52194_6 | package com.brayden.video.util;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class JwtTokenUtils {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
//密钥,用于signature(签名)部分解密
private static final String PRIMARY_KEY = "jwtsecretdemo";
//签发者
private static final String ISS = "Gent.Ni";
// 添加角色的key
private static final String ROLE_CLAIMS = "role";
// 过期时间是3600秒,既是1个小时
private static final long EXPIRATION = 3600L;
// 选择了记住我之后的过期时间为7天
private static final long EXPIRATION_REMEMBER = 604800L;
private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
/**
* description: 创建Token
*
* @param username
* @param isRememberMe
* @return java.lang.String
*/
public static String createToken(String username, List<String> roles, boolean isRememberMe) {
long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
HashMap<String, Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, roles);
return Jwts.builder()
//采用HS256算法对JWT进行的签名,PRIMARY_KEY是我们的密钥
.signWith(SignatureAlgorithm.HS256, PRIMARY_KEY)
//设置角色名
.setClaims(map)
//设置发证人
.setIssuer(ISS)
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.compact();
}
public static Jws<Claims> decode(String token){
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(PRIMARY_KEY).parseClaimsJws(token);
JwsHeader header = claimsJws.getHeader();
Claims body = claimsJws.getBody();
logger.info("header : {}, body : {}", header, body);
return claimsJws;
}
/**
* description: 从token中获取用户名
*
* @param token
* @return java.lang.String
*/
public static String getUsername(String token){
return getTokenBody(token).getSubject();
}
// 获取用户角色
public static List<String> getUserRole(String token){
return (List<String>) getTokenBody(token).get(ROLE_CLAIMS);
}
/**
* description: 判断Token是否过期
*
* @param token
* @return boolean
*/
public static boolean isExpiration(String token){
return getTokenBody(token).getExpiration().before(new Date());
}
/**
* description: 获取
*
* @param token
* @return io.jsonwebtoken.Claims
*/
private static Claims getTokenBody(String token) {
return Jwts.parser()
.setSigningKey(PRIMARY_KEY)
.parseClaimsJws(token)
.getBody();
}
}
| CherishHan/video | src/main/java/com/brayden/video/util/JwtTokenUtils.java | 774 | //采用HS256算法对JWT进行的签名,PRIMARY_KEY是我们的密钥 | line_comment | zh-cn | package com.brayden.video.util;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class JwtTokenUtils {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
//密钥,用于signature(签名)部分解密
private static final String PRIMARY_KEY = "jwtsecretdemo";
//签发者
private static final String ISS = "Gent.Ni";
// 添加角色的key
private static final String ROLE_CLAIMS = "role";
// 过期时间是3600秒,既是1个小时
private static final long EXPIRATION = 3600L;
// 选择了记住我之后的过期时间为7天
private static final long EXPIRATION_REMEMBER = 604800L;
private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
/**
* description: 创建Token
*
* @param username
* @param isRememberMe
* @return java.lang.String
*/
public static String createToken(String username, List<String> roles, boolean isRememberMe) {
long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
HashMap<String, Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, roles);
return Jwts.builder()
//采用 <SUF>
.signWith(SignatureAlgorithm.HS256, PRIMARY_KEY)
//设置角色名
.setClaims(map)
//设置发证人
.setIssuer(ISS)
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.compact();
}
public static Jws<Claims> decode(String token){
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(PRIMARY_KEY).parseClaimsJws(token);
JwsHeader header = claimsJws.getHeader();
Claims body = claimsJws.getBody();
logger.info("header : {}, body : {}", header, body);
return claimsJws;
}
/**
* description: 从token中获取用户名
*
* @param token
* @return java.lang.String
*/
public static String getUsername(String token){
return getTokenBody(token).getSubject();
}
// 获取用户角色
public static List<String> getUserRole(String token){
return (List<String>) getTokenBody(token).get(ROLE_CLAIMS);
}
/**
* description: 判断Token是否过期
*
* @param token
* @return boolean
*/
public static boolean isExpiration(String token){
return getTokenBody(token).getExpiration().before(new Date());
}
/**
* description: 获取
*
* @param token
* @return io.jsonwebtoken.Claims
*/
private static Claims getTokenBody(String token) {
return Jwts.parser()
.setSigningKey(PRIMARY_KEY)
.parseClaimsJws(token)
.getBody();
}
}
| 0 | 38 | 0 |
48146_0 | package com.zsml.textbannerview;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;
import com.superluo.textbannerlibrary.ITextBannerItemClickListener;
import com.superluo.textbannerlibrary.TextBannerView;
import com.zsml.textbannerview.utils.StatusBarUtil;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private TextBannerView mTvBanner;
private TextBannerView mTvBanner1;
private TextBannerView mTvBanner2;
private TextBannerView mTvBanner3;
private TextBannerView mTvBanner4;
private List<String> mList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StatusBarUtil.immersive(this);
initView();
initData();
setListener();
}
private void initView() {
setContentView(R.layout.activity_main);
mTvBanner = findViewById(R.id.tv_banner);
mTvBanner1 = findViewById(R.id.tv_banner1);
mTvBanner2 = findViewById(R.id.tv_banner2);
mTvBanner3 = findViewById(R.id.tv_banner3);
mTvBanner4 = findViewById(R.id.tv_banner4);
}
private void initData() {
mList = new ArrayList<>();
mList.add("学好Java、Android、C#、C、ios、html+css+js");
mList.add("走遍天下都不怕!!!!!");
mList.add("不是我吹,就怕你做不到,哈哈");
mList.add("superluo");
mList.add("你是最棒的,奔跑吧孩子!");
/**
* 设置数据,方式一
*/
mTvBanner.setDatas(mList);
mTvBanner.setDatas(mList);
mTvBanner1.setDatas(mList);
mTvBanner2.setDatas(mList);
mTvBanner3.setDatas(mList);
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
/**
* 设置数据(带图标的数据),方式二
*/
//第一个参数:数据 。第二参数:drawable. 第三参数drawable尺寸。第四参数图标位置
mTvBanner4.setDatasWithDrawableIcon(mList,drawable,18, Gravity.LEFT);
}
private void setListener() {
mTvBanner.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner1.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner2.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner3.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner4.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
/**调用startViewAnimator()重新开始文字轮播*/
mTvBanner.startViewAnimator();
mTvBanner1.startViewAnimator();
mTvBanner2.startViewAnimator();
mTvBanner3.startViewAnimator();
mTvBanner4.startViewAnimator();
}
@Override
protected void onStop() {
super.onStop();
/**调用stopViewAnimator()暂停文字轮播,避免文字重影*/
mTvBanner.stopViewAnimator();
mTvBanner1.stopViewAnimator();
mTvBanner2.stopViewAnimator();
mTvBanner3.stopViewAnimator();
mTvBanner4.stopViewAnimator();
}
}
| ChessLuo/TextBannerView | app/src/main/java/com/zsml/textbannerview/MainActivity.java | 1,099 | /**
* 设置数据,方式一
*/ | block_comment | zh-cn | package com.zsml.textbannerview;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;
import com.superluo.textbannerlibrary.ITextBannerItemClickListener;
import com.superluo.textbannerlibrary.TextBannerView;
import com.zsml.textbannerview.utils.StatusBarUtil;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private TextBannerView mTvBanner;
private TextBannerView mTvBanner1;
private TextBannerView mTvBanner2;
private TextBannerView mTvBanner3;
private TextBannerView mTvBanner4;
private List<String> mList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StatusBarUtil.immersive(this);
initView();
initData();
setListener();
}
private void initView() {
setContentView(R.layout.activity_main);
mTvBanner = findViewById(R.id.tv_banner);
mTvBanner1 = findViewById(R.id.tv_banner1);
mTvBanner2 = findViewById(R.id.tv_banner2);
mTvBanner3 = findViewById(R.id.tv_banner3);
mTvBanner4 = findViewById(R.id.tv_banner4);
}
private void initData() {
mList = new ArrayList<>();
mList.add("学好Java、Android、C#、C、ios、html+css+js");
mList.add("走遍天下都不怕!!!!!");
mList.add("不是我吹,就怕你做不到,哈哈");
mList.add("superluo");
mList.add("你是最棒的,奔跑吧孩子!");
/**
* 设置数 <SUF>*/
mTvBanner.setDatas(mList);
mTvBanner.setDatas(mList);
mTvBanner1.setDatas(mList);
mTvBanner2.setDatas(mList);
mTvBanner3.setDatas(mList);
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
/**
* 设置数据(带图标的数据),方式二
*/
//第一个参数:数据 。第二参数:drawable. 第三参数drawable尺寸。第四参数图标位置
mTvBanner4.setDatasWithDrawableIcon(mList,drawable,18, Gravity.LEFT);
}
private void setListener() {
mTvBanner.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner1.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner2.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner3.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
mTvBanner4.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Toast.makeText(MainActivity.this, String.valueOf(position)+">>"+data, Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
/**调用startViewAnimator()重新开始文字轮播*/
mTvBanner.startViewAnimator();
mTvBanner1.startViewAnimator();
mTvBanner2.startViewAnimator();
mTvBanner3.startViewAnimator();
mTvBanner4.startViewAnimator();
}
@Override
protected void onStop() {
super.onStop();
/**调用stopViewAnimator()暂停文字轮播,避免文字重影*/
mTvBanner.stopViewAnimator();
mTvBanner1.stopViewAnimator();
mTvBanner2.stopViewAnimator();
mTvBanner3.stopViewAnimator();
mTvBanner4.stopViewAnimator();
}
}
| 0 | 35 | 0 |
65338_8 | package cn.ofpp;
import cn.ofpp.core.BoyFriend;
import cn.ofpp.core.GirlFriend;
import cn.ofpp.core.MessageFactory;
import cn.ofpp.core.Wx;
/**
* 启动类
*
* 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容
* <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a>
*
* @author DokiYolo
* Date 2022-08-22
*/
public class Application {
/**
* <li>创建配置</li>
* <li>创建几个 男/女 朋友</li>
* <li>发消息</li>
*/
public static void main(String[] args) {
// load and init
Bootstrap.init();
// ----------------- 以下为演示数据 ------------------------
// new 一个 女友
// GirlFriend girlFriend = new GirlFriend("某女友",
// "江苏省", "南京市", "1999-08-08", "2011-04-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM");
// Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend));
// new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息
BoyFriend boyFriend = new BoyFriend("陈攀宇",
"浙江省", "温岭市", "2003-07-13", "2022-08-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM", "rHwobdNNt4ZrlbVXtnassfGIhocIhVe69z2iQNW_yeM");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend));
}
}
| Chicksqace/Weather-forecast-and-greetings | src/main/java/cn/ofpp/Application.java | 532 | // new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息 | line_comment | zh-cn | package cn.ofpp;
import cn.ofpp.core.BoyFriend;
import cn.ofpp.core.GirlFriend;
import cn.ofpp.core.MessageFactory;
import cn.ofpp.core.Wx;
/**
* 启动类
*
* 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容
* <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a>
*
* @author DokiYolo
* Date 2022-08-22
*/
public class Application {
/**
* <li>创建配置</li>
* <li>创建几个 男/女 朋友</li>
* <li>发消息</li>
*/
public static void main(String[] args) {
// load and init
Bootstrap.init();
// ----------------- 以下为演示数据 ------------------------
// new 一个 女友
// GirlFriend girlFriend = new GirlFriend("某女友",
// "江苏省", "南京市", "1999-08-08", "2011-04-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM");
// Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend));
// ne <SUF>
BoyFriend boyFriend = new BoyFriend("陈攀宇",
"浙江省", "温岭市", "2003-07-13", "2022-08-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM", "rHwobdNNt4ZrlbVXtnassfGIhocIhVe69z2iQNW_yeM");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend));
}
}
| 1 | 44 | 1 |
66472_40 | package com.bilibili.diyviewcomponent.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class PathView extends View {
private Paint mPaint;
public PathView(Context context) {
this(context, null);
}
public PathView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint();
}
private void initPaint() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//普通PATH
// Path path = new Path();
// path.moveTo(100, 100);
// path.lineTo(200, 200);
// path.lineTo(100, 300);
// path.close();
// canvas.drawPath(path, mPaint);
//矩形路径
//逆时针
// Path ccwPath = new Path();
// RectF ccwRect = new RectF(100, 100, 400, 400);
// ccwPath.addRect(ccwRect, Path.Direction.CCW);
// canvas.drawPath(ccwPath, mPaint);
//顺时针
// Path cwPath = new Path();
// RectF cwRect = new RectF(500, 500, 700, 700);
// cwPath.addRect(cwRect, Path.Direction.CW);
// canvas.drawPath(cwPath, mPaint);
//
// String text = "打败鸣人的办法,堵了她的嘴,打败路飞的办法,把肉扔海里,打败纳兹的办法,把他音响砸了!";
// canvas.drawTextOnPath(text, ccwPath, 0, 18, mPaint);
// canvas.drawTextOnPath(text, cwPath, 0, 18, mPaint);
//圆角矩形路径
// RectF rectF = new RectF(200, 800, 400, 900);
// Path roundCcwPath = new Path();
// roundCcwPath.addRoundRect(rectF, 10, 15, Path.Direction.CCW);
// canvas.drawPath(roundCcwPath, mPaint);
//
// RectF rectF1 = new RectF(500, 800, 700, 900);
// Path roundCwPath = new Path();
// float[] radius = new float[]{10, 15, 20, 25, 30, 35, 80, 90};
// roundCwPath.addRoundRect(rectF1, radius, Path.Direction.CCW);
// canvas.drawPath(roundCwPath, mPaint);
//圆形路径
// Path circlePath = new Path();
// circlePath.addCircle(300 ,1200 ,100 , Path.Direction.CCW);
// canvas.drawPath(circlePath ,mPaint);
//椭圆形路径
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Path roundOath = new Path();
// roundOath.addOval(300 ,1400 ,500 ,1600 , Path.Direction.CCW);
// canvas.drawPath(roundOath ,mPaint);
// }
//画弧形
// Path arcPath = new Path();
// RectF arcRect = new RectF(300 ,1700 ,500 ,1500);
// arcPath.addArc(arcRect ,0 ,120);
// canvas.drawPath(arcPath ,mPaint);
//文字
mPaint.setTextSize(80);
mPaint.setStrokeWidth(5);
mPaint.setTextSkewX((float) -0.25f);
canvas.drawText("妖精的尾巴", 0, 100, mPaint);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawText("妖精的尾巴", 0, 200, mPaint);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawText("妖精的尾巴", 0, 300, mPaint);
// Typeface create可修改字体
}
}
| Chihiro23333/ChidoriX | diyviewcomponent/src/main/java/com/bilibili/diyviewcomponent/view/PathView.java | 1,212 | //画弧形 | line_comment | zh-cn | package com.bilibili.diyviewcomponent.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class PathView extends View {
private Paint mPaint;
public PathView(Context context) {
this(context, null);
}
public PathView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint();
}
private void initPaint() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//普通PATH
// Path path = new Path();
// path.moveTo(100, 100);
// path.lineTo(200, 200);
// path.lineTo(100, 300);
// path.close();
// canvas.drawPath(path, mPaint);
//矩形路径
//逆时针
// Path ccwPath = new Path();
// RectF ccwRect = new RectF(100, 100, 400, 400);
// ccwPath.addRect(ccwRect, Path.Direction.CCW);
// canvas.drawPath(ccwPath, mPaint);
//顺时针
// Path cwPath = new Path();
// RectF cwRect = new RectF(500, 500, 700, 700);
// cwPath.addRect(cwRect, Path.Direction.CW);
// canvas.drawPath(cwPath, mPaint);
//
// String text = "打败鸣人的办法,堵了她的嘴,打败路飞的办法,把肉扔海里,打败纳兹的办法,把他音响砸了!";
// canvas.drawTextOnPath(text, ccwPath, 0, 18, mPaint);
// canvas.drawTextOnPath(text, cwPath, 0, 18, mPaint);
//圆角矩形路径
// RectF rectF = new RectF(200, 800, 400, 900);
// Path roundCcwPath = new Path();
// roundCcwPath.addRoundRect(rectF, 10, 15, Path.Direction.CCW);
// canvas.drawPath(roundCcwPath, mPaint);
//
// RectF rectF1 = new RectF(500, 800, 700, 900);
// Path roundCwPath = new Path();
// float[] radius = new float[]{10, 15, 20, 25, 30, 35, 80, 90};
// roundCwPath.addRoundRect(rectF1, radius, Path.Direction.CCW);
// canvas.drawPath(roundCwPath, mPaint);
//圆形路径
// Path circlePath = new Path();
// circlePath.addCircle(300 ,1200 ,100 , Path.Direction.CCW);
// canvas.drawPath(circlePath ,mPaint);
//椭圆形路径
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Path roundOath = new Path();
// roundOath.addOval(300 ,1400 ,500 ,1600 , Path.Direction.CCW);
// canvas.drawPath(roundOath ,mPaint);
// }
//画弧 <SUF>
// Path arcPath = new Path();
// RectF arcRect = new RectF(300 ,1700 ,500 ,1500);
// arcPath.addArc(arcRect ,0 ,120);
// canvas.drawPath(arcPath ,mPaint);
//文字
mPaint.setTextSize(80);
mPaint.setStrokeWidth(5);
mPaint.setTextSkewX((float) -0.25f);
canvas.drawText("妖精的尾巴", 0, 100, mPaint);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawText("妖精的尾巴", 0, 200, mPaint);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawText("妖精的尾巴", 0, 300, mPaint);
// Typeface create可修改字体
}
}
| 1 | 5 | 1 |
28386_4 | package com.cxd.algorithm.sort;
/**
* 冒泡排序
*
* 重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。
* 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
* 这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
*
* 最好情况下:正序有序,则只需要比较n次。故,为O(n)
*
* 最坏情况下:逆序有序,则需要比较(n-1)+(n-2)+……+1,故为O(n*n)
*
* 排序过程中只交换相邻两个元素的位置。因此,当两个数相等时,是没必要交换两个数的位置的。所以,它们的相对位置并没有改变,冒泡排序算法是稳定的!
*
* @author childe
* @date 2018/6/20 19:39
**/
public class BubbleSort {
// 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
// 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
// 针对所有的元素重复以上的步骤,除了最后一个。
// 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
static int[] sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
// 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
}
| Childe-Chen/goodGoodStudy | src/main/java/com/cxd/algorithm/sort/BubbleSort.java | 565 | // 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 | line_comment | zh-cn | package com.cxd.algorithm.sort;
/**
* 冒泡排序
*
* 重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。
* 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
* 这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
*
* 最好情况下:正序有序,则只需要比较n次。故,为O(n)
*
* 最坏情况下:逆序有序,则需要比较(n-1)+(n-2)+……+1,故为O(n*n)
*
* 排序过程中只交换相邻两个元素的位置。因此,当两个数相等时,是没必要交换两个数的位置的。所以,它们的相对位置并没有改变,冒泡排序算法是稳定的!
*
* @author childe
* @date 2018/6/20 19:39
**/
public class BubbleSort {
// 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
// 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
// 针对所有的元素重复以上的步骤,除了最后一个。
// 持续 <SUF>
static int[] sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
// 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
}
| 1 | 41 | 1 |
40532_2 | package com.lhr.jiandou.adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.lhr.jiandou.R;
import com.lhr.jiandou.adapter.base.BasePagerAdapter;
import com.lhr.jiandou.model.bean.SubjectsBean;
import java.util.List;
/**
* Created by ChinaLHR on 2016/12/30.
* Email:[email protected]
*/
public class PageTopAdapter extends BasePagerAdapter<SubjectsBean> {
public PageTopAdapter(Context context, List<SubjectsBean> date) {
super(context, date);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_top250, parent, false);
return new TopHolder(view);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (mDate.size()>1) {
if (getItemViewType(position) == TYPE_FOOTER) return;
((TopHolder)holder).top_movie_brief.setText("");
Glide.with(mContext)
.load(mDate.get(position).getImages().getLarge())
.into(((TopHolder) holder).top_img);
((TopHolder) holder).top_movie_title.setText(mDate.get(position).getTitle());
((TopHolder) holder).top_num.setText(position+1+"");
((TopHolder) holder).top_movie_ratingnum.setText(mDate.get(position).getRating().getAverage() + "");
((TopHolder) holder).top_movie_ratingbar.setRating((float) mDate.get(position).getRating().getAverage() / 2);
/**
* 上映时间
*/
if (!mDate.get(position).getYear().trim().equals("")) {
((TopHolder) holder).top_movie_brief.append("上映时间:");
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getYear() + "\n");
}
/**
* 导演信息
*/
if (mDate.get(position).getDirectors() != null) {
((TopHolder) holder).top_movie_brief.append("导演:");
for (int i = 0; i < mDate.get(position).getDirectors().size(); i++) {
if (i == mDate.get(position).getDirectors().size() - 1) {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName());
} else {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName() + "/");
}
}
((TopHolder) holder).top_movie_brief.append("\n");
}
/**
* 演员信息
*/
if (mDate.get(position).getCasts() != null) {
((TopHolder) holder).top_movie_brief.append("演员:");
for (int i = 0; i < mDate.get(position).getCasts().size(); i++) {
if (i == mDate.get(position).getCasts().size()-1) {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName());
} else {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName() + "/");
}
}
((TopHolder) holder).top_movie_brief.append("\n");
}
/**
* 类型信息
*/
if (mDate.get(position).getCasts() != null) {
((TopHolder) holder).top_movie_brief.append("类型:");
for (int i = 0; i < mDate.get(position).getGenres().size(); i++) {
if (i == mDate.get(position).getGenres().size() - 1) {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i));
} else {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i) + "/");
}
}
((TopHolder) holder).top_movie_brief.append("\n");
}
}
if (mListener!=null){
((TopHolder)holder).top_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getLayoutPosition();
mListener.ItemClickListener(holder.itemView, mDate.get(position).getId(),mDate.get(position).getImages().getLarge());
}
});
}
}
class TopHolder extends RecyclerView.ViewHolder {
TextView top_num;
ImageView top_img;
TextView top_movie_title;
RatingBar top_movie_ratingbar;
TextView top_movie_ratingnum;
TextView top_movie_brief;
CardView top_card;
public TopHolder(View itemView) {
super(itemView);
top_card = (CardView) itemView.findViewById(R.id.top_card);
top_num = (TextView) itemView.findViewById(R.id.top_num);
top_img = (ImageView) itemView.findViewById(R.id.top_img);
top_movie_title = (TextView) itemView.findViewById(R.id.top_movie_title);
top_movie_ratingbar = (RatingBar) itemView.findViewById(R.id.top_movie_ratingbar);
top_movie_ratingnum = (TextView) itemView.findViewById(R.id.top_movie_ratingnum);
top_movie_brief = (TextView) itemView.findViewById(R.id.top_movie_brief);
}
}
}
| ChinaLHR/JianDou | app/src/main/java/com/lhr/jiandou/adapter/PageTopAdapter.java | 1,508 | /**
* 导演信息
*/ | block_comment | zh-cn | package com.lhr.jiandou.adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.lhr.jiandou.R;
import com.lhr.jiandou.adapter.base.BasePagerAdapter;
import com.lhr.jiandou.model.bean.SubjectsBean;
import java.util.List;
/**
* Created by ChinaLHR on 2016/12/30.
* Email:[email protected]
*/
public class PageTopAdapter extends BasePagerAdapter<SubjectsBean> {
public PageTopAdapter(Context context, List<SubjectsBean> date) {
super(context, date);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_top250, parent, false);
return new TopHolder(view);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (mDate.size()>1) {
if (getItemViewType(position) == TYPE_FOOTER) return;
((TopHolder)holder).top_movie_brief.setText("");
Glide.with(mContext)
.load(mDate.get(position).getImages().getLarge())
.into(((TopHolder) holder).top_img);
((TopHolder) holder).top_movie_title.setText(mDate.get(position).getTitle());
((TopHolder) holder).top_num.setText(position+1+"");
((TopHolder) holder).top_movie_ratingnum.setText(mDate.get(position).getRating().getAverage() + "");
((TopHolder) holder).top_movie_ratingbar.setRating((float) mDate.get(position).getRating().getAverage() / 2);
/**
* 上映时间
*/
if (!mDate.get(position).getYear().trim().equals("")) {
((TopHolder) holder).top_movie_brief.append("上映时间:");
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getYear() + "\n");
}
/**
* 导演信 <SUF>*/
if (mDate.get(position).getDirectors() != null) {
((TopHolder) holder).top_movie_brief.append("导演:");
for (int i = 0; i < mDate.get(position).getDirectors().size(); i++) {
if (i == mDate.get(position).getDirectors().size() - 1) {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName());
} else {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName() + "/");
}
}
((TopHolder) holder).top_movie_brief.append("\n");
}
/**
* 演员信息
*/
if (mDate.get(position).getCasts() != null) {
((TopHolder) holder).top_movie_brief.append("演员:");
for (int i = 0; i < mDate.get(position).getCasts().size(); i++) {
if (i == mDate.get(position).getCasts().size()-1) {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName());
} else {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName() + "/");
}
}
((TopHolder) holder).top_movie_brief.append("\n");
}
/**
* 类型信息
*/
if (mDate.get(position).getCasts() != null) {
((TopHolder) holder).top_movie_brief.append("类型:");
for (int i = 0; i < mDate.get(position).getGenres().size(); i++) {
if (i == mDate.get(position).getGenres().size() - 1) {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i));
} else {
((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i) + "/");
}
}
((TopHolder) holder).top_movie_brief.append("\n");
}
}
if (mListener!=null){
((TopHolder)holder).top_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getLayoutPosition();
mListener.ItemClickListener(holder.itemView, mDate.get(position).getId(),mDate.get(position).getImages().getLarge());
}
});
}
}
class TopHolder extends RecyclerView.ViewHolder {
TextView top_num;
ImageView top_img;
TextView top_movie_title;
RatingBar top_movie_ratingbar;
TextView top_movie_ratingnum;
TextView top_movie_brief;
CardView top_card;
public TopHolder(View itemView) {
super(itemView);
top_card = (CardView) itemView.findViewById(R.id.top_card);
top_num = (TextView) itemView.findViewById(R.id.top_num);
top_img = (ImageView) itemView.findViewById(R.id.top_img);
top_movie_title = (TextView) itemView.findViewById(R.id.top_movie_title);
top_movie_ratingbar = (RatingBar) itemView.findViewById(R.id.top_movie_ratingbar);
top_movie_ratingnum = (TextView) itemView.findViewById(R.id.top_movie_ratingnum);
top_movie_brief = (TextView) itemView.findViewById(R.id.top_movie_brief);
}
}
}
| 1 | 39 | 1 |
41450_2 | package com.ming.wowomall.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author [email protected]
* @date 18-9-15 下午3:33
*/
@Slf4j
public class CookieUtil {
private static final String COOKIE_DOMAIN = "wowomall.com";
private static final String COOKIE_NAME = "wowomall_session_token";
/**
* 登录默认一年有效期
*/
private static final int COOKIE_LOGIN_AGE = 60 * 60 * 24 * 365;
public static void writeLoginToken(HttpServletResponse response, String token) {
Cookie cookie = new Cookie(COOKIE_NAME, token);
cookie.setDomain(COOKIE_DOMAIN);
//单位秒 -1永久 0清楚,不写默认写到内存
cookie.setMaxAge(COOKIE_LOGIN_AGE);
//不许通过脚本访问cookie
cookie.setHttpOnly(true);
//代表在根目录
cookie.setPath("/");
response.addCookie(cookie);
log.info("writeLoginToken cookieName:{},value:{}", COOKIE_NAME, token);
}
public static void delLoginToken(HttpServletRequest request,HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie ck : cookies) {
if (StringUtils.equals(COOKIE_NAME, ck.getName())) {
log.info("delLoginToken cookieName:{},value:{}", COOKIE_NAME, ck.getValue());
ck.setDomain(COOKIE_DOMAIN);
ck.setPath("/");
ck.setMaxAge(0);
response.addCookie(ck);
return;
}
}
}
}
public static String readLoginToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(COOKIE_NAME, cookie.getName())) {
log.info("readLoginToken cookieName:{},value:{}", COOKIE_NAME, cookie.getValue());
return cookie.getValue();
}
}
}
return null;
}
}
| ChinaWim/WoWoMall | src/main/java/com/ming/wowomall/util/CookieUtil.java | 552 | //单位秒 -1永久 0清楚,不写默认写到内存 | line_comment | zh-cn | package com.ming.wowomall.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author [email protected]
* @date 18-9-15 下午3:33
*/
@Slf4j
public class CookieUtil {
private static final String COOKIE_DOMAIN = "wowomall.com";
private static final String COOKIE_NAME = "wowomall_session_token";
/**
* 登录默认一年有效期
*/
private static final int COOKIE_LOGIN_AGE = 60 * 60 * 24 * 365;
public static void writeLoginToken(HttpServletResponse response, String token) {
Cookie cookie = new Cookie(COOKIE_NAME, token);
cookie.setDomain(COOKIE_DOMAIN);
//单位 <SUF>
cookie.setMaxAge(COOKIE_LOGIN_AGE);
//不许通过脚本访问cookie
cookie.setHttpOnly(true);
//代表在根目录
cookie.setPath("/");
response.addCookie(cookie);
log.info("writeLoginToken cookieName:{},value:{}", COOKIE_NAME, token);
}
public static void delLoginToken(HttpServletRequest request,HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie ck : cookies) {
if (StringUtils.equals(COOKIE_NAME, ck.getName())) {
log.info("delLoginToken cookieName:{},value:{}", COOKIE_NAME, ck.getValue());
ck.setDomain(COOKIE_DOMAIN);
ck.setPath("/");
ck.setMaxAge(0);
response.addCookie(ck);
return;
}
}
}
}
public static String readLoginToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(COOKIE_NAME, cookie.getName())) {
log.info("readLoginToken cookieName:{},value:{}", COOKIE_NAME, cookie.getValue());
return cookie.getValue();
}
}
}
return null;
}
}
| 0 | 23 | 0 |
48416_2 | package com.lbwan.game.room.gameTeam;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lbwan.game.room.roomGame.GamePlayer;
import com.lbwan.game.utils.GDPropertiesUtils;
import com.lbwan.game.porkerEnumSet.FaceValueEnum;
public class Team {
private Log logger = LogFactory.getLog(getClass());
// 该队伍的主牌
private int majorFaceValue = GDPropertiesUtils.getPropertyAsInteger(GDPropertiesUtils.DEFAULT_MAJOR_CARD);;
private boolean winTheGame = false;
// 队伍
private Map<String, GamePlayer> gamePlayerMap = new HashMap<String, GamePlayer>();
public Team(String strPlayerOne, String strPlayerTwo, TeamGroup teamGroup){
GamePlayer playerOne = new GamePlayer(strPlayerOne, teamGroup);
playerOne.initTeamPlayer(strPlayerTwo);
gamePlayerMap.put(strPlayerOne, playerOne);
GamePlayer playerTwo = new GamePlayer(strPlayerTwo, teamGroup);
playerTwo.initTeamPlayer(strPlayerOne);
gamePlayerMap.put(strPlayerTwo, playerTwo);
majorFaceValue = 2;
winTheGame = false;
}
public void initControlNextPlayer(String strControlerId, String strNextUserId){
GamePlayer controlPlayer = gamePlayerMap.get(strControlerId);
if(null == controlPlayer){
logger.error("Team::initControlNextPlayer controlPlayer Null Error");
return ;
}
controlPlayer.initNextPlayerUserId(strNextUserId);
}
public GamePlayer searchPlayer(String strSearchUser){
GamePlayer controlPlayer = gamePlayerMap.get(strSearchUser);
if(null == controlPlayer){
return null;
}
return controlPlayer;
}
public int getMajorFace(){
return this.majorFaceValue;
}
public void resetNewMajorFaceValue(int nNewMajorFaceValue){
this.majorFaceValue = nNewMajorFaceValue;
}
public int getHandOutPorkerNumOfTeam(){
int nHandOutPlayers = 0;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::initControlNextPlayer player Null Error");
continue;
}
if(0 == player.getPlayerHandPorkerNum()){
nHandOutPlayers = nHandOutPlayers + 1;
continue;
}
}
return nHandOutPlayers;
}
public int teamPlayerNum(){
return gamePlayerMap.size();
}
public void winTheGame(){
this.winTheGame = true;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::winTheGame player Null Error");
continue;
}
player.winTheGameOfThisRound();
}
}
public boolean isTeamWinTheGame(){
if(true == this.winTheGame){
return true;
}
return false;
}
public void initNewRound(){
winTheGame = false;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::initNewRound() player Null Error");
continue;
}
// 初始化
player.initPlayerData();
}
}
// 计算排位
public void calculateRank(TeamGroup teamGroup){
if(null == teamGroup){
logger.error("Team::calculateRank teamGroup Null Error");
return ;
}
GamePlayer minPlayer = new GamePlayer("MinPlayer", null);
minPlayer.resetToTestGamePlayer();
GamePlayer secondMinPlayer = new GamePlayer("SecondMinPlayer", null);
secondMinPlayer.resetToTestGamePlayer();
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::calculateRank player Null Error");
continue;
}
// 手上没有牌了 则直接continue;
int nHandPorkerNum = player.getPlayerHandPorkerNum();
if(0 == nHandPorkerNum){
continue;
}
// 小于最小值
if(nHandPorkerNum < minPlayer.getPlayerHandPorkerNum()){
secondMinPlayer = minPlayer;
minPlayer = player;
}else if((nHandPorkerNum >= minPlayer.getPlayerHandPorkerNum()) && (nHandPorkerNum < secondMinPlayer.getPlayerHandPorkerNum())){
// 大于等于最小值 并且 小于最大值
secondMinPlayer = player;
}
}
if(false == minPlayer.isTestPlayer()){
minPlayer.recordOutPorkerPlayer(teamGroup);
}
if(false == secondMinPlayer.isTestPlayer()){
secondMinPlayer.recordOutPorkerPlayer(teamGroup);
}
}
// 主牌做相对应的升级
public void upMajorFaceValue(){
int nLastHandOut = 0, nFirstHandOut = 0;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::upMajorFaceValue player Null Error");
continue;
}
int nOutPorkerRank = player.getOutAllPorkerRank();
if(1 == nOutPorkerRank){
nFirstHandOut = nFirstHandOut + 1;
continue;
}
nLastHandOut = nOutPorkerRank;
}
if(1 != nFirstHandOut){
logger.error("Team::upMajorFaceValue server Error");
return ;
}
int nNewMajorFaceValue = this.calcuNewMajorValue(nLastHandOut);
if(0 == nNewMajorFaceValue){
logger.error("Team::upMajorFaceValue server Error Of calcuNewMajorValue");
return ;
}
this.resetNewMajorFaceValue(nNewMajorFaceValue);
}
private int calcuNewMajorValue(int nLastHandOut){
int nAddValue = 0;
switch(nLastHandOut){
// 第二个出完牌 则升三级
case 2:
nAddValue = 3;
break;
case 3:
nAddValue = 2;
break;
case 4:
nAddValue = 1;
break;
default:
logger.error("Team::calcuNewMajorValue server Error");
break;
}
// 判断是否达到A
int nCurrentMajorValue = this.getMajorFace();
if(FaceValueEnum.FACE_VALUE_A_VALUE == nCurrentMajorValue){
return (nAddValue + 1);
}
int nNewFaceValue = nCurrentMajorValue + nAddValue;
// A必须打
if(nNewFaceValue >= FaceValueEnum.FACE_VALUE_A_VALUE){
nNewFaceValue = FaceValueEnum.FACE_VALUE_A_VALUE;
return nNewFaceValue;
}
return nNewFaceValue;
}
// 是否是双下
public boolean isDoubleLow(){
// 赢得比赛 则不是
boolean bIsDoubleLowResult = false;
if(true == this.isTeamWinTheGame()){
return bIsDoubleLowResult;
}
Set<Integer> doubelLowSet = new HashSet<>();
doubelLowSet.add(3);
doubelLowSet.add(4);
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::isDoubleLow() player Null Error");
continue;
}
boolean bIsDouble = doubelLowSet.contains(player.getOutAllPorkerRank());
if(false == bIsDouble){
return bIsDoubleLowResult;
}
}
bIsDoubleLowResult = true;
return bIsDoubleLowResult;
}
public Map<String, GamePlayer> getAllTeamMembers(){
return gamePlayerMap;
}
}
| ChinaZZH/GuanDan | game/room/gameTeam/Team.java | 2,349 | // 计算排位 | line_comment | zh-cn | package com.lbwan.game.room.gameTeam;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lbwan.game.room.roomGame.GamePlayer;
import com.lbwan.game.utils.GDPropertiesUtils;
import com.lbwan.game.porkerEnumSet.FaceValueEnum;
public class Team {
private Log logger = LogFactory.getLog(getClass());
// 该队伍的主牌
private int majorFaceValue = GDPropertiesUtils.getPropertyAsInteger(GDPropertiesUtils.DEFAULT_MAJOR_CARD);;
private boolean winTheGame = false;
// 队伍
private Map<String, GamePlayer> gamePlayerMap = new HashMap<String, GamePlayer>();
public Team(String strPlayerOne, String strPlayerTwo, TeamGroup teamGroup){
GamePlayer playerOne = new GamePlayer(strPlayerOne, teamGroup);
playerOne.initTeamPlayer(strPlayerTwo);
gamePlayerMap.put(strPlayerOne, playerOne);
GamePlayer playerTwo = new GamePlayer(strPlayerTwo, teamGroup);
playerTwo.initTeamPlayer(strPlayerOne);
gamePlayerMap.put(strPlayerTwo, playerTwo);
majorFaceValue = 2;
winTheGame = false;
}
public void initControlNextPlayer(String strControlerId, String strNextUserId){
GamePlayer controlPlayer = gamePlayerMap.get(strControlerId);
if(null == controlPlayer){
logger.error("Team::initControlNextPlayer controlPlayer Null Error");
return ;
}
controlPlayer.initNextPlayerUserId(strNextUserId);
}
public GamePlayer searchPlayer(String strSearchUser){
GamePlayer controlPlayer = gamePlayerMap.get(strSearchUser);
if(null == controlPlayer){
return null;
}
return controlPlayer;
}
public int getMajorFace(){
return this.majorFaceValue;
}
public void resetNewMajorFaceValue(int nNewMajorFaceValue){
this.majorFaceValue = nNewMajorFaceValue;
}
public int getHandOutPorkerNumOfTeam(){
int nHandOutPlayers = 0;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::initControlNextPlayer player Null Error");
continue;
}
if(0 == player.getPlayerHandPorkerNum()){
nHandOutPlayers = nHandOutPlayers + 1;
continue;
}
}
return nHandOutPlayers;
}
public int teamPlayerNum(){
return gamePlayerMap.size();
}
public void winTheGame(){
this.winTheGame = true;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::winTheGame player Null Error");
continue;
}
player.winTheGameOfThisRound();
}
}
public boolean isTeamWinTheGame(){
if(true == this.winTheGame){
return true;
}
return false;
}
public void initNewRound(){
winTheGame = false;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::initNewRound() player Null Error");
continue;
}
// 初始化
player.initPlayerData();
}
}
// 计算 <SUF>
public void calculateRank(TeamGroup teamGroup){
if(null == teamGroup){
logger.error("Team::calculateRank teamGroup Null Error");
return ;
}
GamePlayer minPlayer = new GamePlayer("MinPlayer", null);
minPlayer.resetToTestGamePlayer();
GamePlayer secondMinPlayer = new GamePlayer("SecondMinPlayer", null);
secondMinPlayer.resetToTestGamePlayer();
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::calculateRank player Null Error");
continue;
}
// 手上没有牌了 则直接continue;
int nHandPorkerNum = player.getPlayerHandPorkerNum();
if(0 == nHandPorkerNum){
continue;
}
// 小于最小值
if(nHandPorkerNum < minPlayer.getPlayerHandPorkerNum()){
secondMinPlayer = minPlayer;
minPlayer = player;
}else if((nHandPorkerNum >= minPlayer.getPlayerHandPorkerNum()) && (nHandPorkerNum < secondMinPlayer.getPlayerHandPorkerNum())){
// 大于等于最小值 并且 小于最大值
secondMinPlayer = player;
}
}
if(false == minPlayer.isTestPlayer()){
minPlayer.recordOutPorkerPlayer(teamGroup);
}
if(false == secondMinPlayer.isTestPlayer()){
secondMinPlayer.recordOutPorkerPlayer(teamGroup);
}
}
// 主牌做相对应的升级
public void upMajorFaceValue(){
int nLastHandOut = 0, nFirstHandOut = 0;
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::upMajorFaceValue player Null Error");
continue;
}
int nOutPorkerRank = player.getOutAllPorkerRank();
if(1 == nOutPorkerRank){
nFirstHandOut = nFirstHandOut + 1;
continue;
}
nLastHandOut = nOutPorkerRank;
}
if(1 != nFirstHandOut){
logger.error("Team::upMajorFaceValue server Error");
return ;
}
int nNewMajorFaceValue = this.calcuNewMajorValue(nLastHandOut);
if(0 == nNewMajorFaceValue){
logger.error("Team::upMajorFaceValue server Error Of calcuNewMajorValue");
return ;
}
this.resetNewMajorFaceValue(nNewMajorFaceValue);
}
private int calcuNewMajorValue(int nLastHandOut){
int nAddValue = 0;
switch(nLastHandOut){
// 第二个出完牌 则升三级
case 2:
nAddValue = 3;
break;
case 3:
nAddValue = 2;
break;
case 4:
nAddValue = 1;
break;
default:
logger.error("Team::calcuNewMajorValue server Error");
break;
}
// 判断是否达到A
int nCurrentMajorValue = this.getMajorFace();
if(FaceValueEnum.FACE_VALUE_A_VALUE == nCurrentMajorValue){
return (nAddValue + 1);
}
int nNewFaceValue = nCurrentMajorValue + nAddValue;
// A必须打
if(nNewFaceValue >= FaceValueEnum.FACE_VALUE_A_VALUE){
nNewFaceValue = FaceValueEnum.FACE_VALUE_A_VALUE;
return nNewFaceValue;
}
return nNewFaceValue;
}
// 是否是双下
public boolean isDoubleLow(){
// 赢得比赛 则不是
boolean bIsDoubleLowResult = false;
if(true == this.isTeamWinTheGame()){
return bIsDoubleLowResult;
}
Set<Integer> doubelLowSet = new HashSet<>();
doubelLowSet.add(3);
doubelLowSet.add(4);
Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator();
while(true == iter.hasNext()){
Map.Entry<String, GamePlayer> entry = iter.next();
GamePlayer player = entry.getValue();
if(null == player){
logger.error("Team::isDoubleLow() player Null Error");
continue;
}
boolean bIsDouble = doubelLowSet.contains(player.getOutAllPorkerRank());
if(false == bIsDouble){
return bIsDoubleLowResult;
}
}
bIsDoubleLowResult = true;
return bIsDoubleLowResult;
}
public Map<String, GamePlayer> getAllTeamMembers(){
return gamePlayerMap;
}
}
| 1 | 7 | 1 |
62721_0 | package com.teach.javafx.controller.honor;
import com.teach.javafx.AppStore;
import com.teach.javafx.MainApplication;
import com.teach.javafx.request.HttpRequestUtil;
import io.github.palexdev.materialfx.controls.MFXButton;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HonorCheckController {
private final String HONOR_TITLE = "HONOR_TITLE";
private final String HONOR_CONTEST = "HONOR_CONTEST";
private final String HONOR_TECH = "HONOR_TECH";
private final String HONOR_PRACTICE = "HONOR_PRACTICE";
private final String HONOR_INTERNSHIP = "HONOR_INTERNSHIP";
private final String HONOR_PROJ = "HONOR_PROJ";
private final String HONOR_LECTURE = "HONOR_LECTURE";
private final String BASE_URL = "/api/honor";
@FXML
private GridPane gridPane;
@FXML
private BorderPane borderPane;
private List<Map> honors = new ArrayList<>();
private List<Map> title = new ArrayList<>();
private List<Map> practice = new ArrayList<>();
private List<Map> internship = new ArrayList<>();
private List<Map> contest = new ArrayList<>();
private List<Map> tech = new ArrayList<>();
private List<Map> lecture = new ArrayList<>();
private List<Map> proj = new ArrayList<>();
private Stage filterStage = null;
@FXML
public void initialize(){
requestHonors();
arrangeHonor();
setDisplay();
}
public void requestHonors(){
DataRequest req = new DataRequest();
req.add("studentId", AppStore.getJwt().getRoleId());
DataResponse res = HttpRequestUtil.request(BASE_URL+"/getHonors",req);
if(res != null && res.getCode() == 0){
honors = (ArrayList<Map>)(res.getData());
System.out.println("已获取到当前学生的荣誉信息: " + honors);
}
else {
System.out.println("获取荣誉信息失败! ");
}
}
//将不同荣誉按类别分配到相应的数组中
public void arrangeHonor(){
for(Map m : honors){
String type = (String) m.get("honorType");
switch (type) {
case HONOR_TITLE -> title.add(m);
case HONOR_CONTEST -> contest.add(m);
case HONOR_INTERNSHIP -> internship.add(m);
case HONOR_PRACTICE -> practice.add(m);
case HONOR_PROJ -> proj.add(m);
case HONOR_TECH -> tech.add(m);
case HONOR_LECTURE -> lecture.add(m);
}
}
}
public void setDisplay(){
gridPane.getChildren().clear();
int row = 0;
gridPane.add(new Label("荣誉称号"), 0, row);
row = setItem(row, title);
gridPane.add(new Label("学科竞赛"), 0, row);
row = setItem(row, contest);
gridPane.add(new Label("社会实践"), 0, row);
row = setItem(row, practice);
gridPane.add(new Label("科技成果"), 0, row);
row = setItem(row, tech);
gridPane.add(new Label("校外实习"), 0, row);
row = setItem(row, internship);
gridPane.add(new Label("培训讲座"), 0, row);
row = setItem(row, lecture);
gridPane.add(new Label("创新项目"), 0, row);
row = setItem(row, proj);
int numOfHonors = honors.size();
if( numOfHonors == 0){
gridPane.add(new Label("你目前没有个人荣誉诶\n继续加油吧!"), 3, 0);
}
else if(numOfHonors <= 2){
gridPane.add(new Label("你目前有 " + numOfHonors + " 个荣誉耶\n小有成就!"), 3, 0);
}
else if(numOfHonors <= 5){
gridPane.add(new Label("真棒! 你现在有 " + numOfHonors + " 个荣誉\n再接再厉吧!"), 3, 0);
}
else {
gridPane.add(new Label("Wow,你现在有 " + numOfHonors + " 个荣誉\nAmazing!"), 3, 0);
}
}
private int setItem(int row, List<Map> title) {
for(Map m : title){
gridPane.add(new Label((String) m.get("honorContent")), 1, row);
row++;
}
if(title.isEmpty()){
gridPane.add(new Label("暂无奖项"),1,row);
row++;
}
return row;
}
public void openFilterWindow(List<Map> honors, String honorType){
FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource("honor/honor-filter-panel.fxml"));
try {
Scene scene = new Scene(loader.load(), 600, 400);
HonorFilterController honorFilterController = (HonorFilterController) loader.getController();
honorFilterController.setData(honors, honorType);
honorFilterController.setDisplay();
filterStage = new Stage();
filterStage.setScene(scene);
filterStage.setTitle(honorType);
filterStage.initOwner(getStage());
filterStage.initModality(Modality.WINDOW_MODAL);
filterStage.setOnCloseRequest(windowEvent -> filterStage = null);
filterStage.setResizable(false);
filterStage.show();
}
catch (IOException o){
System.out.println("打开分类浏览荣誉的视图失败: " + o.getMessage());
}
}
public void onFilterButtonClick(ActionEvent event) {
MFXButton btn = (MFXButton) event.getTarget();
String text = btn.getText();
switch (text) {
case "荣誉称号" -> openFilterWindow(title, text);
case "学科竞赛" -> openFilterWindow(contest, text);
case "科技成果" -> openFilterWindow(tech, text);
case "社会实践" -> openFilterWindow(practice, text);
case "培训讲座" -> openFilterWindow(lecture, text);
case "创新项目" -> openFilterWindow(proj, text);
case "校外实习" -> openFilterWindow(internship, text);
}
}
private Stage getStage(){
Scene scene = this.borderPane.getScene();
return (Stage) scene.getWindow();
}
}
| ChinesePlayer/2024CourseDesign | java2/java-fx/src/main/java/com/teach/javafx/controller/honor/HonorCheckController.java | 1,819 | //将不同荣誉按类别分配到相应的数组中 | line_comment | zh-cn | package com.teach.javafx.controller.honor;
import com.teach.javafx.AppStore;
import com.teach.javafx.MainApplication;
import com.teach.javafx.request.HttpRequestUtil;
import io.github.palexdev.materialfx.controls.MFXButton;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HonorCheckController {
private final String HONOR_TITLE = "HONOR_TITLE";
private final String HONOR_CONTEST = "HONOR_CONTEST";
private final String HONOR_TECH = "HONOR_TECH";
private final String HONOR_PRACTICE = "HONOR_PRACTICE";
private final String HONOR_INTERNSHIP = "HONOR_INTERNSHIP";
private final String HONOR_PROJ = "HONOR_PROJ";
private final String HONOR_LECTURE = "HONOR_LECTURE";
private final String BASE_URL = "/api/honor";
@FXML
private GridPane gridPane;
@FXML
private BorderPane borderPane;
private List<Map> honors = new ArrayList<>();
private List<Map> title = new ArrayList<>();
private List<Map> practice = new ArrayList<>();
private List<Map> internship = new ArrayList<>();
private List<Map> contest = new ArrayList<>();
private List<Map> tech = new ArrayList<>();
private List<Map> lecture = new ArrayList<>();
private List<Map> proj = new ArrayList<>();
private Stage filterStage = null;
@FXML
public void initialize(){
requestHonors();
arrangeHonor();
setDisplay();
}
public void requestHonors(){
DataRequest req = new DataRequest();
req.add("studentId", AppStore.getJwt().getRoleId());
DataResponse res = HttpRequestUtil.request(BASE_URL+"/getHonors",req);
if(res != null && res.getCode() == 0){
honors = (ArrayList<Map>)(res.getData());
System.out.println("已获取到当前学生的荣誉信息: " + honors);
}
else {
System.out.println("获取荣誉信息失败! ");
}
}
//将不 <SUF>
public void arrangeHonor(){
for(Map m : honors){
String type = (String) m.get("honorType");
switch (type) {
case HONOR_TITLE -> title.add(m);
case HONOR_CONTEST -> contest.add(m);
case HONOR_INTERNSHIP -> internship.add(m);
case HONOR_PRACTICE -> practice.add(m);
case HONOR_PROJ -> proj.add(m);
case HONOR_TECH -> tech.add(m);
case HONOR_LECTURE -> lecture.add(m);
}
}
}
public void setDisplay(){
gridPane.getChildren().clear();
int row = 0;
gridPane.add(new Label("荣誉称号"), 0, row);
row = setItem(row, title);
gridPane.add(new Label("学科竞赛"), 0, row);
row = setItem(row, contest);
gridPane.add(new Label("社会实践"), 0, row);
row = setItem(row, practice);
gridPane.add(new Label("科技成果"), 0, row);
row = setItem(row, tech);
gridPane.add(new Label("校外实习"), 0, row);
row = setItem(row, internship);
gridPane.add(new Label("培训讲座"), 0, row);
row = setItem(row, lecture);
gridPane.add(new Label("创新项目"), 0, row);
row = setItem(row, proj);
int numOfHonors = honors.size();
if( numOfHonors == 0){
gridPane.add(new Label("你目前没有个人荣誉诶\n继续加油吧!"), 3, 0);
}
else if(numOfHonors <= 2){
gridPane.add(new Label("你目前有 " + numOfHonors + " 个荣誉耶\n小有成就!"), 3, 0);
}
else if(numOfHonors <= 5){
gridPane.add(new Label("真棒! 你现在有 " + numOfHonors + " 个荣誉\n再接再厉吧!"), 3, 0);
}
else {
gridPane.add(new Label("Wow,你现在有 " + numOfHonors + " 个荣誉\nAmazing!"), 3, 0);
}
}
private int setItem(int row, List<Map> title) {
for(Map m : title){
gridPane.add(new Label((String) m.get("honorContent")), 1, row);
row++;
}
if(title.isEmpty()){
gridPane.add(new Label("暂无奖项"),1,row);
row++;
}
return row;
}
public void openFilterWindow(List<Map> honors, String honorType){
FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource("honor/honor-filter-panel.fxml"));
try {
Scene scene = new Scene(loader.load(), 600, 400);
HonorFilterController honorFilterController = (HonorFilterController) loader.getController();
honorFilterController.setData(honors, honorType);
honorFilterController.setDisplay();
filterStage = new Stage();
filterStage.setScene(scene);
filterStage.setTitle(honorType);
filterStage.initOwner(getStage());
filterStage.initModality(Modality.WINDOW_MODAL);
filterStage.setOnCloseRequest(windowEvent -> filterStage = null);
filterStage.setResizable(false);
filterStage.show();
}
catch (IOException o){
System.out.println("打开分类浏览荣誉的视图失败: " + o.getMessage());
}
}
public void onFilterButtonClick(ActionEvent event) {
MFXButton btn = (MFXButton) event.getTarget();
String text = btn.getText();
switch (text) {
case "荣誉称号" -> openFilterWindow(title, text);
case "学科竞赛" -> openFilterWindow(contest, text);
case "科技成果" -> openFilterWindow(tech, text);
case "社会实践" -> openFilterWindow(practice, text);
case "培训讲座" -> openFilterWindow(lecture, text);
case "创新项目" -> openFilterWindow(proj, text);
case "校外实习" -> openFilterWindow(internship, text);
}
}
private Stage getStage(){
Scene scene = this.borderPane.getScene();
return (Stage) scene.getWindow();
}
}
| 1 | 19 | 1 |
46513_3 | package com.tom;
import com.google.common.collect.ImmutableList;
import com.tom.enums.LimitType;
import com.tom.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* @author wangtao
*/
@Aspect
@Component
public class LimitInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);
private final RedisTemplate<String, Serializable> limitRedisTemplate;
@Autowired
private HttpServletRequest httpServletRequest;
@Autowired
public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) {
this.limitRedisTemplate = limitRedisTemplate;
}
@Around("execution(public * *(..)) && @annotation(com.tom.Limit)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Limit limitAnnotation = method.getAnnotation(Limit.class);
LimitType limitType = limitAnnotation.limitType();
String name = limitAnnotation.name();
logger.info("aop执行---->名字为{}",name);
String key;
int limitPeriod = limitAnnotation.period();
int limitCount = limitAnnotation.count();
switch (limitType) {
case IP:
key = Util.getIpAddress(httpServletRequest);
break;
case CUSTOMER:
// TODO 如果此处想根据表达式或者一些规则生成 请看 一起来学Spring Boot | 第二十三篇:轻松搞定重复提交(分布式锁)
key = limitAnnotation.key();
break;
default:
key = StringUtils.upperCase(method.getName());
}
ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
try {
String luaScript = buildLuaScript();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
logger.info("Access try count is {} for name={} and key = {}", count, name, key);
if (count != null && count.intValue() <= limitCount) {
return pjp.proceed();
} else {
throw new RuntimeException("You have been dragged into the blacklist");
}
} catch (Throwable e) {
if (e instanceof RuntimeException) {
throw new RuntimeException(e.getLocalizedMessage());
}
throw new RuntimeException("server exception");
}
}
/**
* 限流 脚本
*
* @return lua脚本
*/
public String buildLuaScript() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nc = redis.call('get',KEYS[1])");
// 调用不超过最大值,则直接返回
lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
lua.append("\nreturn c;");
lua.append("\nend");
// 执行计算器自加
lua.append("\nc = redis.call('incr',KEYS[1])");
lua.append("\nif tonumber(c) == 1 then");
// 从第一次调用开始限流,设置对应键值的过期
lua.append("\nredis.call('expire',KEYS[1],ARGV[2])");
lua.append("\nend");
lua.append("\nreturn c;");
return lua.toString();
}
} | ChineseTony/javaDataStruct | myLimit/src/main/java/com/tom/LimitInterceptor.java | 963 | // 调用不超过最大值,则直接返回 | line_comment | zh-cn | package com.tom;
import com.google.common.collect.ImmutableList;
import com.tom.enums.LimitType;
import com.tom.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* @author wangtao
*/
@Aspect
@Component
public class LimitInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);
private final RedisTemplate<String, Serializable> limitRedisTemplate;
@Autowired
private HttpServletRequest httpServletRequest;
@Autowired
public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) {
this.limitRedisTemplate = limitRedisTemplate;
}
@Around("execution(public * *(..)) && @annotation(com.tom.Limit)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Limit limitAnnotation = method.getAnnotation(Limit.class);
LimitType limitType = limitAnnotation.limitType();
String name = limitAnnotation.name();
logger.info("aop执行---->名字为{}",name);
String key;
int limitPeriod = limitAnnotation.period();
int limitCount = limitAnnotation.count();
switch (limitType) {
case IP:
key = Util.getIpAddress(httpServletRequest);
break;
case CUSTOMER:
// TODO 如果此处想根据表达式或者一些规则生成 请看 一起来学Spring Boot | 第二十三篇:轻松搞定重复提交(分布式锁)
key = limitAnnotation.key();
break;
default:
key = StringUtils.upperCase(method.getName());
}
ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
try {
String luaScript = buildLuaScript();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
logger.info("Access try count is {} for name={} and key = {}", count, name, key);
if (count != null && count.intValue() <= limitCount) {
return pjp.proceed();
} else {
throw new RuntimeException("You have been dragged into the blacklist");
}
} catch (Throwable e) {
if (e instanceof RuntimeException) {
throw new RuntimeException(e.getLocalizedMessage());
}
throw new RuntimeException("server exception");
}
}
/**
* 限流 脚本
*
* @return lua脚本
*/
public String buildLuaScript() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nc = redis.call('get',KEYS[1])");
// 调用 <SUF>
lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
lua.append("\nreturn c;");
lua.append("\nend");
// 执行计算器自加
lua.append("\nc = redis.call('incr',KEYS[1])");
lua.append("\nif tonumber(c) == 1 then");
// 从第一次调用开始限流,设置对应键值的过期
lua.append("\nredis.call('expire',KEYS[1],ARGV[2])");
lua.append("\nend");
lua.append("\nreturn c;");
return lua.toString();
}
} | 1 | 17 | 1 |
58589_6 | package moe.gensoukyo.rpgmaths.api.damage.type;
import moe.gensoukyo.rpgmaths.RpgMathsMod;
import moe.gensoukyo.rpgmaths.api.impl.damage.formula.BaseDamageFormula;
import moe.gensoukyo.rpgmaths.api.stats.IStatType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.registries.IForgeRegistryEntry;
import net.minecraftforge.registries.ObjectHolder;
import javax.annotation.Nonnull;
/**
* 伤害类型
* @author Chloe_koopa
*/
@ObjectHolder(RpgMathsMod.ID)
public interface IDamageType extends IForgeRegistryEntry<IDamageType>
{
enum TypedStatCategory implements IStringSerializable {
/* 攻击力 */
ATTACK("attack"),
/* 防御力 */
DEFENSE("defense"),
/* 触发几率 */
TRIGGER("trigger"),
/* 触发抵抗 */
ANTI_TRIGGER("n_trigger");
/**
* 语言文件密钥格式
* rpgmaths.damage.type.category.<属性名称>
*/
public static final String LANG_FORMAT = RpgMathsMod.ID + ".damage.type.category.%s";
private final String name;
TypedStatCategory(String name) {
this.name = name;
}
@Nonnull @Override
public String getName() {
return name;
}
}
/**
* 获取这个伤害类型对应的进攻效果的数值
* @param category 这个数值属于一种元素的哪一类
* @return 影响这个攻击类型攻击力的RPG数值,在属性生成后永远不会是null
*/
IStatType getStat(TypedStatCategory category);
/**
* 为伤害的某一类属性登记注册后的属性,仅用于自动生成并注册属性时使用
* @throws IllegalStateException 如果这项属性已存在
* @param category 这个数值属于一种元素的哪一类数值
* @param generated 自动生成的属性
*/
void registerStat(TypedStatCategory category, IStatType generated);
/**
* 这个攻击类型是否附加原版伤害
* @see BaseDamageFormula#calculateDamage(ICapabilityProvider, ItemStack, LivingEntity, double)
* @return 攻击类型是否附加原版伤害
*/
default boolean acceptsVanillaDamage() {
return false;
}
/**
* 该类伤害每次被施加都会触发的效果
* @param entity 受害者
* @param damage 伤害值
* @param isDefense 触发这次效果的是防御方(true)还是攻击方(false)
*/
default void onEffectTriggered(ICapabilityProvider entity, double damage, boolean isDefense) {}
/**
* 该类伤害被随机触发施加的效果
* @param entity 受害者
* @param damage 伤害值
* @param isDefense 触发这次效果的是防御方(true)还是攻击方(false)
*/
default void onEffectRandomlyTriggered(ICapabilityProvider entity, double damage, boolean isDefense) {}
/**
* 获取名称
* @return 名称
*/
ITextComponent getName();
}
| ChloePrime/RpgMaths | src/main/java/moe/gensoukyo/rpgmaths/api/damage/type/IDamageType.java | 845 | /**
* 获取这个伤害类型对应的进攻效果的数值
* @param category 这个数值属于一种元素的哪一类
* @return 影响这个攻击类型攻击力的RPG数值,在属性生成后永远不会是null
*/ | block_comment | zh-cn | package moe.gensoukyo.rpgmaths.api.damage.type;
import moe.gensoukyo.rpgmaths.RpgMathsMod;
import moe.gensoukyo.rpgmaths.api.impl.damage.formula.BaseDamageFormula;
import moe.gensoukyo.rpgmaths.api.stats.IStatType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.registries.IForgeRegistryEntry;
import net.minecraftforge.registries.ObjectHolder;
import javax.annotation.Nonnull;
/**
* 伤害类型
* @author Chloe_koopa
*/
@ObjectHolder(RpgMathsMod.ID)
public interface IDamageType extends IForgeRegistryEntry<IDamageType>
{
enum TypedStatCategory implements IStringSerializable {
/* 攻击力 */
ATTACK("attack"),
/* 防御力 */
DEFENSE("defense"),
/* 触发几率 */
TRIGGER("trigger"),
/* 触发抵抗 */
ANTI_TRIGGER("n_trigger");
/**
* 语言文件密钥格式
* rpgmaths.damage.type.category.<属性名称>
*/
public static final String LANG_FORMAT = RpgMathsMod.ID + ".damage.type.category.%s";
private final String name;
TypedStatCategory(String name) {
this.name = name;
}
@Nonnull @Override
public String getName() {
return name;
}
}
/**
* 获取这 <SUF>*/
IStatType getStat(TypedStatCategory category);
/**
* 为伤害的某一类属性登记注册后的属性,仅用于自动生成并注册属性时使用
* @throws IllegalStateException 如果这项属性已存在
* @param category 这个数值属于一种元素的哪一类数值
* @param generated 自动生成的属性
*/
void registerStat(TypedStatCategory category, IStatType generated);
/**
* 这个攻击类型是否附加原版伤害
* @see BaseDamageFormula#calculateDamage(ICapabilityProvider, ItemStack, LivingEntity, double)
* @return 攻击类型是否附加原版伤害
*/
default boolean acceptsVanillaDamage() {
return false;
}
/**
* 该类伤害每次被施加都会触发的效果
* @param entity 受害者
* @param damage 伤害值
* @param isDefense 触发这次效果的是防御方(true)还是攻击方(false)
*/
default void onEffectTriggered(ICapabilityProvider entity, double damage, boolean isDefense) {}
/**
* 该类伤害被随机触发施加的效果
* @param entity 受害者
* @param damage 伤害值
* @param isDefense 触发这次效果的是防御方(true)还是攻击方(false)
*/
default void onEffectRandomlyTriggered(ICapabilityProvider entity, double damage, boolean isDefense) {}
/**
* 获取名称
* @return 名称
*/
ITextComponent getName();
}
| 0 | 124 | 0 |
64705_8 | /**
*
* @author ChopinXBP 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
* 思路:Integer.toBinaryString(n)转为字符串判断
*
*/
public class NumberOf1_11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = Solve(-5);
System.out.println(n);
}
// -------------投机取巧的解法:转换为字符串---------------------//
public static int Solve(int n) {
int result = 0;
String binstr = Integer.toBinaryString(n);
System.out.println(binstr);
for (int i = 0; i < binstr.length(); i++) {
if (binstr.charAt(i) == '1')
result++;
}
return result;
}
// -------------可能陷入死循环的解法:从右向左移---------------------//
// 从n的2进制形式的最右边开始判断是不是1,该解法如果输入时负数会陷入死循环,因为负数右移时,在最高位补得是1,最后会补成0xFFFFFFFF。
public static int NumberOf1_CanNotUse(int n) {
int count = 0;
while (n != 0) {
// 用1和n进行位与运算,结果要是为1则n的2进制形式.最右边那位肯定是1,否则为0
if ((n & 1) == 1) {
count++;
}
// 把n的2进制形式往右推一位
n = n >> 1;
}
return count;
}
// --------------------正解:从左向右移---------------------------//
// 思想:用1(1自身左移运算,其实后来就不是1了)和n的每位进行位与,来判断1的个数
private static int NumberOf1_low(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n & flag) != 0) {
count++;
}
flag = flag << 1;
}
return count;
}
// ---------------------------最优解----------------------------//
// 思想:把一个整数减去1,再和原整数做与运算,会把整数最右边的一个1变成0。
// 那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。
public static int NumberOf1(int n) {
int count = 0;
while (n != 0) {
++count;
n = (n - 1) & n;
}
return count;
}
}
| ChopinXBP/JZOffer_Babel | src/NumberOf1_11.java | 702 | // 思想:用1(1自身左移运算,其实后来就不是1了)和n的每位进行位与,来判断1的个数 | line_comment | zh-cn | /**
*
* @author ChopinXBP 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
* 思路:Integer.toBinaryString(n)转为字符串判断
*
*/
public class NumberOf1_11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = Solve(-5);
System.out.println(n);
}
// -------------投机取巧的解法:转换为字符串---------------------//
public static int Solve(int n) {
int result = 0;
String binstr = Integer.toBinaryString(n);
System.out.println(binstr);
for (int i = 0; i < binstr.length(); i++) {
if (binstr.charAt(i) == '1')
result++;
}
return result;
}
// -------------可能陷入死循环的解法:从右向左移---------------------//
// 从n的2进制形式的最右边开始判断是不是1,该解法如果输入时负数会陷入死循环,因为负数右移时,在最高位补得是1,最后会补成0xFFFFFFFF。
public static int NumberOf1_CanNotUse(int n) {
int count = 0;
while (n != 0) {
// 用1和n进行位与运算,结果要是为1则n的2进制形式.最右边那位肯定是1,否则为0
if ((n & 1) == 1) {
count++;
}
// 把n的2进制形式往右推一位
n = n >> 1;
}
return count;
}
// --------------------正解:从左向右移---------------------------//
// 思想 <SUF>
private static int NumberOf1_low(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n & flag) != 0) {
count++;
}
flag = flag << 1;
}
return count;
}
// ---------------------------最优解----------------------------//
// 思想:把一个整数减去1,再和原整数做与运算,会把整数最右边的一个1变成0。
// 那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。
public static int NumberOf1(int n) {
int count = 0;
while (n != 0) {
++count;
n = (n - 1) & n;
}
return count;
}
}
| 1 | 44 | 1 |
35998_5 | package Problems;
import java.util.HashMap;
/**
*
* You are given K eggs, and you have access to a building with N floors from 1 to N.
* Each egg is identical in function, and if an egg breaks, you cannot drop it again.
* You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break,
* and any egg dropped at or below floor F will not break.
* Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).
* Your goal is to know with certainty what the value of F is.
* What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?
* 你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N 共有 N 层楼的建筑。
* 每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去。
* 你知道存在楼层 F ,满足 0 <= F <= N 任何从高于 F 的楼层落下的鸡蛋都会碎,从 F 楼层或比它低的楼层落下的鸡蛋都不会破。
* 每次移动,你可以取一个鸡蛋(如果你有完整的鸡蛋)并把它从任一楼层 X 扔下(满足 1 <= X <= N)。
* 你的目标是确切地知道 F 的值是多少。
* 无论 F 的初始值如何,你确定 F 的值的最小移动次数是多少?
*
*/
public class SuperEggDrop {
//递归(超时)
public int superEggDrop2(int K, int N) {
if(N < 2 || K == 1){
return N;
}
int result = N;
//在手握K个鸡蛋时从第i层楼[0,N]向下丢鸡蛋,会有两种可能:
//1.鸡蛋摔碎,将剩余K-1个鸡蛋移动到楼[0,i-1]进行测递归测试。
//2.鸡蛋没碎,将剩余K个鸡蛋移动到楼[i,N]进行测试,可将i层看成0层,对[0,N-i]进行递归测试。
for(int i = 1; i <= N; i++){
int curMin = Math.max(superEggDrop2(K - 1, i - 1), superEggDrop2(K, N - i)) + 1;
result = curMin < result ? curMin : result;
}
return result;
}
//动态规划:二分搜索
//观察递归公式result = min(max(superEggDrop(K - 1, i - 1), superEggDrop(K, N - i)) + 1),其中i在[1.N]变化
//而fun1=superEggDrop(K - 1, i - 1)随i单调增,fun2=superEggDrop(K, N - i)随i单调减,两条单调函数的交点即为两者最大值的最小取值点
//因此可以对i在[1,N]上进行二分查找
HashMap<Integer, Integer> map = new HashMap<>();
public int superEggDrop3(int K, int N) {
if (N == 0){
return 0;
}
if (K == 1){
return N;
}
//因为K<=100,可以设计一个key值的取值方法,将已经计算过的K,N组合存入哈希表避免重复计算
int key = N * 1000 + K;
if (map.containsKey(key)){
return map.get(key);
}
int begin = 1;
int end = N;
while (begin + 1 < end) {
int mid = (begin + end) >> 1;
int lowVal = superEggDrop(K - 1, mid - 1);
int highVal = superEggDrop(K, N - mid);
if (lowVal < highVal){
begin = mid;
}
else if (lowVal > highVal){
end = mid;
}
else{
end = mid;
begin = mid;
}
}
int minimum = 1 + Math.min(Math.max(superEggDrop(K - 1, begin - 1), superEggDrop(K, N - begin)),
Math.max(superEggDrop(K - 1, end - 1), superEggDrop(K, N - end)));
map.put(key, minimum);
return minimum;
}
//动态规划:自底向上
//观察转为动态规划的递归公式dp[i][j] = min(max(dp[i-1][loc-1], dp[i][j-loc]) + 1),其中i在[1.j]变化,j在[1, N]变化
//而fun1=dp[i-1][loc-1]随loc单调增,fun2=dp[i][j-loc]随loc单调减,两条单调函数的交点即为两者最大值的最小取值点
//寻找loc的思路转换为while循环遍历查找
public int superEggDrop4(int K, int N) {
int[][] dp = new int[K + 1][N + 1];
for(int i = 1; i <= K; i++){
int loc = 1;
for(int j = 1; j <= N; j++){
if(i == 1){
dp[i][j] = j;
continue;
}
//令left为loc-1时的函数值,right为loc时的函数值,循环遍历找到最小值的拐点
//由于后序j值上限不断增大,loc拐点值只可能逐渐向右移动,以此可以简化后序查找
while (loc < j){
int left = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]);
int right = Math.max(dp[i - 1][loc], dp[i][j - loc - 1]);
if(left <= right){
break;
}
loc++;
}
dp[i][j] = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]) + 1;
}
}
return dp[K][N];
}
//动态规划(超时):求能够测得的最少楼层
public int superEggDrop5(int K, int N) {
//dp[i][j]代表有i个鸡蛋和j次移动时一定能够测得的最少楼层数
int[][] dp = new int[K + 1][N + 1];
//没有鸡蛋时或没有移动次数时无法测试dp=0;只有1个鸡蛋但有j次移动,dp=j(从0层开始逐层测试)
for (int i = 1; i <= N; i++) {
dp[1][i] = i;
dp[0][i] = 0;
}
for (int i = 1; i <= K; i++) {
dp[i][0] = 0;
}
for (int i = 2; i <= K; i++) {
for (int j = 1; j <= N; j++) {
//有i个鸡蛋和j次移动时,前j-1次移动的测试结果可能由多种测试路径得来,将其划分为k次和(j-1)-k次遍历取最大
//第j-1次移动鸡蛋碎的结果为dp[i-1][k],鸡蛋未碎的结果为dp[i][(j - 1) - k],当前楼层第j次移动的最少测试结果为1(摔碎)
//dp[i][j] = max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1
int tMinDrop = N * N;
for (int k = 0; k < j; k++) {
tMinDrop = Math.min(tMinDrop, Math.max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1);
}
dp[i][j] = tMinDrop;
}
}
return dp[K][N];
}
//动态规划(次优):求能够测得的最多楼层
public int superEggDrop6(int K, int N) {
//dp[i][j]代表i个鸡蛋在j次移动内能测试确定的最多楼层数
int[][] dp = new int[N + 1][K + 1];
//从第一层楼开始更新dp数组
for(int i = 1; i <= N; i++){
//0次移动无法进行测试,初始值dp[i][0]=0
dp[i][0] = 0;
for(int j = 1; j <= K; j++){
//每多一次移动,可以多进行一次测试。在手中有i-1个鸡蛋的第j-1次移动时已经测出楼高dp[i-1][j-1],
//一次移动最差情况也可以测出当前楼层的情况,因此逆推出当前能够保证第j次移动得出结果的测试楼层为dp[i-1][j-1]+1
//第j次移动鸡蛋摔碎,可以确定当前层(1层)的结果(碎),剩余i-1个鸡蛋和j-1次移动能得出dp[i-1][j-1]层
//h1 = dp[i][j] = dp[i-1][j-1] + 1;
//第j次移动鸡蛋未碎,可以确定前dp[i-1][j-1]+1层的结果(不碎),剩余i个鸡蛋和j-1次移动能得出dp[i][j-1]层
//h2 = dp[i][j] = dp[i-1][j-1] + 1 + dp[i-1][j];
//dp = h2 >= max(h1, h2)
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + 1;
if(dp[i][j] >= N){
return i;
}
}
}
return N;
}
//数学(最优)
//最差情况下(一个鸡蛋)用N次移动可以测得N层楼高,因此可以移动次数x必在[1,N]之间,可以对x进行二分查找
public int superEggDrop(int K, int N) {
int begin = 1;
int end = N;
while(begin < end){
int mid = (begin + end) >> 1;
if(fun(mid, K, N) < N){
begin = mid + 1;
}else {
end = mid;
}
}
return begin;
}
//递归函数fun(x)代表x次移动能够测试的最大楼高
//https://leetcode-cn.com/problems/super-egg-drop/solution/ji-dan-diao-luo-by-leetcode/
//https://leetcode-cn.com/problems/super-egg-drop/solution/shu-xue-fa-jie-shi-by-lycao/
private int fun(int x, int k, int n){
int result = 0;
int r = 1;
for(int i = 1; i <= k; ++i){
r *= x - i + 1;
r /= i;
result += r;
if(result >= n){
break;
}
}
return result;
}
}
| ChopinXBP/LeetCode-Babel | src/Problems/SuperEggDrop.java | 2,901 | //动态规划:二分搜索 | line_comment | zh-cn | package Problems;
import java.util.HashMap;
/**
*
* You are given K eggs, and you have access to a building with N floors from 1 to N.
* Each egg is identical in function, and if an egg breaks, you cannot drop it again.
* You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break,
* and any egg dropped at or below floor F will not break.
* Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).
* Your goal is to know with certainty what the value of F is.
* What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?
* 你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N 共有 N 层楼的建筑。
* 每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去。
* 你知道存在楼层 F ,满足 0 <= F <= N 任何从高于 F 的楼层落下的鸡蛋都会碎,从 F 楼层或比它低的楼层落下的鸡蛋都不会破。
* 每次移动,你可以取一个鸡蛋(如果你有完整的鸡蛋)并把它从任一楼层 X 扔下(满足 1 <= X <= N)。
* 你的目标是确切地知道 F 的值是多少。
* 无论 F 的初始值如何,你确定 F 的值的最小移动次数是多少?
*
*/
public class SuperEggDrop {
//递归(超时)
public int superEggDrop2(int K, int N) {
if(N < 2 || K == 1){
return N;
}
int result = N;
//在手握K个鸡蛋时从第i层楼[0,N]向下丢鸡蛋,会有两种可能:
//1.鸡蛋摔碎,将剩余K-1个鸡蛋移动到楼[0,i-1]进行测递归测试。
//2.鸡蛋没碎,将剩余K个鸡蛋移动到楼[i,N]进行测试,可将i层看成0层,对[0,N-i]进行递归测试。
for(int i = 1; i <= N; i++){
int curMin = Math.max(superEggDrop2(K - 1, i - 1), superEggDrop2(K, N - i)) + 1;
result = curMin < result ? curMin : result;
}
return result;
}
//动态 <SUF>
//观察递归公式result = min(max(superEggDrop(K - 1, i - 1), superEggDrop(K, N - i)) + 1),其中i在[1.N]变化
//而fun1=superEggDrop(K - 1, i - 1)随i单调增,fun2=superEggDrop(K, N - i)随i单调减,两条单调函数的交点即为两者最大值的最小取值点
//因此可以对i在[1,N]上进行二分查找
HashMap<Integer, Integer> map = new HashMap<>();
public int superEggDrop3(int K, int N) {
if (N == 0){
return 0;
}
if (K == 1){
return N;
}
//因为K<=100,可以设计一个key值的取值方法,将已经计算过的K,N组合存入哈希表避免重复计算
int key = N * 1000 + K;
if (map.containsKey(key)){
return map.get(key);
}
int begin = 1;
int end = N;
while (begin + 1 < end) {
int mid = (begin + end) >> 1;
int lowVal = superEggDrop(K - 1, mid - 1);
int highVal = superEggDrop(K, N - mid);
if (lowVal < highVal){
begin = mid;
}
else if (lowVal > highVal){
end = mid;
}
else{
end = mid;
begin = mid;
}
}
int minimum = 1 + Math.min(Math.max(superEggDrop(K - 1, begin - 1), superEggDrop(K, N - begin)),
Math.max(superEggDrop(K - 1, end - 1), superEggDrop(K, N - end)));
map.put(key, minimum);
return minimum;
}
//动态规划:自底向上
//观察转为动态规划的递归公式dp[i][j] = min(max(dp[i-1][loc-1], dp[i][j-loc]) + 1),其中i在[1.j]变化,j在[1, N]变化
//而fun1=dp[i-1][loc-1]随loc单调增,fun2=dp[i][j-loc]随loc单调减,两条单调函数的交点即为两者最大值的最小取值点
//寻找loc的思路转换为while循环遍历查找
public int superEggDrop4(int K, int N) {
int[][] dp = new int[K + 1][N + 1];
for(int i = 1; i <= K; i++){
int loc = 1;
for(int j = 1; j <= N; j++){
if(i == 1){
dp[i][j] = j;
continue;
}
//令left为loc-1时的函数值,right为loc时的函数值,循环遍历找到最小值的拐点
//由于后序j值上限不断增大,loc拐点值只可能逐渐向右移动,以此可以简化后序查找
while (loc < j){
int left = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]);
int right = Math.max(dp[i - 1][loc], dp[i][j - loc - 1]);
if(left <= right){
break;
}
loc++;
}
dp[i][j] = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]) + 1;
}
}
return dp[K][N];
}
//动态规划(超时):求能够测得的最少楼层
public int superEggDrop5(int K, int N) {
//dp[i][j]代表有i个鸡蛋和j次移动时一定能够测得的最少楼层数
int[][] dp = new int[K + 1][N + 1];
//没有鸡蛋时或没有移动次数时无法测试dp=0;只有1个鸡蛋但有j次移动,dp=j(从0层开始逐层测试)
for (int i = 1; i <= N; i++) {
dp[1][i] = i;
dp[0][i] = 0;
}
for (int i = 1; i <= K; i++) {
dp[i][0] = 0;
}
for (int i = 2; i <= K; i++) {
for (int j = 1; j <= N; j++) {
//有i个鸡蛋和j次移动时,前j-1次移动的测试结果可能由多种测试路径得来,将其划分为k次和(j-1)-k次遍历取最大
//第j-1次移动鸡蛋碎的结果为dp[i-1][k],鸡蛋未碎的结果为dp[i][(j - 1) - k],当前楼层第j次移动的最少测试结果为1(摔碎)
//dp[i][j] = max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1
int tMinDrop = N * N;
for (int k = 0; k < j; k++) {
tMinDrop = Math.min(tMinDrop, Math.max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1);
}
dp[i][j] = tMinDrop;
}
}
return dp[K][N];
}
//动态规划(次优):求能够测得的最多楼层
public int superEggDrop6(int K, int N) {
//dp[i][j]代表i个鸡蛋在j次移动内能测试确定的最多楼层数
int[][] dp = new int[N + 1][K + 1];
//从第一层楼开始更新dp数组
for(int i = 1; i <= N; i++){
//0次移动无法进行测试,初始值dp[i][0]=0
dp[i][0] = 0;
for(int j = 1; j <= K; j++){
//每多一次移动,可以多进行一次测试。在手中有i-1个鸡蛋的第j-1次移动时已经测出楼高dp[i-1][j-1],
//一次移动最差情况也可以测出当前楼层的情况,因此逆推出当前能够保证第j次移动得出结果的测试楼层为dp[i-1][j-1]+1
//第j次移动鸡蛋摔碎,可以确定当前层(1层)的结果(碎),剩余i-1个鸡蛋和j-1次移动能得出dp[i-1][j-1]层
//h1 = dp[i][j] = dp[i-1][j-1] + 1;
//第j次移动鸡蛋未碎,可以确定前dp[i-1][j-1]+1层的结果(不碎),剩余i个鸡蛋和j-1次移动能得出dp[i][j-1]层
//h2 = dp[i][j] = dp[i-1][j-1] + 1 + dp[i-1][j];
//dp = h2 >= max(h1, h2)
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + 1;
if(dp[i][j] >= N){
return i;
}
}
}
return N;
}
//数学(最优)
//最差情况下(一个鸡蛋)用N次移动可以测得N层楼高,因此可以移动次数x必在[1,N]之间,可以对x进行二分查找
public int superEggDrop(int K, int N) {
int begin = 1;
int end = N;
while(begin < end){
int mid = (begin + end) >> 1;
if(fun(mid, K, N) < N){
begin = mid + 1;
}else {
end = mid;
}
}
return begin;
}
//递归函数fun(x)代表x次移动能够测试的最大楼高
//https://leetcode-cn.com/problems/super-egg-drop/solution/ji-dan-diao-luo-by-leetcode/
//https://leetcode-cn.com/problems/super-egg-drop/solution/shu-xue-fa-jie-shi-by-lycao/
private int fun(int x, int k, int n){
int result = 0;
int r = 1;
for(int i = 1; i <= k; ++i){
r *= x - i + 1;
r /= i;
result += r;
if(result >= n){
break;
}
}
return result;
}
}
| 1 | 11 | 1 |
5143_22 | package com.ms509.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TimerTask;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import java.util.Timer;
public class MessageDialog extends JDialog {
private int i;
private java.util.TimerTask task;
private java.util.Timer timer;
public MessageDialog(String message,int time) {
super(MainFrame.main, time+"秒后自动关闭窗口", true);
this.i = time;
Toolkit t = Toolkit.getDefaultToolkit();
Dimension d = t.getScreenSize();
this.setResizable(false);
this.setSize(450, 240);
this.setLocation((d.width - this.getWidth()) / 2,
(d.height - this.getHeight()) / 2);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final JTextPane text = new JTextPane();
text.setText(message);
JScrollPane scroll = new JScrollPane(text);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(scroll, BorderLayout.CENTER);
this.getContentPane().add(panel);
// this.setModal(true); // 该方法可用于模态对话框,也可用于非模态对话框。
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
setTitle(--i + "秒后自动关闭窗口");
if (i == 0) {
timer.cancel(); // 终止此计时器
// task.cancel(); // 取消此计时器任务
setVisible(false);
}
}
};
timer.schedule(task, 1000, 1000);
setVisible(true);
// this.setModal(false); // 该方法只能用于非模态对话框
// final javax.swing.Timer timer = new javax.swing.Timer(1000,
// new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// setTitle(--i + "秒后自动关闭窗口");
// }
// });
// timer.start();
// setVisible(true);
// Runnable run = new Runnable() {
// public void run() {
//// while (timer.isRunning()) {
//// if (i == 0) {
//// SwingUtilities.invokeLater(new Runnable() {
//// @Override
//// public void run() {
//// timer.stop();
//// setVisible(false);
//// }
//// });
//// break;
//// }
//// }
// // 在多线程编程中,主线程执行无线循环需要加入sleep或者yield让其他线程有机会执行,
// // 不然其他线程没机会执行,则无线循环的条件也就满足不了,则会进入死循环。
// while (true) {
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// }
// Thread.yield();
// if (i == 0) {
// // 必须通过EDT刷新组件
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// timer.stop();
// setVisible(false);
// }
// });
// break;
// }
// }
// }
// };
// // 不能在EDT中执行其他耗时操作,应该在一个独立的工作器线程中(即普通线程中)做这件事情
// new Thread(run).start();
}
}
| Chora10/Cknife | src/com/ms509/ui/MessageDialog.java | 1,013 | // // 在多线程编程中,主线程执行无线循环需要加入sleep或者yield让其他线程有机会执行, | line_comment | zh-cn | package com.ms509.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TimerTask;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import java.util.Timer;
public class MessageDialog extends JDialog {
private int i;
private java.util.TimerTask task;
private java.util.Timer timer;
public MessageDialog(String message,int time) {
super(MainFrame.main, time+"秒后自动关闭窗口", true);
this.i = time;
Toolkit t = Toolkit.getDefaultToolkit();
Dimension d = t.getScreenSize();
this.setResizable(false);
this.setSize(450, 240);
this.setLocation((d.width - this.getWidth()) / 2,
(d.height - this.getHeight()) / 2);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final JTextPane text = new JTextPane();
text.setText(message);
JScrollPane scroll = new JScrollPane(text);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(scroll, BorderLayout.CENTER);
this.getContentPane().add(panel);
// this.setModal(true); // 该方法可用于模态对话框,也可用于非模态对话框。
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
setTitle(--i + "秒后自动关闭窗口");
if (i == 0) {
timer.cancel(); // 终止此计时器
// task.cancel(); // 取消此计时器任务
setVisible(false);
}
}
};
timer.schedule(task, 1000, 1000);
setVisible(true);
// this.setModal(false); // 该方法只能用于非模态对话框
// final javax.swing.Timer timer = new javax.swing.Timer(1000,
// new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// setTitle(--i + "秒后自动关闭窗口");
// }
// });
// timer.start();
// setVisible(true);
// Runnable run = new Runnable() {
// public void run() {
//// while (timer.isRunning()) {
//// if (i == 0) {
//// SwingUtilities.invokeLater(new Runnable() {
//// @Override
//// public void run() {
//// timer.stop();
//// setVisible(false);
//// }
//// });
//// break;
//// }
//// }
// // 在多 <SUF>
// // 不然其他线程没机会执行,则无线循环的条件也就满足不了,则会进入死循环。
// while (true) {
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// }
// Thread.yield();
// if (i == 0) {
// // 必须通过EDT刷新组件
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// timer.stop();
// setVisible(false);
// }
// });
// break;
// }
// }
// }
// };
// // 不能在EDT中执行其他耗时操作,应该在一个独立的工作器线程中(即普通线程中)做这件事情
// new Thread(run).start();
}
}
| 0 | 53 | 0 |
34648_1 | package hw4;
import java.util.Scanner;
public class DayCount { // 請設計由鍵盤輸入三個整數,分別代表西元yyyy年,mm月,dd日,執行後會顯示是該年的第幾天
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入三個整數 yyyy mm dd:");
int yyyy = sc.nextInt();
int mm = sc.nextInt();
int dd = sc.nextInt();
//2月dd檢查-閏年29 非閏年28
while (yyyy % 4 == 0 && mm == 2 && dd > 29 || yyyy % 4 != 0 && mm == 2 && dd > 28) {
if (yyyy % 4 == 0) {
System.out.println("請輸入合理的日(dd) (2月至多29天):");
dd = sc.nextInt();
if (mm != 2 || (mm == 2 && dd <= 29)) {
break;
}
} else {
System.out.println("請輸入合理的日(dd) (2月至多28天):");
dd = sc.nextInt();
if (mm != 2 || (mm == 2 && dd <= 28)) {
break;
}
}
}
int[][] mdArr1 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 },
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; // 非閏年
int[][] mdArr2 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; // 閏年
int daySum = 0;
int leftDay = 0;
int countDay = 0;
if (yyyy % 4 == 0) { // 判斷是否為閏年
for (int i = 0; i <= mm - 1; i++) {
daySum += mdArr2[1][i]; // 先把至當月底(yy)的累積天數加出來
}
leftDay = mdArr2[1][mm - 1] - dd; // 然後 當月還沒過的天數=當月月底-dd
countDay = daySum - leftDay; // 第幾天=至當月底的累積天數-當月還沒過的天數
} else {
for (int i = 0; i <= mm - 1; i++) {
daySum += mdArr1[1][i]; // 先把至當月底(yy)的累積天數加出來
}
leftDay = mdArr1[1][mm - 1] - dd; // 然後 當月還沒過的天數=當月月底-dd
countDay = daySum - leftDay; // 第幾天=至當月底的累積天數-當月還沒過的天數
}
System.out.printf("輸入的日期為該年第%d天", countDay);
sc.close();
}
}
| Chris86402/TIA10203-Homework | src/hw4/DayCount.java | 959 | //2月dd檢查-閏年29 非閏年28 | line_comment | zh-cn | package hw4;
import java.util.Scanner;
public class DayCount { // 請設計由鍵盤輸入三個整數,分別代表西元yyyy年,mm月,dd日,執行後會顯示是該年的第幾天
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入三個整數 yyyy mm dd:");
int yyyy = sc.nextInt();
int mm = sc.nextInt();
int dd = sc.nextInt();
//2月 <SUF>
while (yyyy % 4 == 0 && mm == 2 && dd > 29 || yyyy % 4 != 0 && mm == 2 && dd > 28) {
if (yyyy % 4 == 0) {
System.out.println("請輸入合理的日(dd) (2月至多29天):");
dd = sc.nextInt();
if (mm != 2 || (mm == 2 && dd <= 29)) {
break;
}
} else {
System.out.println("請輸入合理的日(dd) (2月至多28天):");
dd = sc.nextInt();
if (mm != 2 || (mm == 2 && dd <= 28)) {
break;
}
}
}
int[][] mdArr1 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 },
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; // 非閏年
int[][] mdArr2 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; // 閏年
int daySum = 0;
int leftDay = 0;
int countDay = 0;
if (yyyy % 4 == 0) { // 判斷是否為閏年
for (int i = 0; i <= mm - 1; i++) {
daySum += mdArr2[1][i]; // 先把至當月底(yy)的累積天數加出來
}
leftDay = mdArr2[1][mm - 1] - dd; // 然後 當月還沒過的天數=當月月底-dd
countDay = daySum - leftDay; // 第幾天=至當月底的累積天數-當月還沒過的天數
} else {
for (int i = 0; i <= mm - 1; i++) {
daySum += mdArr1[1][i]; // 先把至當月底(yy)的累積天數加出來
}
leftDay = mdArr1[1][mm - 1] - dd; // 然後 當月還沒過的天數=當月月底-dd
countDay = daySum - leftDay; // 第幾天=至當月底的累積天數-當月還沒過的天數
}
System.out.printf("輸入的日期為該年第%d天", countDay);
sc.close();
}
}
| 0 | 19 | 0 |
54162_12 | package data_structure_homework_2;
import data_structure_homework.Stack;
public class SeqStack implements Stack{//顺序堆栈类
final int defaultSize=10;//堆栈默认大小
int top;//栈顶位置
Object[] stack;//数组对象
int maxStackSize;//最大数据元素个数
public SeqStack() {//无参构造方法
initiate(defaultSize);
}
public SeqStack(int sz) {//带参构造方法
initiate(sz);
}
private void initiate(int sz) {//初始化
maxStackSize=sz;
top=0;
stack=new Object[sz];
}
public void push(Object obj) throws Exception{//入栈
if(top==maxStackSize) {
throw new Exception("The stack is full!");
}
stack[top]=obj;//保存元素
top++;//产生新的栈顶位置
}
public Object pop() throws Exception{//出栈
if(top==0) {
throw new Exception("The stack is empty!");
}
top--;//产生原栈顶位置
return stack[top];//返回原栈顶元素
}
public Object getTop() throws Exception{//取栈顶元素
if(top==0) {
throw new Exception("The stack is empty!");
}
return stack[top-1];//返回原栈顶元素
}
public boolean notEmpty() {//非空否
return (top>0);
}
} | ChristopherFerryman/SSPKU_STUDY | SeqStack.java | 365 | //取栈顶元素 | line_comment | zh-cn | package data_structure_homework_2;
import data_structure_homework.Stack;
public class SeqStack implements Stack{//顺序堆栈类
final int defaultSize=10;//堆栈默认大小
int top;//栈顶位置
Object[] stack;//数组对象
int maxStackSize;//最大数据元素个数
public SeqStack() {//无参构造方法
initiate(defaultSize);
}
public SeqStack(int sz) {//带参构造方法
initiate(sz);
}
private void initiate(int sz) {//初始化
maxStackSize=sz;
top=0;
stack=new Object[sz];
}
public void push(Object obj) throws Exception{//入栈
if(top==maxStackSize) {
throw new Exception("The stack is full!");
}
stack[top]=obj;//保存元素
top++;//产生新的栈顶位置
}
public Object pop() throws Exception{//出栈
if(top==0) {
throw new Exception("The stack is empty!");
}
top--;//产生原栈顶位置
return stack[top];//返回原栈顶元素
}
public Object getTop() throws Exception{//取栈 <SUF>
if(top==0) {
throw new Exception("The stack is empty!");
}
return stack[top-1];//返回原栈顶元素
}
public boolean notEmpty() {//非空否
return (top>0);
}
} | 1 | 7 | 1 |
59498_7 | package com.sibo.fastsport.utils;
import android.content.Context;
import android.util.SparseArray;
import com.sibo.fastsport.domain.SportName;
import com.sibo.fastsport.model.DayPlan;
import com.sibo.fastsport.model.MainAction;
import com.sibo.fastsport.model.RelaxAction;
import com.sibo.fastsport.model.Stretching;
import com.sibo.fastsport.model.UserSportPlan;
import com.sibo.fastsport.model.WarmUp;
import java.util.ArrayList;
import java.util.List;
/**
* 收集健身计划
* Created by chuan on 2017/2/23.
*/
public class CollectPlan {
//public static List<UserSportPlan> userSportPlan = new ArrayList<>();//教练的健身计划 名字 教练
public static List<Integer> dayId = new ArrayList<>();//选择天数的集合
public static String id;
public static UserSportPlan userSportPlan = new UserSportPlan();//教练的健身计划 名字 教练
public static List<DayPlan> dayPlan = new ArrayList<>();//计划的具体内容 第几天的计划 动作类型的有无
public static List<WarmUp> warmUps = new ArrayList<>();//热身动作
public static List<Stretching> stretchings = new ArrayList<>();//拉伸动作
public static List<MainAction> mainActions = new ArrayList<>();//具体动作
public static List<RelaxAction> relaxActions = new ArrayList<>();//放松动作
//动作类别 天数 名字 这样的存储方案
// 热身--1、拉伸--2、具体--3、放松--4
public static SparseArray<SparseArray<List<SportName>>> typeDayNamePlan = new SparseArray<>();
private Context context;
public CollectPlan(Context context){
this.context = context;
}
/**
* 收集健身计划
*/
public static void initDayPlan(){
for (int i = 0;i<7;i++){
DayPlan d = new DayPlan();
d.setDayId(i);
dayPlan.add(d);
}
}
public static void prepareToPush(){
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).warmUpList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).warmUpList) {
WarmUp w = new WarmUp();
w.setDayId(i);
w.setId(id);
w.setWarmId(s.getObjectId());
warmUps.add(w);
}
}
}
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).stretchingList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).stretchingList) {
Stretching stre = new Stretching();
stre.setDayId(i);
stre.setId(id);
stre.setStretchingId(s.getObjectId());
stretchings.add(stre);
}
}
}
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).mainActionList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).mainActionList) {
MainAction m = new MainAction();
m.setDayId(i);
m.setId(id);
m.setMainAction(s.getObjectId());
mainActions.add(m);
}
}
}
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).relaxActionList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).relaxActionList) {
RelaxAction r = new RelaxAction();
r.setDayId(i);
r.setId(id);
r.setRelaxAction(s.getObjectId());
relaxActions.add(r);
}
}
}
}
} | ChuanLikeCode/NewSport | app/src/main/java/com/sibo/fastsport/utils/CollectPlan.java | 1,029 | //具体动作 | line_comment | zh-cn | package com.sibo.fastsport.utils;
import android.content.Context;
import android.util.SparseArray;
import com.sibo.fastsport.domain.SportName;
import com.sibo.fastsport.model.DayPlan;
import com.sibo.fastsport.model.MainAction;
import com.sibo.fastsport.model.RelaxAction;
import com.sibo.fastsport.model.Stretching;
import com.sibo.fastsport.model.UserSportPlan;
import com.sibo.fastsport.model.WarmUp;
import java.util.ArrayList;
import java.util.List;
/**
* 收集健身计划
* Created by chuan on 2017/2/23.
*/
public class CollectPlan {
//public static List<UserSportPlan> userSportPlan = new ArrayList<>();//教练的健身计划 名字 教练
public static List<Integer> dayId = new ArrayList<>();//选择天数的集合
public static String id;
public static UserSportPlan userSportPlan = new UserSportPlan();//教练的健身计划 名字 教练
public static List<DayPlan> dayPlan = new ArrayList<>();//计划的具体内容 第几天的计划 动作类型的有无
public static List<WarmUp> warmUps = new ArrayList<>();//热身动作
public static List<Stretching> stretchings = new ArrayList<>();//拉伸动作
public static List<MainAction> mainActions = new ArrayList<>();//具体 <SUF>
public static List<RelaxAction> relaxActions = new ArrayList<>();//放松动作
//动作类别 天数 名字 这样的存储方案
// 热身--1、拉伸--2、具体--3、放松--4
public static SparseArray<SparseArray<List<SportName>>> typeDayNamePlan = new SparseArray<>();
private Context context;
public CollectPlan(Context context){
this.context = context;
}
/**
* 收集健身计划
*/
public static void initDayPlan(){
for (int i = 0;i<7;i++){
DayPlan d = new DayPlan();
d.setDayId(i);
dayPlan.add(d);
}
}
public static void prepareToPush(){
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).warmUpList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).warmUpList) {
WarmUp w = new WarmUp();
w.setDayId(i);
w.setId(id);
w.setWarmId(s.getObjectId());
warmUps.add(w);
}
}
}
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).stretchingList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).stretchingList) {
Stretching stre = new Stretching();
stre.setDayId(i);
stre.setId(id);
stre.setStretchingId(s.getObjectId());
stretchings.add(stre);
}
}
}
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).mainActionList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).mainActionList) {
MainAction m = new MainAction();
m.setDayId(i);
m.setId(id);
m.setMainAction(s.getObjectId());
mainActions.add(m);
}
}
}
for (int i = 0;i < 7 ; i++){
if (MakePlanUtils.list_day.get(i).relaxActionList.size() != 0){
for (SportName s :
MakePlanUtils.list_day.get(i).relaxActionList) {
RelaxAction r = new RelaxAction();
r.setDayId(i);
r.setId(id);
r.setRelaxAction(s.getObjectId());
relaxActions.add(r);
}
}
}
}
} | 0 | 6 | 0 |
16500_8 | /**
* @author Chunel
* @Name JavaCaiss.java
* @date 2020/9/15 1:23 上午
* @Desc 具体函数功能,请参考说明文档
*/
import com.sun.jna.Native; // 使用前,请自行引入相关依赖。具体可参考给定pom.xml文件
import com.sun.jna.*;
import com.sun.jna.ptr.NativeLongByReference;
import com.sun.jna.ptr.PointerByReference;
public class JaCaiss {
public static String CAISS_PATH = "../libCaiss.so"; // 请设置正确caiss动态库的路径信息
private interface JnaCaiss extends Library {
JnaCaiss instance = (JnaCaiss) Native.loadLibrary(CAISS_PATH, JnaCaiss.class);
int CAISS_Environment(int maxThreadSize, int algoType, int manageType);
int CAISS_CreateHandle(PointerByReference pointer);
int CAISS_Init(Pointer handle, int mode, int distanceType, int dim, String modelPath, Object distFunc);
int CAISS_Train(Pointer handle, String dataPath, int maxDataSize, int normalize,
int maxIndexSize, float precision, int fastRank, int realRank,
int step, int maxEpoch, int showSpan);
int CAISS_Search(Pointer handle, String info, int searchType, int topK,
int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 暂不支持回调函数
int CAISS_Search(Pointer handle, float[] info, int searchType, int topK,
int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 传入向量的情况下,
int CAISS_GetResultSize(Pointer handle, NativeLongByReference size);
int CAISS_GetResult(Pointer handle, Pointer result, NativeLong size);
int CAISS_Insert(Pointer handle, float[] node, String label, int insertType);
int CAISS_Ignore(Pointer handle, String label, int isIgnore);
int CAISS_Save(Pointer handle, String modelPath);
int CAISS_ExecuteSQL(Pointer handle, String sql, Object sqlCBFunc, Pointer sqlParams); // 暂不支持回调函数
int CAISS_DestroyHandle(Pointer handle);
}
public synchronized static int Environment(int maxThreadSize, int algoType, int manageType) {
return JnaCaiss.instance.CAISS_Environment(maxThreadSize, algoType, manageType);
}
public int CreateHandle(PointerByReference pointer) {
return JnaCaiss.instance.CAISS_CreateHandle(pointer);
}
public int Init(Pointer handle, int mode, int distanceType, int dim, String modelPath) {
return JnaCaiss.instance.CAISS_Init(handle, mode, distanceType, dim, modelPath, null);
}
public int Train(Pointer handle, String dataPath, int maxDataSize, int normalize,
int maxIndexSize, float precision, int fastRank, int realRank,
int step, int maxEpoch, int showSpan) {
return JnaCaiss.instance.CAISS_Train(handle, dataPath, maxDataSize, normalize,
maxIndexSize, precision, fastRank, realRank, step, maxEpoch, showSpan);
}
// 查询接口,适用于同步模式下的查询(单词查询)
public String SyncSearch(Pointer handle, String info, int searchType, int topK,
int filterEditDistance , NativeLongByReference ref) {
if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_WORD
&& searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_WORD) {
// 如果不是单词查询的方式,则返回错误码
ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM));
return "";
}
int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK,
filterEditDistance, null, null);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
return getResultString(handle, ref);
}
public String SyncSearch(Pointer handle, float[] info, int searchType, int topK,
int filterEditDistance , NativeLongByReference ref) {
if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_QUERY
&& searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_QUERY) {
// 如果不是向量查询的方式,则返回错误码
ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM));
return "";
}
int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK,
filterEditDistance, null, null);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
return getResultString(handle, ref);
}
public String SyncExecuteSQL(Pointer handle, String sql, NativeLongByReference ref) {
int ret = JnaCaiss.instance.CAISS_ExecuteSQL(handle, sql, null, null);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
return getResultString(handle, ref);
}
public int Insert(Pointer handle, float[] node, String label, int insertType) {
return JnaCaiss.instance.CAISS_Insert(handle, node, label, insertType);
}
public int Ignore(Pointer handle, String label, int isIgnore) {
return JnaCaiss.instance.CAISS_Ignore(handle, label, isIgnore);
}
public int Save(Pointer handle, String modelPath) {
return JnaCaiss.instance.CAISS_Save(handle, modelPath);
}
public int DestroyHandle(Pointer handle) {
return JnaCaiss.instance.CAISS_DestroyHandle(handle);
}
/**
* 获取最终的结果,并且返回对应的返回值
* @param handle 句柄信息
* @param ref CAISS函数的返回值信息
*/
private String getResultString(Pointer handle, NativeLongByReference ref) {
NativeLongByReference sizeRef = new NativeLongByReference();
int ret = JnaCaiss.instance.CAISS_GetResultSize(handle, sizeRef);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
int size = sizeRef.getValue().intValue();
Pointer resultPtr = new Memory(size + 1);
NativeLong size_ = new NativeLong(size);
ret = JnaCaiss.instance.CAISS_GetResult(handle, resultPtr, size_);
String result = (JaCaissDefine.CAISS_RET_OK == ret) ? resultPtr.getString(0) : "";
ref.setValue(new NativeLong(ret)); // 设置返回值信息
Native.free(Pointer.nativeValue(resultPtr)); // 释放申请的内存信息
Pointer.nativeValue(resultPtr, 0);
return result; // 返回最终的查询结果信息
}
}
| ChunelFeng/caiss | java/JaCaiss.java | 1,713 | // 如果不是向量查询的方式,则返回错误码 | line_comment | zh-cn | /**
* @author Chunel
* @Name JavaCaiss.java
* @date 2020/9/15 1:23 上午
* @Desc 具体函数功能,请参考说明文档
*/
import com.sun.jna.Native; // 使用前,请自行引入相关依赖。具体可参考给定pom.xml文件
import com.sun.jna.*;
import com.sun.jna.ptr.NativeLongByReference;
import com.sun.jna.ptr.PointerByReference;
public class JaCaiss {
public static String CAISS_PATH = "../libCaiss.so"; // 请设置正确caiss动态库的路径信息
private interface JnaCaiss extends Library {
JnaCaiss instance = (JnaCaiss) Native.loadLibrary(CAISS_PATH, JnaCaiss.class);
int CAISS_Environment(int maxThreadSize, int algoType, int manageType);
int CAISS_CreateHandle(PointerByReference pointer);
int CAISS_Init(Pointer handle, int mode, int distanceType, int dim, String modelPath, Object distFunc);
int CAISS_Train(Pointer handle, String dataPath, int maxDataSize, int normalize,
int maxIndexSize, float precision, int fastRank, int realRank,
int step, int maxEpoch, int showSpan);
int CAISS_Search(Pointer handle, String info, int searchType, int topK,
int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 暂不支持回调函数
int CAISS_Search(Pointer handle, float[] info, int searchType, int topK,
int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 传入向量的情况下,
int CAISS_GetResultSize(Pointer handle, NativeLongByReference size);
int CAISS_GetResult(Pointer handle, Pointer result, NativeLong size);
int CAISS_Insert(Pointer handle, float[] node, String label, int insertType);
int CAISS_Ignore(Pointer handle, String label, int isIgnore);
int CAISS_Save(Pointer handle, String modelPath);
int CAISS_ExecuteSQL(Pointer handle, String sql, Object sqlCBFunc, Pointer sqlParams); // 暂不支持回调函数
int CAISS_DestroyHandle(Pointer handle);
}
public synchronized static int Environment(int maxThreadSize, int algoType, int manageType) {
return JnaCaiss.instance.CAISS_Environment(maxThreadSize, algoType, manageType);
}
public int CreateHandle(PointerByReference pointer) {
return JnaCaiss.instance.CAISS_CreateHandle(pointer);
}
public int Init(Pointer handle, int mode, int distanceType, int dim, String modelPath) {
return JnaCaiss.instance.CAISS_Init(handle, mode, distanceType, dim, modelPath, null);
}
public int Train(Pointer handle, String dataPath, int maxDataSize, int normalize,
int maxIndexSize, float precision, int fastRank, int realRank,
int step, int maxEpoch, int showSpan) {
return JnaCaiss.instance.CAISS_Train(handle, dataPath, maxDataSize, normalize,
maxIndexSize, precision, fastRank, realRank, step, maxEpoch, showSpan);
}
// 查询接口,适用于同步模式下的查询(单词查询)
public String SyncSearch(Pointer handle, String info, int searchType, int topK,
int filterEditDistance , NativeLongByReference ref) {
if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_WORD
&& searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_WORD) {
// 如果不是单词查询的方式,则返回错误码
ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM));
return "";
}
int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK,
filterEditDistance, null, null);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
return getResultString(handle, ref);
}
public String SyncSearch(Pointer handle, float[] info, int searchType, int topK,
int filterEditDistance , NativeLongByReference ref) {
if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_QUERY
&& searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_QUERY) {
// 如果 <SUF>
ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM));
return "";
}
int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK,
filterEditDistance, null, null);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
return getResultString(handle, ref);
}
public String SyncExecuteSQL(Pointer handle, String sql, NativeLongByReference ref) {
int ret = JnaCaiss.instance.CAISS_ExecuteSQL(handle, sql, null, null);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
return getResultString(handle, ref);
}
public int Insert(Pointer handle, float[] node, String label, int insertType) {
return JnaCaiss.instance.CAISS_Insert(handle, node, label, insertType);
}
public int Ignore(Pointer handle, String label, int isIgnore) {
return JnaCaiss.instance.CAISS_Ignore(handle, label, isIgnore);
}
public int Save(Pointer handle, String modelPath) {
return JnaCaiss.instance.CAISS_Save(handle, modelPath);
}
public int DestroyHandle(Pointer handle) {
return JnaCaiss.instance.CAISS_DestroyHandle(handle);
}
/**
* 获取最终的结果,并且返回对应的返回值
* @param handle 句柄信息
* @param ref CAISS函数的返回值信息
*/
private String getResultString(Pointer handle, NativeLongByReference ref) {
NativeLongByReference sizeRef = new NativeLongByReference();
int ret = JnaCaiss.instance.CAISS_GetResultSize(handle, sizeRef);
if (JaCaissDefine.CAISS_RET_OK != ret) {
ref.setValue(new NativeLong(ret));
return "";
}
int size = sizeRef.getValue().intValue();
Pointer resultPtr = new Memory(size + 1);
NativeLong size_ = new NativeLong(size);
ret = JnaCaiss.instance.CAISS_GetResult(handle, resultPtr, size_);
String result = (JaCaissDefine.CAISS_RET_OK == ret) ? resultPtr.getString(0) : "";
ref.setValue(new NativeLong(ret)); // 设置返回值信息
Native.free(Pointer.nativeValue(resultPtr)); // 释放申请的内存信息
Pointer.nativeValue(resultPtr, 0);
return result; // 返回最终的查询结果信息
}
}
| 1 | 21 | 1 |
36141_3 | package com.jscheng.elemeapplication;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jscheng.elemeapplication.adapter.LeftMenuAdapter;
import com.jscheng.elemeapplication.adapter.RightDishAdapter;
import com.jscheng.elemeapplication.imp.ShopCartImp;
import com.jscheng.elemeapplication.model.Dish;
import com.jscheng.elemeapplication.model.DishMenu;
import com.jscheng.elemeapplication.model.ShopCart;
import com.jscheng.elemeapplication.wiget.FakeAddImageView;
import com.jscheng.elemeapplication.wiget.PointFTypeEvaluator;
import com.jscheng.elemeapplication.wiget.ShopCartDialog;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements LeftMenuAdapter.onItemSelectedListener,ShopCartImp,ShopCartDialog.ShopCartDialogImp{
private final static String TAG = "MainActivity";
private RecyclerView leftMenu;//左侧菜单栏
private RecyclerView rightMenu;//右侧菜单栏
private TextView headerView;
private LinearLayout headerLayout;//右侧菜单栏最上面的菜单
private LinearLayout bottomLayout;
private DishMenu headMenu;
private LeftMenuAdapter leftAdapter;
private RightDishAdapter rightAdapter;
private ArrayList<DishMenu> dishMenuList;//数据源
private boolean leftClickType = false;//左侧菜单点击引发的右侧联动
private ShopCart shopCart;
// private FakeAddImageView fakeAddImageView;
private ImageView shoppingCartView;
private FrameLayout shopingCartLayout;
private TextView totalPriceTextView;
private TextView totalPriceNumTextView;
private RelativeLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
initAdapter();
}
private void initView(){
mainLayout = (RelativeLayout)findViewById(R.id.main_layout);
leftMenu = (RecyclerView)findViewById(R.id.left_menu);
rightMenu = (RecyclerView)findViewById(R.id.right_menu);
headerView = (TextView)findViewById(R.id.right_menu_tv);
headerLayout = (LinearLayout)findViewById(R.id.right_menu_item);
// fakeAddImageView = (FakeAddImageView)findViewById(R.id.right_dish_fake_add);
bottomLayout = (LinearLayout)findViewById(R.id.shopping_cart_bottom);
shoppingCartView = (ImageView) findViewById(R.id.shopping_cart);
shopingCartLayout = (FrameLayout) findViewById(R.id.shopping_cart_layout);
totalPriceTextView = (TextView)findViewById(R.id.shopping_cart_total_tv);
totalPriceNumTextView = (TextView)findViewById(R.id.shopping_cart_total_num);
leftMenu.setLayoutManager(new LinearLayoutManager(this));
rightMenu.setLayoutManager(new LinearLayoutManager(this));
rightMenu.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if( recyclerView.canScrollVertically(1)==false) {//无法下滑
showHeadView();
return;
}
View underView = null;
if(dy>0)
underView = rightMenu.findChildViewUnder(headerLayout.getX(),headerLayout.getMeasuredHeight()+1);
else
underView = rightMenu.findChildViewUnder(headerLayout.getX(),0);
if(underView!=null && underView.getContentDescription()!=null ){
int position = Integer.parseInt(underView.getContentDescription().toString());
DishMenu menu = rightAdapter.getMenuOfMenuByPosition(position);
if(leftClickType || !menu.getMenuName().equals(headMenu.getMenuName())) {
if (dy> 0 && headerLayout.getTranslationY()<=1 && headerLayout.getTranslationY()>= -1 * headerLayout.getMeasuredHeight()*4/5 && !leftClickType) {// underView.getTop()>9
int dealtY = underView.getTop() - headerLayout.getMeasuredHeight();
headerLayout.setTranslationY(dealtY);
// Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+" "+headerLayout.getBottom()+" - "+headerLayout.getMeasuredHeight() );
}
else if(dy<0 && headerLayout.getTranslationY()<=0 && !leftClickType) {
headerView.setText(menu.getMenuName());
int dealtY = underView.getBottom() - headerLayout.getMeasuredHeight();
headerLayout.setTranslationY(dealtY);
// Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+" "+headerLayout.getBottom()+" - "+headerLayout.getMeasuredHeight() );
}
else{
headerLayout.setTranslationY(0);
headMenu = menu;
headerView.setText(headMenu.getMenuName());
for (int i = 0; i < dishMenuList.size(); i++) {
if (dishMenuList.get(i) == headMenu) {
leftAdapter.setSelectedNum(i);
break;
}
}
if(leftClickType)leftClickType=false;
Log.e(TAG, "onScrolled: "+menu.getMenuName() );
}
}
}
}
});
shopingCartLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showCart(view);
}
});
}
private void initData(){
shopCart = new ShopCart();
dishMenuList = new ArrayList<>();
ArrayList<Dish> dishs1 = new ArrayList<>();
dishs1.add(new Dish("面包",1.0,10));
dishs1.add(new Dish("蛋挞",1.0,10));
dishs1.add(new Dish("牛奶",1.0,10));
dishs1.add(new Dish("肠粉",1.0,10));
dishs1.add(new Dish("绿茶饼",1.0,10));
dishs1.add(new Dish("花卷",1.0,10));
dishs1.add(new Dish("包子",1.0,10));
DishMenu breakfast = new DishMenu("早点",dishs1);
ArrayList<Dish> dishs2 = new ArrayList<>();
dishs2.add(new Dish("粥",1.0,10));
dishs2.add(new Dish("炒饭",1.0,10));
dishs2.add(new Dish("炒米粉",1.0,10));
dishs2.add(new Dish("炒粿条",1.0,10));
dishs2.add(new Dish("炒牛河",1.0,10));
dishs2.add(new Dish("炒菜",1.0,10));
DishMenu launch = new DishMenu("午餐",dishs2);
ArrayList<Dish> dishs3 = new ArrayList<>();
dishs3.add(new Dish("淋菜",1.0,10));
dishs3.add(new Dish("川菜",1.0,10));
dishs3.add(new Dish("湘菜",1.0,10));
dishs3.add(new Dish("粤菜",1.0,10));
dishs3.add(new Dish("赣菜",1.0,10));
dishs3.add(new Dish("东北菜",1.0,10));
DishMenu evening = new DishMenu("晚餐",dishs3);
ArrayList<Dish> dishs4 = new ArrayList<>();
dishs4.add(new Dish("淋菜",1.0,10));
dishs4.add(new Dish("川菜",1.0,10));
dishs4.add(new Dish("湘菜",1.0,10));
dishs4.add(new Dish("粤菜",1.0,10));
dishs4.add(new Dish("赣菜",1.0,10));
dishs4.add(new Dish("东北菜",1.0,10));
DishMenu menu1 = new DishMenu("晚餐",dishs3);
dishMenuList.add(breakfast);
dishMenuList.add(launch);
dishMenuList.add(evening);
dishMenuList.add(menu1);
}
private void initAdapter(){
leftAdapter = new LeftMenuAdapter(this,dishMenuList);
rightAdapter = new RightDishAdapter(this,dishMenuList,shopCart);
rightMenu.setAdapter(rightAdapter);
leftMenu.setAdapter(leftAdapter);
leftAdapter.addItemSelectedListener(this);
rightAdapter.setShopCartImp(this);
initHeadView();
}
private void initHeadView(){
headMenu = rightAdapter.getMenuOfMenuByPosition(0);
headerLayout.setContentDescription("0");
headerView.setText(headMenu.getMenuName());
}
@Override
protected void onDestroy() {
super.onDestroy();
leftAdapter.removeItemSelectedListener(this);
}
private void showHeadView(){
headerLayout.setTranslationY(0);
View underView = rightMenu.findChildViewUnder(headerView.getX(),0);
if(underView!=null && underView.getContentDescription()!=null){
int position = Integer.parseInt(underView.getContentDescription().toString());
DishMenu menu = rightAdapter.getMenuOfMenuByPosition(position+1);
headMenu = menu;
headerView.setText(headMenu.getMenuName());
for (int i = 0; i < dishMenuList.size(); i++) {
if (dishMenuList.get(i) == headMenu) {
leftAdapter.setSelectedNum(i);
break;
}
}
}
}
@Override
public void onLeftItemSelected(int position, DishMenu menu) {
int sum=0;
for(int i = 0;i<position;i++){
sum+=dishMenuList.get(i).getDishList().size()+1;
}
LinearLayoutManager layoutManager = (LinearLayoutManager) rightMenu.getLayoutManager();
layoutManager.scrollToPositionWithOffset(sum,0);
leftClickType = true;
}
@Override
public void add(View view,int position) {
int[] addLocation = new int[2];
int[] cartLocation = new int[2];
int[] recycleLocation = new int[2];
view.getLocationInWindow(addLocation);
shoppingCartView.getLocationInWindow(cartLocation);
rightMenu.getLocationInWindow(recycleLocation);
PointF startP = new PointF();
PointF endP = new PointF();
PointF controlP = new PointF();
startP.x = addLocation[0];
startP.y = addLocation[1]-recycleLocation[1];
endP.x = cartLocation[0];
endP.y = cartLocation[1]-recycleLocation[1];
controlP.x = endP.x;
controlP.y = startP.y;
final FakeAddImageView fakeAddImageView = new FakeAddImageView(this);
mainLayout.addView(fakeAddImageView);
fakeAddImageView.setImageResource(R.drawable.ic_add_circle_blue_700_36dp);
fakeAddImageView.getLayoutParams().width = getResources().getDimensionPixelSize(R.dimen.item_dish_circle_size);
fakeAddImageView.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.item_dish_circle_size);
fakeAddImageView.setVisibility(View.VISIBLE);
ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
new PointFTypeEvaluator(controlP), startP, endP);
addAnimator.setInterpolator(new AccelerateInterpolator());
addAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
fakeAddImageView.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animator) {
fakeAddImageView.setVisibility(View.GONE);
mainLayout.removeView(fakeAddImageView);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(shoppingCartView,"scaleX", 0.6f, 1.0f);
ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(shoppingCartView,"scaleY", 0.6f, 1.0f);
scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
animatorSet.setDuration(800);
animatorSet.start();
showTotalPrice();
}
@Override
public void remove(View view,int position) {
showTotalPrice();
}
private void showTotalPrice(){
if(shopCart!=null && shopCart.getShoppingTotalPrice()>0){
totalPriceTextView.setVisibility(View.VISIBLE);
totalPriceTextView.setText("¥ "+shopCart.getShoppingTotalPrice());
totalPriceNumTextView.setVisibility(View.VISIBLE);
totalPriceNumTextView.setText(""+shopCart.getShoppingAccount());
}else {
totalPriceTextView.setVisibility(View.GONE);
totalPriceNumTextView.setVisibility(View.GONE);
}
}
private void showCart(View view) {
if(shopCart!=null && shopCart.getShoppingAccount()>0){
ShopCartDialog dialog = new ShopCartDialog(this,shopCart,R.style.cartdialog);
Window window = dialog.getWindow();
dialog.setShopCartDialogImp(this);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
dialog.show();
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.BOTTOM;
params.dimAmount =0.5f;
window.setAttributes(params);
}
}
@Override
public void dialogDismiss() {
showTotalPrice();
rightAdapter.notifyDataSetChanged();
}
} | ChyengJason/ShoppingCart | app/src/main/java/com/jscheng/elemeapplication/MainActivity.java | 3,687 | //数据源 | line_comment | zh-cn | package com.jscheng.elemeapplication;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jscheng.elemeapplication.adapter.LeftMenuAdapter;
import com.jscheng.elemeapplication.adapter.RightDishAdapter;
import com.jscheng.elemeapplication.imp.ShopCartImp;
import com.jscheng.elemeapplication.model.Dish;
import com.jscheng.elemeapplication.model.DishMenu;
import com.jscheng.elemeapplication.model.ShopCart;
import com.jscheng.elemeapplication.wiget.FakeAddImageView;
import com.jscheng.elemeapplication.wiget.PointFTypeEvaluator;
import com.jscheng.elemeapplication.wiget.ShopCartDialog;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements LeftMenuAdapter.onItemSelectedListener,ShopCartImp,ShopCartDialog.ShopCartDialogImp{
private final static String TAG = "MainActivity";
private RecyclerView leftMenu;//左侧菜单栏
private RecyclerView rightMenu;//右侧菜单栏
private TextView headerView;
private LinearLayout headerLayout;//右侧菜单栏最上面的菜单
private LinearLayout bottomLayout;
private DishMenu headMenu;
private LeftMenuAdapter leftAdapter;
private RightDishAdapter rightAdapter;
private ArrayList<DishMenu> dishMenuList;//数据 <SUF>
private boolean leftClickType = false;//左侧菜单点击引发的右侧联动
private ShopCart shopCart;
// private FakeAddImageView fakeAddImageView;
private ImageView shoppingCartView;
private FrameLayout shopingCartLayout;
private TextView totalPriceTextView;
private TextView totalPriceNumTextView;
private RelativeLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
initAdapter();
}
private void initView(){
mainLayout = (RelativeLayout)findViewById(R.id.main_layout);
leftMenu = (RecyclerView)findViewById(R.id.left_menu);
rightMenu = (RecyclerView)findViewById(R.id.right_menu);
headerView = (TextView)findViewById(R.id.right_menu_tv);
headerLayout = (LinearLayout)findViewById(R.id.right_menu_item);
// fakeAddImageView = (FakeAddImageView)findViewById(R.id.right_dish_fake_add);
bottomLayout = (LinearLayout)findViewById(R.id.shopping_cart_bottom);
shoppingCartView = (ImageView) findViewById(R.id.shopping_cart);
shopingCartLayout = (FrameLayout) findViewById(R.id.shopping_cart_layout);
totalPriceTextView = (TextView)findViewById(R.id.shopping_cart_total_tv);
totalPriceNumTextView = (TextView)findViewById(R.id.shopping_cart_total_num);
leftMenu.setLayoutManager(new LinearLayoutManager(this));
rightMenu.setLayoutManager(new LinearLayoutManager(this));
rightMenu.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if( recyclerView.canScrollVertically(1)==false) {//无法下滑
showHeadView();
return;
}
View underView = null;
if(dy>0)
underView = rightMenu.findChildViewUnder(headerLayout.getX(),headerLayout.getMeasuredHeight()+1);
else
underView = rightMenu.findChildViewUnder(headerLayout.getX(),0);
if(underView!=null && underView.getContentDescription()!=null ){
int position = Integer.parseInt(underView.getContentDescription().toString());
DishMenu menu = rightAdapter.getMenuOfMenuByPosition(position);
if(leftClickType || !menu.getMenuName().equals(headMenu.getMenuName())) {
if (dy> 0 && headerLayout.getTranslationY()<=1 && headerLayout.getTranslationY()>= -1 * headerLayout.getMeasuredHeight()*4/5 && !leftClickType) {// underView.getTop()>9
int dealtY = underView.getTop() - headerLayout.getMeasuredHeight();
headerLayout.setTranslationY(dealtY);
// Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+" "+headerLayout.getBottom()+" - "+headerLayout.getMeasuredHeight() );
}
else if(dy<0 && headerLayout.getTranslationY()<=0 && !leftClickType) {
headerView.setText(menu.getMenuName());
int dealtY = underView.getBottom() - headerLayout.getMeasuredHeight();
headerLayout.setTranslationY(dealtY);
// Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+" "+headerLayout.getBottom()+" - "+headerLayout.getMeasuredHeight() );
}
else{
headerLayout.setTranslationY(0);
headMenu = menu;
headerView.setText(headMenu.getMenuName());
for (int i = 0; i < dishMenuList.size(); i++) {
if (dishMenuList.get(i) == headMenu) {
leftAdapter.setSelectedNum(i);
break;
}
}
if(leftClickType)leftClickType=false;
Log.e(TAG, "onScrolled: "+menu.getMenuName() );
}
}
}
}
});
shopingCartLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showCart(view);
}
});
}
private void initData(){
shopCart = new ShopCart();
dishMenuList = new ArrayList<>();
ArrayList<Dish> dishs1 = new ArrayList<>();
dishs1.add(new Dish("面包",1.0,10));
dishs1.add(new Dish("蛋挞",1.0,10));
dishs1.add(new Dish("牛奶",1.0,10));
dishs1.add(new Dish("肠粉",1.0,10));
dishs1.add(new Dish("绿茶饼",1.0,10));
dishs1.add(new Dish("花卷",1.0,10));
dishs1.add(new Dish("包子",1.0,10));
DishMenu breakfast = new DishMenu("早点",dishs1);
ArrayList<Dish> dishs2 = new ArrayList<>();
dishs2.add(new Dish("粥",1.0,10));
dishs2.add(new Dish("炒饭",1.0,10));
dishs2.add(new Dish("炒米粉",1.0,10));
dishs2.add(new Dish("炒粿条",1.0,10));
dishs2.add(new Dish("炒牛河",1.0,10));
dishs2.add(new Dish("炒菜",1.0,10));
DishMenu launch = new DishMenu("午餐",dishs2);
ArrayList<Dish> dishs3 = new ArrayList<>();
dishs3.add(new Dish("淋菜",1.0,10));
dishs3.add(new Dish("川菜",1.0,10));
dishs3.add(new Dish("湘菜",1.0,10));
dishs3.add(new Dish("粤菜",1.0,10));
dishs3.add(new Dish("赣菜",1.0,10));
dishs3.add(new Dish("东北菜",1.0,10));
DishMenu evening = new DishMenu("晚餐",dishs3);
ArrayList<Dish> dishs4 = new ArrayList<>();
dishs4.add(new Dish("淋菜",1.0,10));
dishs4.add(new Dish("川菜",1.0,10));
dishs4.add(new Dish("湘菜",1.0,10));
dishs4.add(new Dish("粤菜",1.0,10));
dishs4.add(new Dish("赣菜",1.0,10));
dishs4.add(new Dish("东北菜",1.0,10));
DishMenu menu1 = new DishMenu("晚餐",dishs3);
dishMenuList.add(breakfast);
dishMenuList.add(launch);
dishMenuList.add(evening);
dishMenuList.add(menu1);
}
private void initAdapter(){
leftAdapter = new LeftMenuAdapter(this,dishMenuList);
rightAdapter = new RightDishAdapter(this,dishMenuList,shopCart);
rightMenu.setAdapter(rightAdapter);
leftMenu.setAdapter(leftAdapter);
leftAdapter.addItemSelectedListener(this);
rightAdapter.setShopCartImp(this);
initHeadView();
}
private void initHeadView(){
headMenu = rightAdapter.getMenuOfMenuByPosition(0);
headerLayout.setContentDescription("0");
headerView.setText(headMenu.getMenuName());
}
@Override
protected void onDestroy() {
super.onDestroy();
leftAdapter.removeItemSelectedListener(this);
}
private void showHeadView(){
headerLayout.setTranslationY(0);
View underView = rightMenu.findChildViewUnder(headerView.getX(),0);
if(underView!=null && underView.getContentDescription()!=null){
int position = Integer.parseInt(underView.getContentDescription().toString());
DishMenu menu = rightAdapter.getMenuOfMenuByPosition(position+1);
headMenu = menu;
headerView.setText(headMenu.getMenuName());
for (int i = 0; i < dishMenuList.size(); i++) {
if (dishMenuList.get(i) == headMenu) {
leftAdapter.setSelectedNum(i);
break;
}
}
}
}
@Override
public void onLeftItemSelected(int position, DishMenu menu) {
int sum=0;
for(int i = 0;i<position;i++){
sum+=dishMenuList.get(i).getDishList().size()+1;
}
LinearLayoutManager layoutManager = (LinearLayoutManager) rightMenu.getLayoutManager();
layoutManager.scrollToPositionWithOffset(sum,0);
leftClickType = true;
}
@Override
public void add(View view,int position) {
int[] addLocation = new int[2];
int[] cartLocation = new int[2];
int[] recycleLocation = new int[2];
view.getLocationInWindow(addLocation);
shoppingCartView.getLocationInWindow(cartLocation);
rightMenu.getLocationInWindow(recycleLocation);
PointF startP = new PointF();
PointF endP = new PointF();
PointF controlP = new PointF();
startP.x = addLocation[0];
startP.y = addLocation[1]-recycleLocation[1];
endP.x = cartLocation[0];
endP.y = cartLocation[1]-recycleLocation[1];
controlP.x = endP.x;
controlP.y = startP.y;
final FakeAddImageView fakeAddImageView = new FakeAddImageView(this);
mainLayout.addView(fakeAddImageView);
fakeAddImageView.setImageResource(R.drawable.ic_add_circle_blue_700_36dp);
fakeAddImageView.getLayoutParams().width = getResources().getDimensionPixelSize(R.dimen.item_dish_circle_size);
fakeAddImageView.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.item_dish_circle_size);
fakeAddImageView.setVisibility(View.VISIBLE);
ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
new PointFTypeEvaluator(controlP), startP, endP);
addAnimator.setInterpolator(new AccelerateInterpolator());
addAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
fakeAddImageView.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animator) {
fakeAddImageView.setVisibility(View.GONE);
mainLayout.removeView(fakeAddImageView);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(shoppingCartView,"scaleX", 0.6f, 1.0f);
ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(shoppingCartView,"scaleY", 0.6f, 1.0f);
scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
animatorSet.setDuration(800);
animatorSet.start();
showTotalPrice();
}
@Override
public void remove(View view,int position) {
showTotalPrice();
}
private void showTotalPrice(){
if(shopCart!=null && shopCart.getShoppingTotalPrice()>0){
totalPriceTextView.setVisibility(View.VISIBLE);
totalPriceTextView.setText("¥ "+shopCart.getShoppingTotalPrice());
totalPriceNumTextView.setVisibility(View.VISIBLE);
totalPriceNumTextView.setText(""+shopCart.getShoppingAccount());
}else {
totalPriceTextView.setVisibility(View.GONE);
totalPriceNumTextView.setVisibility(View.GONE);
}
}
private void showCart(View view) {
if(shopCart!=null && shopCart.getShoppingAccount()>0){
ShopCartDialog dialog = new ShopCartDialog(this,shopCart,R.style.cartdialog);
Window window = dialog.getWindow();
dialog.setShopCartDialogImp(this);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
dialog.show();
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.BOTTOM;
params.dimAmount =0.5f;
window.setAttributes(params);
}
}
@Override
public void dialogDismiss() {
showTotalPrice();
rightAdapter.notifyDataSetChanged();
}
} | 0 | 5 | 0 |
23221_5 | package com.company;
import java.awt.*;
public class Bg {
// 关卡数
static int level = 1;
// 目标得分
int goal = (level * 500) + 550;
// 总分
static int count = 0;
// 药水数量
static int waterNum = 3;
// 药水状态
static boolean waterFlag = false;
// 开始时间
long startTime;
// 结束时间
long endTime;
// 药水价格
int price = (int) (Math.random() * 10);
// 是否进入商店 f不购买
boolean shop = false;
// 载入图片
Image bg = Toolkit.getDefaultToolkit().getImage("imgs/bg.jpg");
Image bg1 = Toolkit.getDefaultToolkit().getImage("imgs/bg1.jpg");
Image peo = Toolkit.getDefaultToolkit().getImage("imgs/peo.png");
Image water = Toolkit.getDefaultToolkit().getImage("imgs/water.png");
// 绘制
void paintSelf(Graphics g) {
g.drawImage(bg, 0, 200, null);
g.drawImage(bg1, 0, 0, null);
switch (GameWin.state) {
case 0:
drawWord(g, 80, Color.black, "按鼠标右键开始", 100, 400);
drawWord(g, 60, Color.red, "游戏规则:", 100, 500);
drawWord(g, 30, Color.black, "点击鼠标左键放出抓钩", 100, 560);
drawWord(g, 30, Color.black, "抓住金块或石头可以点击鼠标右键", 100, 620);
drawWord(g, 30, Color.black, "使用“大力神药”快速收回金块或者爆破石头", 100, 680);
break;
case 1:
g.drawImage(peo, 310, 50, null);
drawWord(g, 30, Color.black, "分数:" + count, 30, 150);
g.drawImage(water, 550, 40, null);
drawWord(g, 30, Color.black, "×" + waterNum, 610, 90);
// 关卡数&目标得分
drawWord(g, 20, Color.black, "关卡:" + level, 30, 60);
drawWord(g, 30, Color.black, "目标:" + goal, 30, 115);
// 实时赋值
endTime = System.currentTimeMillis();
long time = 20 - (endTime - startTime) / 1000;
drawWord(g, 30, Color.black, "时间:" + (time > 0 ? time : 0), 520, 150);
break;
case 2:
g.drawImage(water, 330, 380, null);
drawWord(g, 30, Color.black, "价格:" + price, 300, 500);
drawWord(g, 30, Color.black, "是否购买“大力神药”?", 280, 550);
drawWord(g, 30, Color.black, "点击鼠标左键确认购买,右键退出商店", 100, 700);
if (shop) {
count = count - price;
waterNum++;
shop = false;
GameWin.state = 1;
startTime = System.currentTimeMillis();
}
break;
case 3:
drawWord(g, 80, Color.cyan, "失败", 300, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
case 4:
drawWord(g, 80, Color.red, "恭喜过关", 250, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
default:
}
}
// t倒计时完成,f未完成倒计时
boolean gameTime() {
long time = (endTime - startTime) / 1000;
if (time >= 20) {
return true;
}
return false;
}
// 重置元素
void reGame() {
// 关卡数
level = 1;
// 目标得分
goal = (level * 500) + 550;
// 总分
count = 0;
// 药水数量
waterNum = 3;
// 药水状态
waterFlag = false;
}
// 绘制字符串
public static void drawWord(Graphics g, int size, Color color, String str, int x, int y) {
g.setColor(color);
g.setFont(new Font("宋体", Font.BOLD, size));
g.drawString(str, x, y);
}
}
| Cikian/GoldMiner | src/com/company/Bg.java | 1,336 | // 开始时间
| line_comment | zh-cn | package com.company;
import java.awt.*;
public class Bg {
// 关卡数
static int level = 1;
// 目标得分
int goal = (level * 500) + 550;
// 总分
static int count = 0;
// 药水数量
static int waterNum = 3;
// 药水状态
static boolean waterFlag = false;
// 开始 <SUF>
long startTime;
// 结束时间
long endTime;
// 药水价格
int price = (int) (Math.random() * 10);
// 是否进入商店 f不购买
boolean shop = false;
// 载入图片
Image bg = Toolkit.getDefaultToolkit().getImage("imgs/bg.jpg");
Image bg1 = Toolkit.getDefaultToolkit().getImage("imgs/bg1.jpg");
Image peo = Toolkit.getDefaultToolkit().getImage("imgs/peo.png");
Image water = Toolkit.getDefaultToolkit().getImage("imgs/water.png");
// 绘制
void paintSelf(Graphics g) {
g.drawImage(bg, 0, 200, null);
g.drawImage(bg1, 0, 0, null);
switch (GameWin.state) {
case 0:
drawWord(g, 80, Color.black, "按鼠标右键开始", 100, 400);
drawWord(g, 60, Color.red, "游戏规则:", 100, 500);
drawWord(g, 30, Color.black, "点击鼠标左键放出抓钩", 100, 560);
drawWord(g, 30, Color.black, "抓住金块或石头可以点击鼠标右键", 100, 620);
drawWord(g, 30, Color.black, "使用“大力神药”快速收回金块或者爆破石头", 100, 680);
break;
case 1:
g.drawImage(peo, 310, 50, null);
drawWord(g, 30, Color.black, "分数:" + count, 30, 150);
g.drawImage(water, 550, 40, null);
drawWord(g, 30, Color.black, "×" + waterNum, 610, 90);
// 关卡数&目标得分
drawWord(g, 20, Color.black, "关卡:" + level, 30, 60);
drawWord(g, 30, Color.black, "目标:" + goal, 30, 115);
// 实时赋值
endTime = System.currentTimeMillis();
long time = 20 - (endTime - startTime) / 1000;
drawWord(g, 30, Color.black, "时间:" + (time > 0 ? time : 0), 520, 150);
break;
case 2:
g.drawImage(water, 330, 380, null);
drawWord(g, 30, Color.black, "价格:" + price, 300, 500);
drawWord(g, 30, Color.black, "是否购买“大力神药”?", 280, 550);
drawWord(g, 30, Color.black, "点击鼠标左键确认购买,右键退出商店", 100, 700);
if (shop) {
count = count - price;
waterNum++;
shop = false;
GameWin.state = 1;
startTime = System.currentTimeMillis();
}
break;
case 3:
drawWord(g, 80, Color.cyan, "失败", 300, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
case 4:
drawWord(g, 80, Color.red, "恭喜过关", 250, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
default:
}
}
// t倒计时完成,f未完成倒计时
boolean gameTime() {
long time = (endTime - startTime) / 1000;
if (time >= 20) {
return true;
}
return false;
}
// 重置元素
void reGame() {
// 关卡数
level = 1;
// 目标得分
goal = (level * 500) + 550;
// 总分
count = 0;
// 药水数量
waterNum = 3;
// 药水状态
waterFlag = false;
}
// 绘制字符串
public static void drawWord(Graphics g, int size, Color color, String str, int x, int y) {
g.setColor(color);
g.setFont(new Font("宋体", Font.BOLD, size));
g.drawString(str, x, y);
}
}
| 1 | 8 | 1 |
44314_5 | package hw9;
public class Hw9Bear {
// 熊大在念大學,生活費倚靠媽媽。媽媽怕熊大一天到晚領錢亂花,不好好唸書,
// 所以只要看到熊大帳戶的餘額超過3000元,就會停止匯款給熊大;但要是帳戶
// 餘額在2000元以下,熊大就會要求媽媽匯款給他。如果帳戶餘額低於熊大要提
// 款的金額,熊大就會暫停提款,直到媽媽告知他錢已經入帳戶。假設媽媽一次匯
// 款2000 元,熊大一次提款1000元,寫一個Java程式模擬匯款10次與提款10次
// 的情形。
public static void main(String[] args) {
CashFlow cashflow = new CashFlow(); // 建立金流物件
Bear bear = new Bear(cashflow); // 建立熊大執行緒
BearMom bearMom = new BearMom(cashflow); // 建立熊媽執行緒
// 因匯入金額與領出金額不同,當熊大都領完之後JVM會繼續執行(熊媽無法匯10次以上)
bearMom.setDaemon(true); // 設定為Daemon,當熊大領完以後讓熊媽休息
bearMom.start();
bear.start();
}
}
class CashFlow {
private int savings = 0;
private int n, m; //計次用
synchronized public void withdraw(int money) {
while(savings == 0) {
System.out.println("熊大看到帳戶沒錢,暫停提款");
System.out.println("媽媽被熊大要求匯款!");
try {
notify();
wait();
} catch(Exception e) {
e.printStackTrace();
}
}
savings -= money;
n++;
System.out.println("熊大領了1000,帳戶共有:" + savings + " (熊大領了" + n + "次)");
if(savings <= 2000) {
System.out.println("熊大看到餘額在2000以下,要求匯款");
notify();
}
}
synchronized public void save(int money) {
while(savings > 3000) {
System.out.println("媽媽看到餘額在3000以上,暫停匯款");
System.out.println("熊大被老媽告知帳戶已經有錢!");
try{
notify();
wait();
} catch(Exception e) {
e.printStackTrace();
}
}
savings += money;
m++;
System.out.println("媽媽存了2000,帳戶共有:" + savings + " (熊媽匯了" + m + "次)");
}
}
class Bear extends Thread {
CashFlow cashflow;
public Bear(CashFlow cashflow) {
this.cashflow = cashflow;
}
@Override
public void run() {
// TODO Auto-generated method stub
// 提款10次
for(int i = 1; i <= 10; i++) {
cashflow.withdraw(1000); // 每次領1000
}
}
}
class BearMom extends Thread {
CashFlow cashflow;
public BearMom(CashFlow cashflow) {
this.cashflow = cashflow;
}
@Override
public void run() {
// TODO Auto-generated method stub
// 匯款10次
for(int i = 1; i <= 10; i++) {
cashflow.save(2000); // 每次存2000
}
}
} | Ciren22007524/CIA10129-Homework | src/hw9/Hw9Bear.java | 1,103 | // 的情形。 | line_comment | zh-cn | package hw9;
public class Hw9Bear {
// 熊大在念大學,生活費倚靠媽媽。媽媽怕熊大一天到晚領錢亂花,不好好唸書,
// 所以只要看到熊大帳戶的餘額超過3000元,就會停止匯款給熊大;但要是帳戶
// 餘額在2000元以下,熊大就會要求媽媽匯款給他。如果帳戶餘額低於熊大要提
// 款的金額,熊大就會暫停提款,直到媽媽告知他錢已經入帳戶。假設媽媽一次匯
// 款2000 元,熊大一次提款1000元,寫一個Java程式模擬匯款10次與提款10次
// 的情 <SUF>
public static void main(String[] args) {
CashFlow cashflow = new CashFlow(); // 建立金流物件
Bear bear = new Bear(cashflow); // 建立熊大執行緒
BearMom bearMom = new BearMom(cashflow); // 建立熊媽執行緒
// 因匯入金額與領出金額不同,當熊大都領完之後JVM會繼續執行(熊媽無法匯10次以上)
bearMom.setDaemon(true); // 設定為Daemon,當熊大領完以後讓熊媽休息
bearMom.start();
bear.start();
}
}
class CashFlow {
private int savings = 0;
private int n, m; //計次用
synchronized public void withdraw(int money) {
while(savings == 0) {
System.out.println("熊大看到帳戶沒錢,暫停提款");
System.out.println("媽媽被熊大要求匯款!");
try {
notify();
wait();
} catch(Exception e) {
e.printStackTrace();
}
}
savings -= money;
n++;
System.out.println("熊大領了1000,帳戶共有:" + savings + " (熊大領了" + n + "次)");
if(savings <= 2000) {
System.out.println("熊大看到餘額在2000以下,要求匯款");
notify();
}
}
synchronized public void save(int money) {
while(savings > 3000) {
System.out.println("媽媽看到餘額在3000以上,暫停匯款");
System.out.println("熊大被老媽告知帳戶已經有錢!");
try{
notify();
wait();
} catch(Exception e) {
e.printStackTrace();
}
}
savings += money;
m++;
System.out.println("媽媽存了2000,帳戶共有:" + savings + " (熊媽匯了" + m + "次)");
}
}
class Bear extends Thread {
CashFlow cashflow;
public Bear(CashFlow cashflow) {
this.cashflow = cashflow;
}
@Override
public void run() {
// TODO Auto-generated method stub
// 提款10次
for(int i = 1; i <= 10; i++) {
cashflow.withdraw(1000); // 每次領1000
}
}
}
class BearMom extends Thread {
CashFlow cashflow;
public BearMom(CashFlow cashflow) {
this.cashflow = cashflow;
}
@Override
public void run() {
// TODO Auto-generated method stub
// 匯款10次
for(int i = 1; i <= 10; i++) {
cashflow.save(2000); // 每次存2000
}
}
} | 0 | 7 | 0 |
15282_5 | 问题1
class Context {
//保证一个引用
private AbstractStrategy strategy;
public void setStrategy(AbstractStrategy str) {
this.strategy= str;
}
//调用策略类中的算法
public void algorithm() {
strategy.algorithm();
}
}
abstract class AbstractStrategy {
//声明抽象算法
public abstract void algorithm();
}
class ConcreteStrategyA extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyB extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyC extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
如果要添加其他算法,继续声明新类继承父类即可
问题2
使用模板方法模式 步骤不同的进行重写
class Context {
private Algorithm algorithm;
public void setAlgorithm(Algorithm algorithm) {
this.algorithm= algorithm;
}
//调用策略类中的算法
public void algorithm() {
algorithm.step1();
algorithm.step2();
algorithm.step3();
}
}
class Algorithm {
public void step1() {
System.out.println("step1的具体内容");
}
public void step2() {
System.out.println("step2的具体内容");
}
public void step3() {
System.out.println("step3的具体内容");
}
class ConcreteAlgorithmA extends Algorithm {
//算法的具体实现
public void step1() {
System.out.println("重写了算法步骤1");//A步骤1有所不同
}
}
class ConcreteAlgorithmB extends Algorithm {
//算法的具体实现
public void step2() {
System.out.println("重写了算法步骤2"); //B步骤2有所不同
}
}
class ConcreteAlgorithmC extends Algorithm {
//算法的具体实现
public void step3() {
System.out.println("重写了算法步骤3");//C步骤3有所不同
}
}
| CirillaQL/DesignPatternsHomework | 7-1.java | 565 | //算法的具体实现 | line_comment | zh-cn | 问题1
class Context {
//保证一个引用
private AbstractStrategy strategy;
public void setStrategy(AbstractStrategy str) {
this.strategy= str;
}
//调用策略类中的算法
public void algorithm() {
strategy.algorithm();
}
}
abstract class AbstractStrategy {
//声明抽象算法
public abstract void algorithm();
}
class ConcreteStrategyA extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyB extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyC extends AbstractStrategy {
//算法 <SUF>
public void algorithm() {
System.out.println("重写");
}
}
如果要添加其他算法,继续声明新类继承父类即可
问题2
使用模板方法模式 步骤不同的进行重写
class Context {
private Algorithm algorithm;
public void setAlgorithm(Algorithm algorithm) {
this.algorithm= algorithm;
}
//调用策略类中的算法
public void algorithm() {
algorithm.step1();
algorithm.step2();
algorithm.step3();
}
}
class Algorithm {
public void step1() {
System.out.println("step1的具体内容");
}
public void step2() {
System.out.println("step2的具体内容");
}
public void step3() {
System.out.println("step3的具体内容");
}
class ConcreteAlgorithmA extends Algorithm {
//算法的具体实现
public void step1() {
System.out.println("重写了算法步骤1");//A步骤1有所不同
}
}
class ConcreteAlgorithmB extends Algorithm {
//算法的具体实现
public void step2() {
System.out.println("重写了算法步骤2"); //B步骤2有所不同
}
}
class ConcreteAlgorithmC extends Algorithm {
//算法的具体实现
public void step3() {
System.out.println("重写了算法步骤3");//C步骤3有所不同
}
}
| 1 | 11 | 1 |
40721_6 | package com.civitasv.spider.model.bo;
import com.civitasv.spider.model.po.PoiPo;
import com.civitasv.spider.util.BeanUtils;
import com.google.gson.annotations.SerializedName;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.List;
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public class POI {
@SerializedName("status")
private final Integer status;
@SerializedName("info")
private String info;
@SerializedName("infocode")
private Integer infoCode;
@SerializedName("count")
private Integer count;
@SerializedName("pois")
private List<Info> details;
@Getter
@Accessors(fluent = true)
@AllArgsConstructor
public enum OutputFields {
ID("id", "id", "唯一ID", false, true),
NAME("name", "name", "名称", false, true),
TYPE("type", "type", "类型", false, true),
TYPE_CODE("typeCode", "typeCode", "类型编码", false, true),
BIZ_TYPE("bizType", "bizType", "行业类型", false, true),
ADDRESS("address", "address", "地址", false, true),
GCJ02_LNG("gcj02_lng", "gcj02_lng", "gcj02 格式经度", false, true),
GCJ02_LAT("gcj02_lat", "gcj02_lat", "gcj02 格式纬度", false, true),
WGS84_LNG("wgs84_lng", "wgs84_lng", "wgs84 格式经度", false, true),
WGS84_LAT("wgs84_lat", "wgs84_lat", "wgs84 格式纬度", false, true),
TEL("tel", "tel", "电话", false, true),
PROVINCE_NAME("provinceName", "province", "省份名称", false, true),
CITY_NAME("cityName", "city", "城市名称", false, true),
AD_NAME("adName", "ad", "区域名称", false, true),
POST_CODE("postCode", "postCode", "邮编", true, false),
WEBSITE("website", "website", "网址", true, false),
EMAIL("email", "email", "邮箱", true, false),
PROVINCE_CODE("provinceCode", "provCode", "省份编码", true, false),
CITY_CODE("cityCode", "cityCode", "城市编码", true, false),
AD_CODE("adCode", "adCode", "区域编码", true, false);
private final String fieldName;
private final String shapeFieldName; // shp 字段长度有限制
private final String description;
private final boolean inExtension;
private boolean checked;
public void checked(boolean checked) {
this.checked = checked;
}
@Override
public String toString() {
return description;
}
}
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public static class Info {
private transient Long id; // 对应PoiPo id
@SerializedName("id")
private Object poiId; // 唯一id 对应pid
@SerializedName("name")
private Object name; // 名称
@SerializedName("type")
private Object type; // 兴趣点类型
@SerializedName("typecode")
private Object typeCode; // 兴趣点类型编码
@SerializedName("biz_type")
private Object bizType; // 行业类型
@SerializedName("address")
private Object address; // 地址
@SerializedName("location")
private Object location; // 经纬度
@SerializedName("tel")
private Object tel; // 电话
@SerializedName("pname")
private Object provinceName; // 省份名称
@SerializedName("cityname")
private Object cityName; // 城市名称
@SerializedName("adname")
private Object adName; // 区域名称
@SerializedName("postcode")
private Object postCode; // 邮编,extensions=all时返回
@SerializedName("website")
private Object website; // 网址,extensions=all时返回
@SerializedName("email")
private Object email; // 邮箱,extensions=all时返回
@SerializedName("pcode")
private Object provinceCode; // 省份编码,extensions=all时返回
@SerializedName("citycode")
private Object cityCode; // 城市编码,extensions=all时返回
@SerializedName("adcode")
private Object adCode; // 区域编码,extensions=all时返回
public PoiPo toPoiPo(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.build();
}
public PoiPo toPoiPoWithExtensions(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.postCode(BeanUtils.obj2String(postCode))
.website(BeanUtils.obj2String(website))
.email(BeanUtils.obj2String(email))
.provinceCode(BeanUtils.obj2String(provinceCode))
.cityCode(BeanUtils.obj2String(cityCode))
.adCode(BeanUtils.obj2String(adCode))
.build();
}
}
}
| Civitasv/AMapPoi | src/main/java/com/civitasv/spider/model/bo/POI.java | 1,565 | // 经纬度 | line_comment | zh-cn | package com.civitasv.spider.model.bo;
import com.civitasv.spider.model.po.PoiPo;
import com.civitasv.spider.util.BeanUtils;
import com.google.gson.annotations.SerializedName;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.List;
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public class POI {
@SerializedName("status")
private final Integer status;
@SerializedName("info")
private String info;
@SerializedName("infocode")
private Integer infoCode;
@SerializedName("count")
private Integer count;
@SerializedName("pois")
private List<Info> details;
@Getter
@Accessors(fluent = true)
@AllArgsConstructor
public enum OutputFields {
ID("id", "id", "唯一ID", false, true),
NAME("name", "name", "名称", false, true),
TYPE("type", "type", "类型", false, true),
TYPE_CODE("typeCode", "typeCode", "类型编码", false, true),
BIZ_TYPE("bizType", "bizType", "行业类型", false, true),
ADDRESS("address", "address", "地址", false, true),
GCJ02_LNG("gcj02_lng", "gcj02_lng", "gcj02 格式经度", false, true),
GCJ02_LAT("gcj02_lat", "gcj02_lat", "gcj02 格式纬度", false, true),
WGS84_LNG("wgs84_lng", "wgs84_lng", "wgs84 格式经度", false, true),
WGS84_LAT("wgs84_lat", "wgs84_lat", "wgs84 格式纬度", false, true),
TEL("tel", "tel", "电话", false, true),
PROVINCE_NAME("provinceName", "province", "省份名称", false, true),
CITY_NAME("cityName", "city", "城市名称", false, true),
AD_NAME("adName", "ad", "区域名称", false, true),
POST_CODE("postCode", "postCode", "邮编", true, false),
WEBSITE("website", "website", "网址", true, false),
EMAIL("email", "email", "邮箱", true, false),
PROVINCE_CODE("provinceCode", "provCode", "省份编码", true, false),
CITY_CODE("cityCode", "cityCode", "城市编码", true, false),
AD_CODE("adCode", "adCode", "区域编码", true, false);
private final String fieldName;
private final String shapeFieldName; // shp 字段长度有限制
private final String description;
private final boolean inExtension;
private boolean checked;
public void checked(boolean checked) {
this.checked = checked;
}
@Override
public String toString() {
return description;
}
}
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public static class Info {
private transient Long id; // 对应PoiPo id
@SerializedName("id")
private Object poiId; // 唯一id 对应pid
@SerializedName("name")
private Object name; // 名称
@SerializedName("type")
private Object type; // 兴趣点类型
@SerializedName("typecode")
private Object typeCode; // 兴趣点类型编码
@SerializedName("biz_type")
private Object bizType; // 行业类型
@SerializedName("address")
private Object address; // 地址
@SerializedName("location")
private Object location; // 经纬 <SUF>
@SerializedName("tel")
private Object tel; // 电话
@SerializedName("pname")
private Object provinceName; // 省份名称
@SerializedName("cityname")
private Object cityName; // 城市名称
@SerializedName("adname")
private Object adName; // 区域名称
@SerializedName("postcode")
private Object postCode; // 邮编,extensions=all时返回
@SerializedName("website")
private Object website; // 网址,extensions=all时返回
@SerializedName("email")
private Object email; // 邮箱,extensions=all时返回
@SerializedName("pcode")
private Object provinceCode; // 省份编码,extensions=all时返回
@SerializedName("citycode")
private Object cityCode; // 城市编码,extensions=all时返回
@SerializedName("adcode")
private Object adCode; // 区域编码,extensions=all时返回
public PoiPo toPoiPo(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.build();
}
public PoiPo toPoiPoWithExtensions(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.postCode(BeanUtils.obj2String(postCode))
.website(BeanUtils.obj2String(website))
.email(BeanUtils.obj2String(email))
.provinceCode(BeanUtils.obj2String(provinceCode))
.cityCode(BeanUtils.obj2String(cityCode))
.adCode(BeanUtils.obj2String(adCode))
.build();
}
}
}
| 1 | 6 | 1 |
34769_11 | package ali;
import java.util.Arrays;
/**
*
* @author Claudius
* 给一个正整数数组,砍掉三个数,分为四个段,查看是否存在着三个数,让这四个段之和相等。如果存在则返回true。
* 阿里的笔试题。
*/
public class NewMain {
/** 请完成下面这个函数,实现题目要求的功能 **/
/** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/
static boolean resolve(int[] A) {
int length = A.length;
if (length <= 7) { //数组中数的数量至少有七个
return false;
}
//先对两个和rightSum和leftSum赋值,分别为左端与右端赋值给两段的和
for(int left = 1,right = length - 2,rightSum = A[length - 1],leftSum = A[0];left <= right - 4; ){ //从两端开始遍历,直到左端与右端下标距离
if (leftSum < rightSum) { //哪个大,移动哪个 //(必须保证中间的数还可以分为两段)
leftSum += A[left];
left++;
continue;
}else if (leftSum > rightSum) {
rightSum += A[right];
right--;
continue;
}
if(right - left + 2 <= 2*leftSum ){
return false;
}
//此时leftSum 和rightSum相等,left 和 right 分别对应需要跳过的下标
int middleLeft,middleRight,middleLeftSum;
// middleRight 代表中间最右值的下标
//将左起第一个值赋值给middleLeftSum,累加循环,直到middleLeftSum大于等于leftSum 或者 距离右端只有两个值时
for( middleLeft = left+2,middleRight = right - 1,middleLeftSum = A[left + 1];middleLeft < middleRight-1; middleLeft++){
if (middleLeftSum >= leftSum) { //如果要是相等,或者比leftSum大,则跳出循环
break;
}else if (middleLeftSum < leftSum) { //如果要是小于,则继续循环
middleLeftSum += A[middleLeft];
}
}
if (middleLeftSum < leftSum) { //小于代表着中间值加完了还是小于,所以最外圈循环再加下去会更小,没有必要再继续了
return false;
}else if (middleLeftSum == leftSum) { //相等,判断剩下的值之和是否相等,如果不相等,则继续外圈循环
int middleRightSum = 0;
//因为相等了,所以必然是从middleLeft + 1开始的,因为要空过下一个下标
for(int index = middleLeft + 1;index <= middleRight;index++){
middleRightSum += A[index];
}
//判断是否相等
if (middleRightSum == rightSum) {
return true;
}else {
continue;
}
}else { //大于,给左边继续加,然后继续循环
leftSum += A[left];
left++;
}
}
return false;
}
public static void main(String[] args){
// ArrayList<Integer> inputs = new ArrayList<Integer>();
// Scanner in = new Scanner(System.in);
// String line = in.nextLine();
// while(line != null && !line.isEmpty()) {
// int value = Integer.parseInt(line.trim());
// if(value == 0) break;
// inputs.add(value);
// line = in.nextLine();
// }
// int[] A = new int[inputs.size()];
// for(int i=0; i<inputs.size(); i++) {
// A[i] = inputs.get(i).intValue();
// }
int [] A = {2,2,5,1,2,1,1,3,1,10,1,1,1,1};
Boolean res = resolve(A);
System.out.println(String.valueOf(res));
}
} | ClaudiusJXK/SwordToOffer | java/NewMain.java | 1,056 | //如果要是小于,则继续循环 | line_comment | zh-cn | package ali;
import java.util.Arrays;
/**
*
* @author Claudius
* 给一个正整数数组,砍掉三个数,分为四个段,查看是否存在着三个数,让这四个段之和相等。如果存在则返回true。
* 阿里的笔试题。
*/
public class NewMain {
/** 请完成下面这个函数,实现题目要求的功能 **/
/** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/
static boolean resolve(int[] A) {
int length = A.length;
if (length <= 7) { //数组中数的数量至少有七个
return false;
}
//先对两个和rightSum和leftSum赋值,分别为左端与右端赋值给两段的和
for(int left = 1,right = length - 2,rightSum = A[length - 1],leftSum = A[0];left <= right - 4; ){ //从两端开始遍历,直到左端与右端下标距离
if (leftSum < rightSum) { //哪个大,移动哪个 //(必须保证中间的数还可以分为两段)
leftSum += A[left];
left++;
continue;
}else if (leftSum > rightSum) {
rightSum += A[right];
right--;
continue;
}
if(right - left + 2 <= 2*leftSum ){
return false;
}
//此时leftSum 和rightSum相等,left 和 right 分别对应需要跳过的下标
int middleLeft,middleRight,middleLeftSum;
// middleRight 代表中间最右值的下标
//将左起第一个值赋值给middleLeftSum,累加循环,直到middleLeftSum大于等于leftSum 或者 距离右端只有两个值时
for( middleLeft = left+2,middleRight = right - 1,middleLeftSum = A[left + 1];middleLeft < middleRight-1; middleLeft++){
if (middleLeftSum >= leftSum) { //如果要是相等,或者比leftSum大,则跳出循环
break;
}else if (middleLeftSum < leftSum) { //如果 <SUF>
middleLeftSum += A[middleLeft];
}
}
if (middleLeftSum < leftSum) { //小于代表着中间值加完了还是小于,所以最外圈循环再加下去会更小,没有必要再继续了
return false;
}else if (middleLeftSum == leftSum) { //相等,判断剩下的值之和是否相等,如果不相等,则继续外圈循环
int middleRightSum = 0;
//因为相等了,所以必然是从middleLeft + 1开始的,因为要空过下一个下标
for(int index = middleLeft + 1;index <= middleRight;index++){
middleRightSum += A[index];
}
//判断是否相等
if (middleRightSum == rightSum) {
return true;
}else {
continue;
}
}else { //大于,给左边继续加,然后继续循环
leftSum += A[left];
left++;
}
}
return false;
}
public static void main(String[] args){
// ArrayList<Integer> inputs = new ArrayList<Integer>();
// Scanner in = new Scanner(System.in);
// String line = in.nextLine();
// while(line != null && !line.isEmpty()) {
// int value = Integer.parseInt(line.trim());
// if(value == 0) break;
// inputs.add(value);
// line = in.nextLine();
// }
// int[] A = new int[inputs.size()];
// for(int i=0; i<inputs.size(); i++) {
// A[i] = inputs.get(i).intValue();
// }
int [] A = {2,2,5,1,2,1,1,3,1,10,1,1,1,1};
Boolean res = resolve(A);
System.out.println(String.valueOf(res));
}
} | 1 | 14 | 1 |
56555_8 | package com.kesar.a;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
*
* ClassName: AStar
* @Description: A星算法
* @author kesar
*/
public class AStar
{
public final static int BAR = 1; // 障碍值
public final static int PATH = 2; // 路径
public final static int DIRECT_VALUE = 10; // 横竖移动代价
public final static int OBLIQUE_VALUE = 14; // 斜移动代价
Queue<Node> openList = new PriorityQueue<Node>(); // 优先队列(升序)
List<Node> closeList = new ArrayList<Node>();
/**
* 开始算法
*/
public void start(MapInfo mapInfo)
{
if(mapInfo==null) return;
// clean
openList.clear();
closeList.clear();
// 开始搜索
openList.add(mapInfo.start);
moveNodes(mapInfo);
}
/**
* 移动当前结点
*/
private void moveNodes(MapInfo mapInfo)
{
while (!openList.isEmpty())
{
Node current = openList.poll();
closeList.add(current);
addNeighborNodeInOpen(mapInfo,current);
if (isCoordInClose(mapInfo.end.coord))
{
drawPath(mapInfo.maps, mapInfo.end);
break;
}
}
}
/**
* 在二维数组中绘制路径
*/
private void drawPath(int[][] maps, Node end)
{
if(end==null||maps==null) return;
System.out.println("总代价:" + end.G);
while (end != null)
{
Coord c = end.coord;
maps[c.y][c.x] = PATH;
end = end.parent;
}
}
/**
* 添加所有邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current)
{
int x = current.coord.x;
int y = current.coord.y;
// 左
addNeighborNodeInOpen(mapInfo,current, x - 1, y, DIRECT_VALUE);
// 上
addNeighborNodeInOpen(mapInfo,current, x, y - 1, DIRECT_VALUE);
// 右
addNeighborNodeInOpen(mapInfo,current, x + 1, y, DIRECT_VALUE);
// 下
addNeighborNodeInOpen(mapInfo,current, x, y + 1, DIRECT_VALUE);
// 左上
addNeighborNodeInOpen(mapInfo,current, x - 1, y - 1, OBLIQUE_VALUE);
// 右上
addNeighborNodeInOpen(mapInfo,current, x + 1, y - 1, OBLIQUE_VALUE);
// 右下
addNeighborNodeInOpen(mapInfo,current, x + 1, y + 1, OBLIQUE_VALUE);
// 左下
addNeighborNodeInOpen(mapInfo,current, x - 1, y + 1, OBLIQUE_VALUE);
}
/**
* 添加一个邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current, int x, int y, int value)
{
if (canAddNodeToOpen(mapInfo,x, y))
{
Node end=mapInfo.end;
Coord coord = new Coord(x, y);
int G = current.G + value; // 计算邻结点的G值
Node child = findNodeInOpen(coord);
if (child == null)
{
int H=calcH(end.coord,coord); // 计算H值
if(isEndNode(end.coord,coord))
{
child=end;
child.parent=current;
child.G=G;
child.H=H;
}
else
{
child = new Node(coord, current, G, H);
}
openList.add(child);
}
else if (child.G > G)
{
child.G = G;
child.parent = current;
openList.add(child);
}
}
}
/**
* 从Open列表中查找结点
*/
private Node findNodeInOpen(Coord coord)
{
if (coord == null || openList.isEmpty()) return null;
for (Node node : openList)
{
if (node.coord.equals(coord))
{
return node;
}
}
return null;
}
/**
* 计算H的估值:“曼哈顿”法,坐标分别取差值相加
*/
private int calcH(Coord end,Coord coord)
{
return (Math.abs(end.x - coord.x) + Math.abs(end.y - coord.y)) * DIRECT_VALUE;
}
/**
* 判断结点是否是最终结点
*/
private boolean isEndNode(Coord end,Coord coord)
{
return coord != null && end.equals(coord);
}
/**
* 判断结点能否放入Open列表
*/
private boolean canAddNodeToOpen(MapInfo mapInfo,int x, int y)
{
// 是否在地图中
if (x < 0 || x >= mapInfo.width || y < 0 || y >= mapInfo.hight) return false;
// 判断是否是不可通过的结点
if (mapInfo.maps[y][x] == BAR) return false;
// 判断结点是否存在close表
if (isCoordInClose(x, y)) return false;
return true;
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(Coord coord)
{
return coord!=null&&isCoordInClose(coord.x, coord.y);
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(int x, int y)
{
if (closeList.isEmpty()) return false;
for (Node node : closeList)
{
if (node.coord.x == x && node.coord.y == y)
{
return true;
}
}
return false;
}
}
| ClaymanTwinkle/astar | src/com/kesar/a/AStar.java | 1,621 | // 开始搜索
| line_comment | zh-cn | package com.kesar.a;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
*
* ClassName: AStar
* @Description: A星算法
* @author kesar
*/
public class AStar
{
public final static int BAR = 1; // 障碍值
public final static int PATH = 2; // 路径
public final static int DIRECT_VALUE = 10; // 横竖移动代价
public final static int OBLIQUE_VALUE = 14; // 斜移动代价
Queue<Node> openList = new PriorityQueue<Node>(); // 优先队列(升序)
List<Node> closeList = new ArrayList<Node>();
/**
* 开始算法
*/
public void start(MapInfo mapInfo)
{
if(mapInfo==null) return;
// clean
openList.clear();
closeList.clear();
// 开始 <SUF>
openList.add(mapInfo.start);
moveNodes(mapInfo);
}
/**
* 移动当前结点
*/
private void moveNodes(MapInfo mapInfo)
{
while (!openList.isEmpty())
{
Node current = openList.poll();
closeList.add(current);
addNeighborNodeInOpen(mapInfo,current);
if (isCoordInClose(mapInfo.end.coord))
{
drawPath(mapInfo.maps, mapInfo.end);
break;
}
}
}
/**
* 在二维数组中绘制路径
*/
private void drawPath(int[][] maps, Node end)
{
if(end==null||maps==null) return;
System.out.println("总代价:" + end.G);
while (end != null)
{
Coord c = end.coord;
maps[c.y][c.x] = PATH;
end = end.parent;
}
}
/**
* 添加所有邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current)
{
int x = current.coord.x;
int y = current.coord.y;
// 左
addNeighborNodeInOpen(mapInfo,current, x - 1, y, DIRECT_VALUE);
// 上
addNeighborNodeInOpen(mapInfo,current, x, y - 1, DIRECT_VALUE);
// 右
addNeighborNodeInOpen(mapInfo,current, x + 1, y, DIRECT_VALUE);
// 下
addNeighborNodeInOpen(mapInfo,current, x, y + 1, DIRECT_VALUE);
// 左上
addNeighborNodeInOpen(mapInfo,current, x - 1, y - 1, OBLIQUE_VALUE);
// 右上
addNeighborNodeInOpen(mapInfo,current, x + 1, y - 1, OBLIQUE_VALUE);
// 右下
addNeighborNodeInOpen(mapInfo,current, x + 1, y + 1, OBLIQUE_VALUE);
// 左下
addNeighborNodeInOpen(mapInfo,current, x - 1, y + 1, OBLIQUE_VALUE);
}
/**
* 添加一个邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current, int x, int y, int value)
{
if (canAddNodeToOpen(mapInfo,x, y))
{
Node end=mapInfo.end;
Coord coord = new Coord(x, y);
int G = current.G + value; // 计算邻结点的G值
Node child = findNodeInOpen(coord);
if (child == null)
{
int H=calcH(end.coord,coord); // 计算H值
if(isEndNode(end.coord,coord))
{
child=end;
child.parent=current;
child.G=G;
child.H=H;
}
else
{
child = new Node(coord, current, G, H);
}
openList.add(child);
}
else if (child.G > G)
{
child.G = G;
child.parent = current;
openList.add(child);
}
}
}
/**
* 从Open列表中查找结点
*/
private Node findNodeInOpen(Coord coord)
{
if (coord == null || openList.isEmpty()) return null;
for (Node node : openList)
{
if (node.coord.equals(coord))
{
return node;
}
}
return null;
}
/**
* 计算H的估值:“曼哈顿”法,坐标分别取差值相加
*/
private int calcH(Coord end,Coord coord)
{
return (Math.abs(end.x - coord.x) + Math.abs(end.y - coord.y)) * DIRECT_VALUE;
}
/**
* 判断结点是否是最终结点
*/
private boolean isEndNode(Coord end,Coord coord)
{
return coord != null && end.equals(coord);
}
/**
* 判断结点能否放入Open列表
*/
private boolean canAddNodeToOpen(MapInfo mapInfo,int x, int y)
{
// 是否在地图中
if (x < 0 || x >= mapInfo.width || y < 0 || y >= mapInfo.hight) return false;
// 判断是否是不可通过的结点
if (mapInfo.maps[y][x] == BAR) return false;
// 判断结点是否存在close表
if (isCoordInClose(x, y)) return false;
return true;
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(Coord coord)
{
return coord!=null&&isCoordInClose(coord.x, coord.y);
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(int x, int y)
{
if (closeList.isEmpty()) return false;
for (Node node : closeList)
{
if (node.coord.x == x && node.coord.y == y)
{
return true;
}
}
return false;
}
}
| 1 | 8 | 1 |
10127_7 | package com.mcylm.coi.realm.tools.npc;
import com.mcylm.coi.realm.model.COINpc;
import com.mcylm.coi.realm.tools.npc.impl.COIEntity;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.List;
/**
* AI的接口层,AI的基础能力
*/
public interface AI {
// 创建NPC
COIEntity create(COINpc coiNpc);
// 更新NPC
COIEntity update(COINpc coiNpc, boolean respawn);
// AI寻路
void findPath(Location location);
// 说话
void say(String message);
// 捡起地上的东西
void pickItems();
// 吃东西
void eatFood();
// 自动穿衣服
void wearClothes();
// 获取NPC附近的方块
List<Block> getNearbyBlocks(double radius);
// 获取NPC附近的生物
List<Entity> getNearByEntities(double radius);
// 移动
void move();
// 生成NPC
void spawn(Location location);
// 消除NPC
void despawn();
// 彻底清除NPC
void remove();
// 是否还或者
boolean isAlive();
// 是否被清除
boolean isRemoved();
// 获取NPC位置
Location getLocation();
default int delayTick() {
return 20;
}
}
| Clayun/coi-realm | src/main/java/com/mcylm/coi/realm/tools/npc/AI.java | 355 | // 获取NPC附近的方块 | line_comment | zh-cn | package com.mcylm.coi.realm.tools.npc;
import com.mcylm.coi.realm.model.COINpc;
import com.mcylm.coi.realm.tools.npc.impl.COIEntity;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.List;
/**
* AI的接口层,AI的基础能力
*/
public interface AI {
// 创建NPC
COIEntity create(COINpc coiNpc);
// 更新NPC
COIEntity update(COINpc coiNpc, boolean respawn);
// AI寻路
void findPath(Location location);
// 说话
void say(String message);
// 捡起地上的东西
void pickItems();
// 吃东西
void eatFood();
// 自动穿衣服
void wearClothes();
// 获取 <SUF>
List<Block> getNearbyBlocks(double radius);
// 获取NPC附近的生物
List<Entity> getNearByEntities(double radius);
// 移动
void move();
// 生成NPC
void spawn(Location location);
// 消除NPC
void despawn();
// 彻底清除NPC
void remove();
// 是否还或者
boolean isAlive();
// 是否被清除
boolean isRemoved();
// 获取NPC位置
Location getLocation();
default int delayTick() {
return 20;
}
}
| 1 | 13 | 1 |
55734_2 | package com.guhao.learn.chapter6;
import java.util.*;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*;
/**
* @Author guhao
* @DateTime 2019-12-06 8:58
* @Description
**/
public class Demo04 {
private static final List<Student> list = new ArrayList<>();
static {
//true未毕业,false毕业
list.add(new Student("酱",23,"male",99.0,true));
list.add(new Student("航",23,"male",99.0,true));
list.add(new Student("兔",23,"male",99.0,true));
list.add(new Student("汁",23,"male",99.0,true));
list.add(new Student("彬",23,"male",99.0,true));
list.add(new Student("马",23,"male",99.0,true));
list.add(new Student("虎",23,"male",99.0,true));
list.add(new Student("菜",23,"male",99.0,true));
list.add(new Student("峰",23,"male",99.0,true));
list.add(new Student("猫",23,"male",99.0,true));
list.add(new Student("狗",18,"male",100.0,false));
list.add(new Student("白",23,"male",99.0,true));
list.add(new Student("夜",23,"male",99.0,true));
list.add(new Student("风",23,"male",99.0,true));
}
public static void main(String[] args) {
//毕业,未毕业人数
Map<Boolean, Long> collect = list.stream()
.collect(partitioningBy(Student::getStatus, counting()));
System.out.println(collect);
//毕业,未毕业
Map<Boolean, Map<String, List<Student>>> collect1 = list.stream()
.collect(partitioningBy(Student::getStatus, groupingBy(Student::getName)));
System.out.println(collect1);
//毕业,未毕业
// list.stream().collect(partitioningBy(Student::getStatus, collectingAndThen(maxBy(Student::getAge),Optional::get)));
}
}
| ClearScenery/Java8-Learn | src/com/guhao/learn/chapter6/Demo04.java | 592 | //毕业,未毕业人数 | line_comment | zh-cn | package com.guhao.learn.chapter6;
import java.util.*;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*;
/**
* @Author guhao
* @DateTime 2019-12-06 8:58
* @Description
**/
public class Demo04 {
private static final List<Student> list = new ArrayList<>();
static {
//true未毕业,false毕业
list.add(new Student("酱",23,"male",99.0,true));
list.add(new Student("航",23,"male",99.0,true));
list.add(new Student("兔",23,"male",99.0,true));
list.add(new Student("汁",23,"male",99.0,true));
list.add(new Student("彬",23,"male",99.0,true));
list.add(new Student("马",23,"male",99.0,true));
list.add(new Student("虎",23,"male",99.0,true));
list.add(new Student("菜",23,"male",99.0,true));
list.add(new Student("峰",23,"male",99.0,true));
list.add(new Student("猫",23,"male",99.0,true));
list.add(new Student("狗",18,"male",100.0,false));
list.add(new Student("白",23,"male",99.0,true));
list.add(new Student("夜",23,"male",99.0,true));
list.add(new Student("风",23,"male",99.0,true));
}
public static void main(String[] args) {
//毕业 <SUF>
Map<Boolean, Long> collect = list.stream()
.collect(partitioningBy(Student::getStatus, counting()));
System.out.println(collect);
//毕业,未毕业
Map<Boolean, Map<String, List<Student>>> collect1 = list.stream()
.collect(partitioningBy(Student::getStatus, groupingBy(Student::getName)));
System.out.println(collect1);
//毕业,未毕业
// list.stream().collect(partitioningBy(Student::getStatus, collectingAndThen(maxBy(Student::getAge),Optional::get)));
}
}
| 1 | 10 | 1 |
58142_10 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.rsf.domain;
import java.util.ArrayList;
import java.util.List;
/**
* RSF Request 的化身,是封装 Request 的数据对象。
* @version : 2014年10月25日
* @author 赵永春 ([email protected])
*/
public class RequestInfo extends OptionInfo {
private long requestID = 0; //请求ID
private short flags = 0; //标签
private long receiveTime = 0; //接收请求(本地时间戳)
private String serviceName = null; //远程服务名
private String serviceGroup = null; //远程服务分组
private String serviceVersion = null; //远程服务版本
private String targetMethod = null; //远程服务方法名
private String serializeType = null; //序列化策略
private int clientTimeout = 0; //远程调用时最大忍受等待时间
private boolean isMessage = false;//是否为消息请求
private List<String> paramTypes = null; //参数类型
private List<Object> paramValues = null; //参数值
//
//
public RequestInfo() {
this.paramTypes = new ArrayList<String>();
this.paramValues = new ArrayList<Object>();
}
/**获取请求ID。*/
public long getRequestID() {
return this.requestID;
}
/**设置请求ID。*/
public void setRequestID(long requestID) {
this.requestID = requestID;
}
/**获取flag*/
public short getFlags() {
return flags;
}
/**设置flag。*/
public void setFlags(short flags) {
this.flags = flags;
}
/**数据包到达时间*/
public void setReceiveTime(long receiveTime) {
this.receiveTime = receiveTime;
}
/**数据包到达时间*/
public long getReceiveTime() {
return this.receiveTime;
}
/**获取服务名*/
public String getServiceName() {
return this.serviceName;
}
/**设置服务名*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/**获取服务分组*/
public String getServiceGroup() {
return this.serviceGroup;
}
/**设置服务分组*/
public void setServiceGroup(String serviceGroup) {
this.serviceGroup = serviceGroup;
}
/**获取服务版本*/
public String getServiceVersion() {
return this.serviceVersion;
}
/**设置服务版本*/
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
/**获取调用的方法名*/
public String getTargetMethod() {
return this.targetMethod;
}
/**设置调用的方法名*/
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
/**获取序列化类型*/
public String getSerializeType() {
return this.serializeType;
}
/**设置序列化类型*/
public void setSerializeType(String serializeType) {
this.serializeType = serializeType;
}
/**获取远程客户端调用超时时间。*/
public int getClientTimeout() {
return this.clientTimeout;
}
/**设置远程客户端调用超时时间。*/
public void setClientTimeout(int clientTimeout) {
this.clientTimeout = clientTimeout;
}
/**是否为消息请求*/
public boolean isMessage() {
return isMessage;
}
/**设置是否为消息请求*/
public void setMessage(boolean message) {
isMessage = message;
}
//
/**添加请求参数。*/
public void addParameter(String paramType, Object paramValue) {
this.paramTypes.add(paramType);
this.paramValues.add(paramValue);
}
/**添加请求参数。*/
public void updateParameter(int index, String paramType, Object paramValue) {
if (index < 0 || index > this.paramTypes.size()) {
throw new IndexOutOfBoundsException("index out of range 0~" + this.paramTypes.size());
}
this.paramTypes.set(index, paramType);
this.paramValues.set(index, paramValue);
}
/**获取请求参数类型列表。*/
public List<String> getParameterTypes() {
return this.paramTypes;
}
/**获取请求参数值列表。*/
public List<Object> getParameterValues() {
return this.paramValues;
}
} | ClouGence/hasor | hasor-rsf/rsf-framework/src/main/java/net/hasor/rsf/domain/RequestInfo.java | 1,186 | //是否为消息请求 | line_comment | zh-cn | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.rsf.domain;
import java.util.ArrayList;
import java.util.List;
/**
* RSF Request 的化身,是封装 Request 的数据对象。
* @version : 2014年10月25日
* @author 赵永春 ([email protected])
*/
public class RequestInfo extends OptionInfo {
private long requestID = 0; //请求ID
private short flags = 0; //标签
private long receiveTime = 0; //接收请求(本地时间戳)
private String serviceName = null; //远程服务名
private String serviceGroup = null; //远程服务分组
private String serviceVersion = null; //远程服务版本
private String targetMethod = null; //远程服务方法名
private String serializeType = null; //序列化策略
private int clientTimeout = 0; //远程调用时最大忍受等待时间
private boolean isMessage = false;//是否 <SUF>
private List<String> paramTypes = null; //参数类型
private List<Object> paramValues = null; //参数值
//
//
public RequestInfo() {
this.paramTypes = new ArrayList<String>();
this.paramValues = new ArrayList<Object>();
}
/**获取请求ID。*/
public long getRequestID() {
return this.requestID;
}
/**设置请求ID。*/
public void setRequestID(long requestID) {
this.requestID = requestID;
}
/**获取flag*/
public short getFlags() {
return flags;
}
/**设置flag。*/
public void setFlags(short flags) {
this.flags = flags;
}
/**数据包到达时间*/
public void setReceiveTime(long receiveTime) {
this.receiveTime = receiveTime;
}
/**数据包到达时间*/
public long getReceiveTime() {
return this.receiveTime;
}
/**获取服务名*/
public String getServiceName() {
return this.serviceName;
}
/**设置服务名*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/**获取服务分组*/
public String getServiceGroup() {
return this.serviceGroup;
}
/**设置服务分组*/
public void setServiceGroup(String serviceGroup) {
this.serviceGroup = serviceGroup;
}
/**获取服务版本*/
public String getServiceVersion() {
return this.serviceVersion;
}
/**设置服务版本*/
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
/**获取调用的方法名*/
public String getTargetMethod() {
return this.targetMethod;
}
/**设置调用的方法名*/
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
/**获取序列化类型*/
public String getSerializeType() {
return this.serializeType;
}
/**设置序列化类型*/
public void setSerializeType(String serializeType) {
this.serializeType = serializeType;
}
/**获取远程客户端调用超时时间。*/
public int getClientTimeout() {
return this.clientTimeout;
}
/**设置远程客户端调用超时时间。*/
public void setClientTimeout(int clientTimeout) {
this.clientTimeout = clientTimeout;
}
/**是否为消息请求*/
public boolean isMessage() {
return isMessage;
}
/**设置是否为消息请求*/
public void setMessage(boolean message) {
isMessage = message;
}
//
/**添加请求参数。*/
public void addParameter(String paramType, Object paramValue) {
this.paramTypes.add(paramType);
this.paramValues.add(paramValue);
}
/**添加请求参数。*/
public void updateParameter(int index, String paramType, Object paramValue) {
if (index < 0 || index > this.paramTypes.size()) {
throw new IndexOutOfBoundsException("index out of range 0~" + this.paramTypes.size());
}
this.paramTypes.set(index, paramType);
this.paramValues.set(index, paramValue);
}
/**获取请求参数类型列表。*/
public List<String> getParameterTypes() {
return this.paramTypes;
}
/**获取请求参数值列表。*/
public List<Object> getParameterValues() {
return this.paramValues;
}
} | 1 | 9 | 1 |
34001_68 | package cn.edu.imau;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author HBYang
* @Package cn.edu.imau
* @date 2022/4/13 18:17
* @Copyright © 内蒙古农业大学职业技术学院计算机技术与信息管理系
*/
public class HunDLFrame extends JPanel implements KeyListener{
//声明背景图片类型
BufferedImage bgImg;
BufferedImage StartBgImg;
BufferedImage EndBgImg;
BufferedImage WinImg;
//实例化英雄
Hero hero =new Hero();
//创建子弹数组
Bullet[] bullets = {};
//创建敌人数组
Enemy[] enemies = {};
//分数
static int SCORE=0;
//子弹个数
static int bullet_number=50;
//敌人出现的位置
String EnemyLocation;
/**
* 游戏的状态
* 0开始 1运行 2暂停 3结束
*/
static int START=0,RUN=1,PAUSE=2,GAME_OVER=3,Game_Win=4;
//游戏当前状态
static int STATE = START;
//static int STATE=1;
boolean isJump = false;//是否是跳跃状态默认为没有跳跃
int Herocount = 0;//timer减速
int winScore = 100;//定义胜利需要的分数
/**
* 利用构造方法载入背景图片
*/
public HunDLFrame(){
try {
bgImg = ImageIO.read(new File("images/bg.png"));
StartBgImg = ImageIO.read(new File("images/Startbg.png"));
EndBgImg = ImageIO.read(new File("images/endframe.png"));
WinImg = ImageIO.read(new File("images/win.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 主方法,创建窗体
* @param args
*/
public static void main(String[] args) {
//创建一个JFrame窗体
JFrame jFrame = new JFrame("简易魂斗罗");
//创建画布
HunDLFrame hunDLFrame = new HunDLFrame();
//将画布添加到窗体中
jFrame.add(hunDLFrame);
//设置窗体大小
jFrame.setSize(900, 623);
//设置默认关闭
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置窗口居中
jFrame.setLocationRelativeTo(null);
//设置窗口可见
jFrame.setVisible(true);
jFrame.addKeyListener(hunDLFrame);
hunDLFrame.Start();
while (true){
playMusic();
}
}
/**
* 绘制方法
* @param g
*/
public void paint(Graphics g){
g.drawImage(bgImg,0,0,null);
if(STATE==START){
//设置字体样式
g.drawImage(StartBgImg,0,0,null);
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,40));
g.setColor(new Color(0xFFFFFF));
g.drawString("请按空格开始游戏",150,400);
}else if(STATE==RUN){
g.drawImage(hero.this_img, hero.x, hero.y,null);
paintObject(bullets,g);//子弹绘制
paintObject(enemies,g);//敌人绘制
paintString(g);//文本绘制
}else if(STATE == PAUSE){
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,40));
g.setColor(new Color(0xFFFFFF));
g.drawString("游戏暂停",280,300);
paintString(g);//文本绘制
}else if(STATE == GAME_OVER){
g.drawImage(EndBgImg,0,0,null);
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,40));
g.setColor(new Color(0xFFFFFF));
g.drawString("Game Over",420,200);
g.drawString("Score:"+SCORE,420,300);
g.drawString("请按空格重新开始游戏",420,400);
}else if(STATE == Game_Win){
g.drawImage(WinImg,50,-150,null);
}
}
/**
* 静态执行HeroJumpTimer线程
*/
{
HeroJump();
}
/**
* 按k跳跃连续动作方法
*/
public void HeroJump(){
Timer timer= new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(Herocount>2){
Herocount = 0;
}
switch (Herocount){
case 0:
//System.out.println(0);
if(isJump){
hero.HeroJump();
Herocount++;
}
break;
case 1:
//System.out.println(3);
if(isJump) {
hero.HeroDown();
Herocount++;
}
break;
case 2:
//System.out.println(6);
if(isJump) {
hero.setStandup();
Herocount++;
isJump = false;
}
break;
}
repaint();//重绘
}
};
timer.schedule(timerTask, 0, 200);
}
//public void HeroJump(Timer timer){
// if (Herocount % 5 ==0 && isJump){
// hero.HeroJump();
// repaint();
// }
// if (Herocount % 10 ==0){
// hero.HeroDown();
// isJump =false;
// repaint();
// timer.cancel();
// hero.setStandup();
// repaint();
// }
//
//
// Herocount++;
//}
/**
* 遍历HunDLObject类型的数组,并调用数组中每个对象的绘制方法
* @param objects 被遍历的数组
* @param g 画笔
*/
public void paintObject(HunDLObject[] objects,Graphics g){
//遍历数组 并调用数组中每一个元素的绘制方法
for (int i = 0; i < objects.length; i++) {
objects[i].paint(g);
}
}
/**
* 添加子弹
*/
private void addBullet() {
if(bullet_number>0){
//给子弹数组扩容
bullets = Arrays.copyOf(bullets, bullets.length + 1);
//创建子弹对象
Bullet b;
if(hero.direction.equals("R")){
b = new Bullet(hero.x + hero.width, hero.y+hero.height/2-30,"R");
}else if(hero.direction.equals("L")){
b = new Bullet(hero.x , hero.y+hero.height/2-30,"L");
}else {
if(hero.isSkyRight){
b = new Bullet(hero.x + hero.width, hero.y+hero.height/2-30,"R");
}else{
b = new Bullet(hero.x , hero.y+hero.height/2-30,"L");
}
}
//将子弹对象添加到数组的末尾
bullets[bullets.length - 1] = b;
bullet_number--;
}
}
Random random = new Random();
int count;//定时器
/**
* 周期性添加敌人
*/
private void addEnemy(){
count++;
if(count % 50 == 0){
if(random.nextInt(2) == 0){
EnemyLocation = "R";
}else {
EnemyLocation = "L";
}
Enemy e = new Enemy(EnemyLocation);
//给敌人数组扩容
enemies = Arrays.copyOf(enemies, enemies.length + 1);
//添加敌人对象到数组中
enemies[enemies.length - 1] = e;
}
}
/**
* 执行
*/
public void Start(){
Timer timer= new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(HunDLFrame.STATE==RUN) {
//角色移动方法
move();
//添加敌人
addEnemy();
count = random.nextInt(30)+20;
checkHit();
removeObject();
isOutOf();
}
repaint();//重绘
}
};
timer.schedule(timerTask, 0, 100);
}
/**
* 绘制文本的方法
* @param g 画笔
*/
private void paintString(Graphics g) {
//设置字体样式
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,30));
g.setColor(new Color(0xFFFFFF));
//绘制分数
g.drawString("分数:"+ HunDLFrame.SCORE,750,30);
//绘制英雄生命
g.drawString("生命值:"+hero.lifes,20,30);
//绘制子弹个数
g.drawString("子弹个数:"+bullet_number,160,30);
}
/**
* 管理游戏中所有角色的移动方法
*/
private void move() {
//遍历敌人数组 并调用数组中每个元素的移动方法
for (int i = 0; i < enemies.length; i++) {
Enemy enemy = enemies[i];
enemy.move();
}
//子弹移动
for (int i = 0; i < bullets.length; i++) {
Bullet bullet = bullets[i];
bullet.move();//子弹移动方法
}
}
/**
* 所有角色判断碰撞的方法
* 1.检查敌人是否与英雄碰撞
* 敌人爆炸后消失,加分
* 英雄爆炸后消失,检查命数,如果<=0就结束游戏
* 2.子弹与敌人碰撞
* 子弹消失
* 敌人,减命1 如果命<=0,敌人爆炸消失
* 3.英雄与救援潜艇碰撞
* 救援潜艇消失,但当前的救援潜艇有奖励属性
* 英雄得到奖励(救援潜艇属性的奖励)
* <p>
* <p>
* 0 1 2
* 0或者 --> 死亡(碰撞后/命<=0) (何时显示爆炸效果?当死亡了就开始显示爆炸图片,何时爆炸图片显示完毕?下标大于等于元素个数)-->删除
*/
public void checkHit() {
//遍历敌人的数组,用每一个敌人与英雄检查碰撞,碰撞修改他们的状态
for (int i = 0; i < enemies.length; i++) {
Enemy enemy = enemies[i];
//判断当前敌人是否与英雄碰撞 并且 当前的敌人状态为活着 与英雄碰撞直接死去
if (enemy.hit(hero) && enemy.state==HunDLObject.LIFE) {
//判断敌人是否死亡
enemy.state = 1;
//碰撞英雄减少生命值
hero.lifes--;
//如果英雄的生命小于等于0就结束游戏
if(hero.lifes<=0){
HunDLFrame.STATE= HunDLFrame.GAME_OVER;
}
continue;
}
//遍历子弹数组,用当前的这个敌人与所有的子弹检查碰撞
for (int j = 0; j < bullets.length; j++) {
Bullet bullet = bullets[j];
//如果敌人j的生命大于0 并且 子弹与敌人碰撞了 .就修改它们的状态
if (bullet.hit(enemy) && enemy.lifes>0) {
//子弹消失
bullet.state = 1;
//敌人减命
//enemy.state=ObjectSubmarine.DIE;
if(enemy.state==0){
enemy.lifes-=1;
//判断敌人的生命值是否足够 没生命值则死亡
if(enemy.lifes<=0){
enemy.state=1;
}
}
}
}
}
}
/**
* 管理所有角色的删除方法
*/
private void removeObject() {
Enemy[] newEnemy = new Enemy[enemies.length];//1
int index = 0;//2
for (int i = 0; i < enemies.length; i++) {//3
Enemy enemy = enemies[i];//获取一个元素(对象)
if (enemy.state != 1) {//敌人存活
newEnemy[index] = enemy;//将存活的敌人放入新数组
index++;
}else{
SCORE+=enemy.getScore();
if(SCORE==winScore){
STATE = Game_Win;
}
}
}
enemies = Arrays.copyOf(newEnemy, index);//将存活的敌人重新赋值到敌人数组中
//删除子弹状态为remove
Bullet[] newBullet = new Bullet[bullets.length];
index = 0;
//遍历源数组
for (int i = 0; i < bullets.length; i++) {
Bullet bullet = bullets[i];
if (bullet.state != 1) {
newBullet[index] = bullet;
index++;
}else{
try {
//bulletMusic();
} catch (Exception e) {
e.printStackTrace();
}
}
}
bullets = Arrays.copyOf(newBullet, index);
}
/**
* 管理所有角色的越界方法
*/
private void isOutOf() {
//遍历敌人数组 并调用敌人的越界判断方法
for (int i = 0; i < enemies.length; i++) {
//Enemy enemy=enemies[i];
//enemy.isOut();
if (enemies[i].isOut()) {//判断该对象是否越界 如果越界就从改变当前对象的状态为删除
//改变当前对象的状态
enemies[i].state = 1;
}
}
//遍历子弹数组
for (int i = 0; i < bullets.length; i++) {
Bullet bullet = bullets[i];
//判断子弹是否越界,如果越界将当前子弹的状态改为remove
if (bullet.isOut()) {
bullet.state = 1;
}
}
}
/**
* 添加背景音乐
* 参考:https://blog.csdn.net/weixin_43926171/article/details/90739074
*/
static void playMusic() {// 背景音乐播放
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("audios/bgsound.mid"));
AudioFormat aif = ais.getFormat();
final SourceDataLine sdl;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(aif);
sdl.start();
FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
// value可以用来设置音量,从0-2.0
double value = 0.2;
float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
fc.setValue(dB);
int nByte = 0;
int writeByte = 0;
final int SIZE = 1024 * 64;
byte[] buffer = new byte[SIZE];
while (nByte != -1) {
if(STATE != PAUSE && STATE!=Game_Win && STATE!=GAME_OVER) {
nByte = ais.read(buffer, 0, SIZE);
sdl.write(buffer, 0, nByte);
}else {
nByte = ais.read(buffer, 0, 0);
}
}
sdl.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 添加子弹击中音效
*/
static void bulletMusic(){
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("audios/m_gun.wav"));
AudioFormat aif = ais.getFormat();
final SourceDataLine sdl;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(aif);
sdl.start();
FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
// value可以用来设置音量,从0-2.0
double value = 1.3;
float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
fc.setValue(dB);
int nByte = 0;
int writeByte = 0;
final int SIZE = 1024 * 64;
byte[] buffer = new byte[SIZE];
nByte = ais.read(buffer, 0, SIZE);
sdl.write(buffer, 0, nByte);
sdl.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 重新开始游戏
*/
private void reSet(){
hero=new Hero();
enemies=new Enemy[0];
bullets=new Bullet[0];
SCORE=0;
bullet_number=50;
STATE= RUN;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override//按键
public void keyPressed(KeyEvent e) {
//System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case 74://发射子弹
addBullet();
hero.HeroShoot();
break;
case 75://按键w 或者k
hero.setDirection("U");
hero.JudgeDirection();
isJump = true;
repaint();
break;
case 87://跳 按键w
hero.setDirection("U");
hero.JudgeDirection();
isJump = true;
repaint();
break;
case 65://左 按键A
hero.setDirection("L");
hero.JudgeDirection();
repaint();
break;
case 68://右 按键 D
hero.setDirection("R");
hero.JudgeDirection();
repaint();
break;
case 32://空格
if(STATE==START){
STATE =RUN;
}else if(STATE==RUN){
STATE =2;
}else if(STATE == PAUSE){
STATE = RUN;
}else if(STATE == GAME_OVER){
reSet();
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| ClutterGit/HunDL | src/cn/edu/imau/HunDLFrame.java | 4,729 | //子弹移动
| line_comment | zh-cn | package cn.edu.imau;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author HBYang
* @Package cn.edu.imau
* @date 2022/4/13 18:17
* @Copyright © 内蒙古农业大学职业技术学院计算机技术与信息管理系
*/
public class HunDLFrame extends JPanel implements KeyListener{
//声明背景图片类型
BufferedImage bgImg;
BufferedImage StartBgImg;
BufferedImage EndBgImg;
BufferedImage WinImg;
//实例化英雄
Hero hero =new Hero();
//创建子弹数组
Bullet[] bullets = {};
//创建敌人数组
Enemy[] enemies = {};
//分数
static int SCORE=0;
//子弹个数
static int bullet_number=50;
//敌人出现的位置
String EnemyLocation;
/**
* 游戏的状态
* 0开始 1运行 2暂停 3结束
*/
static int START=0,RUN=1,PAUSE=2,GAME_OVER=3,Game_Win=4;
//游戏当前状态
static int STATE = START;
//static int STATE=1;
boolean isJump = false;//是否是跳跃状态默认为没有跳跃
int Herocount = 0;//timer减速
int winScore = 100;//定义胜利需要的分数
/**
* 利用构造方法载入背景图片
*/
public HunDLFrame(){
try {
bgImg = ImageIO.read(new File("images/bg.png"));
StartBgImg = ImageIO.read(new File("images/Startbg.png"));
EndBgImg = ImageIO.read(new File("images/endframe.png"));
WinImg = ImageIO.read(new File("images/win.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 主方法,创建窗体
* @param args
*/
public static void main(String[] args) {
//创建一个JFrame窗体
JFrame jFrame = new JFrame("简易魂斗罗");
//创建画布
HunDLFrame hunDLFrame = new HunDLFrame();
//将画布添加到窗体中
jFrame.add(hunDLFrame);
//设置窗体大小
jFrame.setSize(900, 623);
//设置默认关闭
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置窗口居中
jFrame.setLocationRelativeTo(null);
//设置窗口可见
jFrame.setVisible(true);
jFrame.addKeyListener(hunDLFrame);
hunDLFrame.Start();
while (true){
playMusic();
}
}
/**
* 绘制方法
* @param g
*/
public void paint(Graphics g){
g.drawImage(bgImg,0,0,null);
if(STATE==START){
//设置字体样式
g.drawImage(StartBgImg,0,0,null);
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,40));
g.setColor(new Color(0xFFFFFF));
g.drawString("请按空格开始游戏",150,400);
}else if(STATE==RUN){
g.drawImage(hero.this_img, hero.x, hero.y,null);
paintObject(bullets,g);//子弹绘制
paintObject(enemies,g);//敌人绘制
paintString(g);//文本绘制
}else if(STATE == PAUSE){
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,40));
g.setColor(new Color(0xFFFFFF));
g.drawString("游戏暂停",280,300);
paintString(g);//文本绘制
}else if(STATE == GAME_OVER){
g.drawImage(EndBgImg,0,0,null);
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,40));
g.setColor(new Color(0xFFFFFF));
g.drawString("Game Over",420,200);
g.drawString("Score:"+SCORE,420,300);
g.drawString("请按空格重新开始游戏",420,400);
}else if(STATE == Game_Win){
g.drawImage(WinImg,50,-150,null);
}
}
/**
* 静态执行HeroJumpTimer线程
*/
{
HeroJump();
}
/**
* 按k跳跃连续动作方法
*/
public void HeroJump(){
Timer timer= new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(Herocount>2){
Herocount = 0;
}
switch (Herocount){
case 0:
//System.out.println(0);
if(isJump){
hero.HeroJump();
Herocount++;
}
break;
case 1:
//System.out.println(3);
if(isJump) {
hero.HeroDown();
Herocount++;
}
break;
case 2:
//System.out.println(6);
if(isJump) {
hero.setStandup();
Herocount++;
isJump = false;
}
break;
}
repaint();//重绘
}
};
timer.schedule(timerTask, 0, 200);
}
//public void HeroJump(Timer timer){
// if (Herocount % 5 ==0 && isJump){
// hero.HeroJump();
// repaint();
// }
// if (Herocount % 10 ==0){
// hero.HeroDown();
// isJump =false;
// repaint();
// timer.cancel();
// hero.setStandup();
// repaint();
// }
//
//
// Herocount++;
//}
/**
* 遍历HunDLObject类型的数组,并调用数组中每个对象的绘制方法
* @param objects 被遍历的数组
* @param g 画笔
*/
public void paintObject(HunDLObject[] objects,Graphics g){
//遍历数组 并调用数组中每一个元素的绘制方法
for (int i = 0; i < objects.length; i++) {
objects[i].paint(g);
}
}
/**
* 添加子弹
*/
private void addBullet() {
if(bullet_number>0){
//给子弹数组扩容
bullets = Arrays.copyOf(bullets, bullets.length + 1);
//创建子弹对象
Bullet b;
if(hero.direction.equals("R")){
b = new Bullet(hero.x + hero.width, hero.y+hero.height/2-30,"R");
}else if(hero.direction.equals("L")){
b = new Bullet(hero.x , hero.y+hero.height/2-30,"L");
}else {
if(hero.isSkyRight){
b = new Bullet(hero.x + hero.width, hero.y+hero.height/2-30,"R");
}else{
b = new Bullet(hero.x , hero.y+hero.height/2-30,"L");
}
}
//将子弹对象添加到数组的末尾
bullets[bullets.length - 1] = b;
bullet_number--;
}
}
Random random = new Random();
int count;//定时器
/**
* 周期性添加敌人
*/
private void addEnemy(){
count++;
if(count % 50 == 0){
if(random.nextInt(2) == 0){
EnemyLocation = "R";
}else {
EnemyLocation = "L";
}
Enemy e = new Enemy(EnemyLocation);
//给敌人数组扩容
enemies = Arrays.copyOf(enemies, enemies.length + 1);
//添加敌人对象到数组中
enemies[enemies.length - 1] = e;
}
}
/**
* 执行
*/
public void Start(){
Timer timer= new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(HunDLFrame.STATE==RUN) {
//角色移动方法
move();
//添加敌人
addEnemy();
count = random.nextInt(30)+20;
checkHit();
removeObject();
isOutOf();
}
repaint();//重绘
}
};
timer.schedule(timerTask, 0, 100);
}
/**
* 绘制文本的方法
* @param g 画笔
*/
private void paintString(Graphics g) {
//设置字体样式
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,30));
g.setColor(new Color(0xFFFFFF));
//绘制分数
g.drawString("分数:"+ HunDLFrame.SCORE,750,30);
//绘制英雄生命
g.drawString("生命值:"+hero.lifes,20,30);
//绘制子弹个数
g.drawString("子弹个数:"+bullet_number,160,30);
}
/**
* 管理游戏中所有角色的移动方法
*/
private void move() {
//遍历敌人数组 并调用数组中每个元素的移动方法
for (int i = 0; i < enemies.length; i++) {
Enemy enemy = enemies[i];
enemy.move();
}
//子弹 <SUF>
for (int i = 0; i < bullets.length; i++) {
Bullet bullet = bullets[i];
bullet.move();//子弹移动方法
}
}
/**
* 所有角色判断碰撞的方法
* 1.检查敌人是否与英雄碰撞
* 敌人爆炸后消失,加分
* 英雄爆炸后消失,检查命数,如果<=0就结束游戏
* 2.子弹与敌人碰撞
* 子弹消失
* 敌人,减命1 如果命<=0,敌人爆炸消失
* 3.英雄与救援潜艇碰撞
* 救援潜艇消失,但当前的救援潜艇有奖励属性
* 英雄得到奖励(救援潜艇属性的奖励)
* <p>
* <p>
* 0 1 2
* 0或者 --> 死亡(碰撞后/命<=0) (何时显示爆炸效果?当死亡了就开始显示爆炸图片,何时爆炸图片显示完毕?下标大于等于元素个数)-->删除
*/
public void checkHit() {
//遍历敌人的数组,用每一个敌人与英雄检查碰撞,碰撞修改他们的状态
for (int i = 0; i < enemies.length; i++) {
Enemy enemy = enemies[i];
//判断当前敌人是否与英雄碰撞 并且 当前的敌人状态为活着 与英雄碰撞直接死去
if (enemy.hit(hero) && enemy.state==HunDLObject.LIFE) {
//判断敌人是否死亡
enemy.state = 1;
//碰撞英雄减少生命值
hero.lifes--;
//如果英雄的生命小于等于0就结束游戏
if(hero.lifes<=0){
HunDLFrame.STATE= HunDLFrame.GAME_OVER;
}
continue;
}
//遍历子弹数组,用当前的这个敌人与所有的子弹检查碰撞
for (int j = 0; j < bullets.length; j++) {
Bullet bullet = bullets[j];
//如果敌人j的生命大于0 并且 子弹与敌人碰撞了 .就修改它们的状态
if (bullet.hit(enemy) && enemy.lifes>0) {
//子弹消失
bullet.state = 1;
//敌人减命
//enemy.state=ObjectSubmarine.DIE;
if(enemy.state==0){
enemy.lifes-=1;
//判断敌人的生命值是否足够 没生命值则死亡
if(enemy.lifes<=0){
enemy.state=1;
}
}
}
}
}
}
/**
* 管理所有角色的删除方法
*/
private void removeObject() {
Enemy[] newEnemy = new Enemy[enemies.length];//1
int index = 0;//2
for (int i = 0; i < enemies.length; i++) {//3
Enemy enemy = enemies[i];//获取一个元素(对象)
if (enemy.state != 1) {//敌人存活
newEnemy[index] = enemy;//将存活的敌人放入新数组
index++;
}else{
SCORE+=enemy.getScore();
if(SCORE==winScore){
STATE = Game_Win;
}
}
}
enemies = Arrays.copyOf(newEnemy, index);//将存活的敌人重新赋值到敌人数组中
//删除子弹状态为remove
Bullet[] newBullet = new Bullet[bullets.length];
index = 0;
//遍历源数组
for (int i = 0; i < bullets.length; i++) {
Bullet bullet = bullets[i];
if (bullet.state != 1) {
newBullet[index] = bullet;
index++;
}else{
try {
//bulletMusic();
} catch (Exception e) {
e.printStackTrace();
}
}
}
bullets = Arrays.copyOf(newBullet, index);
}
/**
* 管理所有角色的越界方法
*/
private void isOutOf() {
//遍历敌人数组 并调用敌人的越界判断方法
for (int i = 0; i < enemies.length; i++) {
//Enemy enemy=enemies[i];
//enemy.isOut();
if (enemies[i].isOut()) {//判断该对象是否越界 如果越界就从改变当前对象的状态为删除
//改变当前对象的状态
enemies[i].state = 1;
}
}
//遍历子弹数组
for (int i = 0; i < bullets.length; i++) {
Bullet bullet = bullets[i];
//判断子弹是否越界,如果越界将当前子弹的状态改为remove
if (bullet.isOut()) {
bullet.state = 1;
}
}
}
/**
* 添加背景音乐
* 参考:https://blog.csdn.net/weixin_43926171/article/details/90739074
*/
static void playMusic() {// 背景音乐播放
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("audios/bgsound.mid"));
AudioFormat aif = ais.getFormat();
final SourceDataLine sdl;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(aif);
sdl.start();
FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
// value可以用来设置音量,从0-2.0
double value = 0.2;
float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
fc.setValue(dB);
int nByte = 0;
int writeByte = 0;
final int SIZE = 1024 * 64;
byte[] buffer = new byte[SIZE];
while (nByte != -1) {
if(STATE != PAUSE && STATE!=Game_Win && STATE!=GAME_OVER) {
nByte = ais.read(buffer, 0, SIZE);
sdl.write(buffer, 0, nByte);
}else {
nByte = ais.read(buffer, 0, 0);
}
}
sdl.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 添加子弹击中音效
*/
static void bulletMusic(){
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("audios/m_gun.wav"));
AudioFormat aif = ais.getFormat();
final SourceDataLine sdl;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(aif);
sdl.start();
FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
// value可以用来设置音量,从0-2.0
double value = 1.3;
float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
fc.setValue(dB);
int nByte = 0;
int writeByte = 0;
final int SIZE = 1024 * 64;
byte[] buffer = new byte[SIZE];
nByte = ais.read(buffer, 0, SIZE);
sdl.write(buffer, 0, nByte);
sdl.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 重新开始游戏
*/
private void reSet(){
hero=new Hero();
enemies=new Enemy[0];
bullets=new Bullet[0];
SCORE=0;
bullet_number=50;
STATE= RUN;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override//按键
public void keyPressed(KeyEvent e) {
//System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case 74://发射子弹
addBullet();
hero.HeroShoot();
break;
case 75://按键w 或者k
hero.setDirection("U");
hero.JudgeDirection();
isJump = true;
repaint();
break;
case 87://跳 按键w
hero.setDirection("U");
hero.JudgeDirection();
isJump = true;
repaint();
break;
case 65://左 按键A
hero.setDirection("L");
hero.JudgeDirection();
repaint();
break;
case 68://右 按键 D
hero.setDirection("R");
hero.JudgeDirection();
repaint();
break;
case 32://空格
if(STATE==START){
STATE =RUN;
}else if(STATE==RUN){
STATE =2;
}else if(STATE == PAUSE){
STATE = RUN;
}else if(STATE == GAME_OVER){
reSet();
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| 0 | 7 | 0 |
27464_56 | package server;
import common.PacketBuffer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
import java.net.Socket;
class Client {
// 服务端->客户端数据包类型常量
private static final int PACKET_LOGIN_SUCCESS = 1; // 登陆成功数据包类型
private static final int PACKET_USER_ONLINE = 2; // 用户上线数据包类型
private static final int PACKET_USER_OFFLINE = 3; // 用户下线数据包类型
private static final int PACKET_GROUP_MSG = 4; // 群消息数据包类型
private static final int PACKET_DM_MSG = 5; // 私聊消息数据包类型
private static final Hashtable<Integer, Client> clients = new Hashtable<>();
private static final long CONN_CHECK_PERIOD = 60000; // 检查客户端超时的间隔时间
/**
* 检查所有已登录客户端数据包是否超时
*/
private static void checkConn() {
for (Client client : clients.values()) {
if (client.status.isTimeout()) { // 这个客户端超时了
client.close("数据包超时");
}
}
}
static { // ConnCheck
Timer timer = new Timer(true); // 后台线程
timer.schedule(new TimerTask() {
public void run() {
checkConn();
}
}, 0, CONN_CHECK_PERIOD);
}
/**
* 向所有在线用户广播数据
* @param buf 字节流
*/
private static void broadCast(PacketBuffer buf) {
for (Client client : clients.values()) {
synchronized (client.output) {
try {
buf.writeTo(client.output);
} catch (IOException ignored) {}
}
}
}
/**
* 群发通知:某用户下线
* @param userId 下线用户的id
*/
private static void notifyUserOffline(int userId) {
PacketBuffer buf = new PacketBuffer();
// 用户下线数据包类型
buf.write(PACKET_USER_OFFLINE);
// 用户id
buf.writeUint16(userId);
// 向所有在线用户进行群发
broadCast(buf);
}
/**
* 群发通知:某用户上线
* @param userId 上线用户id
* @param userNameBytes 上线用户名字节
*/
private static void notifyUserOnline(int userId, byte[] userNameBytes) {
PacketBuffer buf = new PacketBuffer();
// 用户上线数据包类型
buf.write(PACKET_USER_ONLINE);
// 用户id
buf.writeUint16(userId);
// 用户名字节数
buf.write(userNameBytes.length);
// 用户名字节
buf.writeBytes(userNameBytes);
// 向所有在线用户进行群发
broadCast(buf);
}
/**
* 获取当前在线用户列表(登陆成功包)
* @return 数据流
*/
private static PacketBuffer getUserList() {
PacketBuffer buf = new PacketBuffer();
int cnt = clients.size();
// 在线用户数量
buf.writeUint16(cnt);
for (Client client : clients.values()) {
// 当前用户id
buf.writeUint16(client.userId);
// 当前用户用户名长度
buf.write(client.userNameBytes.length);
// 用户名文本
buf.writeBytes(client.userNameBytes);
}
return buf;
}
private final DataOutputStream output; // 写入输出数据流时必须使用synchronized块,防止多个线程同时写入造成数据包错误
private final Socket socket;
private final int userId;
private final byte[] userNameBytes;
public final ConnStatus status; // 接收数据包状态对象,用于检测链接超时
/**
* 用户登陆
* @param conn 用户Socket对象
* @param id 用户id
* @param name 用户名
* @throws IOException Socket异常直接抛出
*/
public Client(Socket conn, int id, String name) throws IOException {
socket = conn;
output = new DataOutputStream(conn.getOutputStream());
userId = id;
userNameBytes = name.getBytes();
status = new ConnStatus();
if (clients.containsKey(id)) { // 同帐号重复登陆
clients.get(id).close("id在另一个客户端登陆"); // 把前一个用户踢下线
}
notifyUserOnline(id, userNameBytes); // 通知所有在线用户
clients.put(id, this); // 将新用户加入列表
// 发送登陆成功数据包
synchronized (output) {
// 数据包类型
output.write(PACKET_LOGIN_SUCCESS);
// 用户列表
getUserList().writeTo(output);
}
}
/**
* 关闭用户连接
* @param msg 错误/提示信息
*/
public void close(String msg) {
// 用户已经下线,忽略
if (!clients.containsKey(userId)) {
return;
}
clients.remove(userId);
try {
byte[] bytes = msg.getBytes(); // 错误信息字节
synchronized (output) {
output.writeByte(0); // 错误包类型
output.writeByte(bytes.length); // 错误信息长度
output.write(bytes); // 错误信息字节
}
socket.close();
} catch (IOException ignored) {} finally {
notifyUserOffline(userId);
}
}
/**
* 用户发送群消息
* @param msgType 消息内容类型
* @param msg 消息内容
*/
public void sendGroupMsg(int msgType, byte[] msg) {
PacketBuffer buf = new PacketBuffer();
buf.write(PACKET_GROUP_MSG); // 群发消息数据包类型
buf.writeUint16(userId); // 发送者id
buf.writeUint32(System.currentTimeMillis() / 1000); // 时间戳
buf.write(msgType); // 消息类型
buf.writeUint16(msg.length); // 消息内容长度
buf.writeBytes(msg); // 内容字节
broadCast(buf);
}
/**
* 用户发送私聊消息
* @param targetId 发送目标id
* @param msgType 消息内容类型
* @param msg 消息内容
*/
public void sendDmMsg(int targetId, int msgType, byte[] msg) {
PacketBuffer buf = new PacketBuffer();
buf.write(PACKET_DM_MSG); // 私聊消息数据包类型
buf.writeUint16(userId); // 发送者id
buf.writeUint32(System.currentTimeMillis() / 1000); // 时间戳
buf.write(msgType); // 消息类型
buf.writeUint16(msg.length); // 消息内容长度
buf.writeBytes(msg); // 内容字节
Client target = clients.get(targetId);
if (target == null) return;
synchronized (target.output) {
try {
buf.writeTo(target.output);
} catch (IOException ignored) {}
}
}
}
| CmdBlockZQG/java-chat | server/Client.java | 1,658 | // 内容字节 | line_comment | zh-cn | package server;
import common.PacketBuffer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
import java.net.Socket;
class Client {
// 服务端->客户端数据包类型常量
private static final int PACKET_LOGIN_SUCCESS = 1; // 登陆成功数据包类型
private static final int PACKET_USER_ONLINE = 2; // 用户上线数据包类型
private static final int PACKET_USER_OFFLINE = 3; // 用户下线数据包类型
private static final int PACKET_GROUP_MSG = 4; // 群消息数据包类型
private static final int PACKET_DM_MSG = 5; // 私聊消息数据包类型
private static final Hashtable<Integer, Client> clients = new Hashtable<>();
private static final long CONN_CHECK_PERIOD = 60000; // 检查客户端超时的间隔时间
/**
* 检查所有已登录客户端数据包是否超时
*/
private static void checkConn() {
for (Client client : clients.values()) {
if (client.status.isTimeout()) { // 这个客户端超时了
client.close("数据包超时");
}
}
}
static { // ConnCheck
Timer timer = new Timer(true); // 后台线程
timer.schedule(new TimerTask() {
public void run() {
checkConn();
}
}, 0, CONN_CHECK_PERIOD);
}
/**
* 向所有在线用户广播数据
* @param buf 字节流
*/
private static void broadCast(PacketBuffer buf) {
for (Client client : clients.values()) {
synchronized (client.output) {
try {
buf.writeTo(client.output);
} catch (IOException ignored) {}
}
}
}
/**
* 群发通知:某用户下线
* @param userId 下线用户的id
*/
private static void notifyUserOffline(int userId) {
PacketBuffer buf = new PacketBuffer();
// 用户下线数据包类型
buf.write(PACKET_USER_OFFLINE);
// 用户id
buf.writeUint16(userId);
// 向所有在线用户进行群发
broadCast(buf);
}
/**
* 群发通知:某用户上线
* @param userId 上线用户id
* @param userNameBytes 上线用户名字节
*/
private static void notifyUserOnline(int userId, byte[] userNameBytes) {
PacketBuffer buf = new PacketBuffer();
// 用户上线数据包类型
buf.write(PACKET_USER_ONLINE);
// 用户id
buf.writeUint16(userId);
// 用户名字节数
buf.write(userNameBytes.length);
// 用户名字节
buf.writeBytes(userNameBytes);
// 向所有在线用户进行群发
broadCast(buf);
}
/**
* 获取当前在线用户列表(登陆成功包)
* @return 数据流
*/
private static PacketBuffer getUserList() {
PacketBuffer buf = new PacketBuffer();
int cnt = clients.size();
// 在线用户数量
buf.writeUint16(cnt);
for (Client client : clients.values()) {
// 当前用户id
buf.writeUint16(client.userId);
// 当前用户用户名长度
buf.write(client.userNameBytes.length);
// 用户名文本
buf.writeBytes(client.userNameBytes);
}
return buf;
}
private final DataOutputStream output; // 写入输出数据流时必须使用synchronized块,防止多个线程同时写入造成数据包错误
private final Socket socket;
private final int userId;
private final byte[] userNameBytes;
public final ConnStatus status; // 接收数据包状态对象,用于检测链接超时
/**
* 用户登陆
* @param conn 用户Socket对象
* @param id 用户id
* @param name 用户名
* @throws IOException Socket异常直接抛出
*/
public Client(Socket conn, int id, String name) throws IOException {
socket = conn;
output = new DataOutputStream(conn.getOutputStream());
userId = id;
userNameBytes = name.getBytes();
status = new ConnStatus();
if (clients.containsKey(id)) { // 同帐号重复登陆
clients.get(id).close("id在另一个客户端登陆"); // 把前一个用户踢下线
}
notifyUserOnline(id, userNameBytes); // 通知所有在线用户
clients.put(id, this); // 将新用户加入列表
// 发送登陆成功数据包
synchronized (output) {
// 数据包类型
output.write(PACKET_LOGIN_SUCCESS);
// 用户列表
getUserList().writeTo(output);
}
}
/**
* 关闭用户连接
* @param msg 错误/提示信息
*/
public void close(String msg) {
// 用户已经下线,忽略
if (!clients.containsKey(userId)) {
return;
}
clients.remove(userId);
try {
byte[] bytes = msg.getBytes(); // 错误信息字节
synchronized (output) {
output.writeByte(0); // 错误包类型
output.writeByte(bytes.length); // 错误信息长度
output.write(bytes); // 错误信息字节
}
socket.close();
} catch (IOException ignored) {} finally {
notifyUserOffline(userId);
}
}
/**
* 用户发送群消息
* @param msgType 消息内容类型
* @param msg 消息内容
*/
public void sendGroupMsg(int msgType, byte[] msg) {
PacketBuffer buf = new PacketBuffer();
buf.write(PACKET_GROUP_MSG); // 群发消息数据包类型
buf.writeUint16(userId); // 发送者id
buf.writeUint32(System.currentTimeMillis() / 1000); // 时间戳
buf.write(msgType); // 消息类型
buf.writeUint16(msg.length); // 消息内容长度
buf.writeBytes(msg); // 内容字节
broadCast(buf);
}
/**
* 用户发送私聊消息
* @param targetId 发送目标id
* @param msgType 消息内容类型
* @param msg 消息内容
*/
public void sendDmMsg(int targetId, int msgType, byte[] msg) {
PacketBuffer buf = new PacketBuffer();
buf.write(PACKET_DM_MSG); // 私聊消息数据包类型
buf.writeUint16(userId); // 发送者id
buf.writeUint32(System.currentTimeMillis() / 1000); // 时间戳
buf.write(msgType); // 消息类型
buf.writeUint16(msg.length); // 消息内容长度
buf.writeBytes(msg); // 内容 <SUF>
Client target = clients.get(targetId);
if (target == null) return;
synchronized (target.output) {
try {
buf.writeTo(target.output);
} catch (IOException ignored) {}
}
}
}
| 0 | 7 | 0 |
37126_17 | /*
* Copyright 2022-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.code13.javase.time;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* @author <a href="https://github.com/Code-13/">code13</a>
* @date 2021/6/15 13:55
*/
class ZoneAndOffsetTest {
@DisplayName("ZoneId: 指定时区标识符并提供 Instant 和 LocalDateTime 之间转换的规则。")
static class ZoneIdTest {
@Test
@DisplayName("ZoneId")
void test1() {
// 获取所有可用的时区
Set<String> allZones = ZoneId.getAvailableZoneIds();
// 按自然顺序排序
// Create a List using the set of zones and sort it.
List<String> zoneList = new ArrayList<>(allZones);
Collections.sort(zoneList);
LocalDateTime dt = LocalDateTime.now();
for (String s : zoneList) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zonedDateTime = dt.atZone(zone);
ZoneOffset offset = zonedDateTime.getOffset();
int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
String out = String.format("%35s %10s%n", zone, offset);
if (secondsOfHour != 0) {
System.out.printf(out);
}
}
}
}
/**
* 你什么时候使用 OffsetDateTime 而不是 ZonedDateTime? 如果您正在编写复杂的软件,
* 该软件根据地理位置对自己的日期和时间计算规则进行建模,或者将时间戳存储在仅跟踪格林威治/ UTC 时间的绝对偏移量的数据库中, 则可能需要使用 OffsetDateTime。另外,XML
* 和其他网络格式将日期时间传输定义为 OffsetDateTime 或 OffsetTime。
*/
@DisplayName("java.time.ZonedDateTime")
static class ZonedDateTimeTest {
// 实际上,结合了 LocalDateTime 与类 了 zoneid 类。它用于表示具有时区(地区/城市,如欧洲/巴黎)的完整日期(年,月,日)和时间(小时,分钟,秒,纳秒)。
@Test
@DisplayName("ZonedDateTime 示例")
void test1() {
// DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
// Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
// 2013-07-20 19:30:00
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Flight is 10 hours and 50 minutes, or 650 minutes
ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
// 使用美国洛杉矶出发的时间,然后换算成东京的时区,返回该时区对应的时间
ZonedDateTime arrival =
departure.withZoneSameInstant(arrivingZone).plusMinutes(650); // 在该时区的基础上加650分钟
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
// 夏令时
if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) {
System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone);
} else {
// 标准时间
System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone);
}
}
}
/**
* 结合了 LocalDateTime 与类 ZoneOffset 类。 它用于表示格林威治/ UTC 时间的偏移量 (+/-小时:分钟,例如 +06:00
* 或-)的整个日期(年,月,日)和时间(小时,分钟,秒,纳秒)08:00)。
*/
@DisplayName("java.time.OffsetDateTime")
static class OffsetDateTimeTest {
@Test
@DisplayName("OffsetDateTime")
void test1() {
LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
OffsetDateTime lastThursday =
offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf(
"The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());
}
}
/**
* 结合 LocalDateTime 与类 ZoneOffset 类。它用于表示格林威治/ UTC 时间偏移 (+/-小时:分钟,例如+06:00或-08:00)的时间(小时,分钟,秒,纳秒)。
*/
@DisplayName("java.time.OffsetTime")
static class OffsetTime {
@Test
@DisplayName("OffsetTime 示例")
void test1() {
// 一个不带任何时区的时间
LocalDateTime date = LocalDateTime.of(2018, 05, 01, 0, 0, 0);
ZonedDateTime d1 = ZonedDateTime.of(date, ZoneId.systemDefault());
ZoneOffset offset = ZoneOffset.of("+08:00");
OffsetDateTime d2 = OffsetDateTime.of(date, offset);
// 2018-05-01T00:00+08:00[GMT+08:00]
// ZoneId 带了具体的ID
System.out.println(d1);
// 2018-05-01T00:00+08:00
// 而偏移没有ID,因为多个ID对应的值有可能是一样的
System.out.println(d2);
// 那么把中国时间变成其他的时间
// 2018-04-30T20:00+04:00[Asia/Yerevan]
// 把该时间转换成指定时区了
d1.withZoneSameInstant(ZoneId.of("Asia/Yerevan"));
// 2018-05-01T00:00+04:00[Asia/Yerevan]
// 只是改变了时区
d1.withZoneSameLocal(ZoneId.of("Asia/Yerevan"));
}
}
}
| Code-13/java-stack-labs | javase/java-time/src/main/java/io/github/code13/javase/time/ZoneAndOffsetTest.java | 2,028 | // 一个不带任何时区的时间 | line_comment | zh-cn | /*
* Copyright 2022-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.code13.javase.time;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* @author <a href="https://github.com/Code-13/">code13</a>
* @date 2021/6/15 13:55
*/
class ZoneAndOffsetTest {
@DisplayName("ZoneId: 指定时区标识符并提供 Instant 和 LocalDateTime 之间转换的规则。")
static class ZoneIdTest {
@Test
@DisplayName("ZoneId")
void test1() {
// 获取所有可用的时区
Set<String> allZones = ZoneId.getAvailableZoneIds();
// 按自然顺序排序
// Create a List using the set of zones and sort it.
List<String> zoneList = new ArrayList<>(allZones);
Collections.sort(zoneList);
LocalDateTime dt = LocalDateTime.now();
for (String s : zoneList) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zonedDateTime = dt.atZone(zone);
ZoneOffset offset = zonedDateTime.getOffset();
int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
String out = String.format("%35s %10s%n", zone, offset);
if (secondsOfHour != 0) {
System.out.printf(out);
}
}
}
}
/**
* 你什么时候使用 OffsetDateTime 而不是 ZonedDateTime? 如果您正在编写复杂的软件,
* 该软件根据地理位置对自己的日期和时间计算规则进行建模,或者将时间戳存储在仅跟踪格林威治/ UTC 时间的绝对偏移量的数据库中, 则可能需要使用 OffsetDateTime。另外,XML
* 和其他网络格式将日期时间传输定义为 OffsetDateTime 或 OffsetTime。
*/
@DisplayName("java.time.ZonedDateTime")
static class ZonedDateTimeTest {
// 实际上,结合了 LocalDateTime 与类 了 zoneid 类。它用于表示具有时区(地区/城市,如欧洲/巴黎)的完整日期(年,月,日)和时间(小时,分钟,秒,纳秒)。
@Test
@DisplayName("ZonedDateTime 示例")
void test1() {
// DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
// Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
// 2013-07-20 19:30:00
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Flight is 10 hours and 50 minutes, or 650 minutes
ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
// 使用美国洛杉矶出发的时间,然后换算成东京的时区,返回该时区对应的时间
ZonedDateTime arrival =
departure.withZoneSameInstant(arrivingZone).plusMinutes(650); // 在该时区的基础上加650分钟
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
// 夏令时
if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) {
System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone);
} else {
// 标准时间
System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone);
}
}
}
/**
* 结合了 LocalDateTime 与类 ZoneOffset 类。 它用于表示格林威治/ UTC 时间的偏移量 (+/-小时:分钟,例如 +06:00
* 或-)的整个日期(年,月,日)和时间(小时,分钟,秒,纳秒)08:00)。
*/
@DisplayName("java.time.OffsetDateTime")
static class OffsetDateTimeTest {
@Test
@DisplayName("OffsetDateTime")
void test1() {
LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
OffsetDateTime lastThursday =
offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf(
"The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());
}
}
/**
* 结合 LocalDateTime 与类 ZoneOffset 类。它用于表示格林威治/ UTC 时间偏移 (+/-小时:分钟,例如+06:00或-08:00)的时间(小时,分钟,秒,纳秒)。
*/
@DisplayName("java.time.OffsetTime")
static class OffsetTime {
@Test
@DisplayName("OffsetTime 示例")
void test1() {
// 一个 <SUF>
LocalDateTime date = LocalDateTime.of(2018, 05, 01, 0, 0, 0);
ZonedDateTime d1 = ZonedDateTime.of(date, ZoneId.systemDefault());
ZoneOffset offset = ZoneOffset.of("+08:00");
OffsetDateTime d2 = OffsetDateTime.of(date, offset);
// 2018-05-01T00:00+08:00[GMT+08:00]
// ZoneId 带了具体的ID
System.out.println(d1);
// 2018-05-01T00:00+08:00
// 而偏移没有ID,因为多个ID对应的值有可能是一样的
System.out.println(d2);
// 那么把中国时间变成其他的时间
// 2018-04-30T20:00+04:00[Asia/Yerevan]
// 把该时间转换成指定时区了
d1.withZoneSameInstant(ZoneId.of("Asia/Yerevan"));
// 2018-05-01T00:00+04:00[Asia/Yerevan]
// 只是改变了时区
d1.withZoneSameLocal(ZoneId.of("Asia/Yerevan"));
}
}
}
| 1 | 14 | 1 |
19707_15 | package pic;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChart {
ChartPanel frame1;
public BarChart(){
CategoryDataset dataset = getDataSet();
JFreeChart chart = ChartFactory.createBarChart3D(
"水果", // 图表标题
"水果种类", // 目录轴的显示标签
"数量", // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
false, // 是否生成工具
false // 是否生成URL链接
);
//从这里开始
CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象
CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题
ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体
//到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题
frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame
}
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "北京", "苹果");
dataset.addValue(100, "上海", "苹果");
dataset.addValue(100, "广州", "苹果");
dataset.addValue(200, "北京", "梨子");
dataset.addValue(200, "上海", "梨子");
dataset.addValue(200, "广州", "梨子");
dataset.addValue(300, "北京", "葡萄");
dataset.addValue(300, "上海", "葡萄");
dataset.addValue(300, "广州", "葡萄");
dataset.addValue(400, "北京", "香蕉");
dataset.addValue(400, "上海", "香蕉");
dataset.addValue(400, "广州", "香蕉");
dataset.addValue(500, "北京", "荔枝");
dataset.addValue(500, "上海", "荔枝");
dataset.addValue(500, "广州", "荔枝");
return dataset;
}
public ChartPanel getChartPanel(){
return frame1;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFrame jframe = new JFrame();
jframe.setSize(1200,600);
jframe.setLocationRelativeTo(null);
jframe.setDefaultCloseOperation(3);
BarChart bar = new BarChart();
ChartPanel panel = bar.getChartPanel();
jframe.add(panel);
jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| CodeAsPoetry/PublicOpinion | src/pic/BarChart.java | 1,050 | //到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题 | line_comment | zh-cn | package pic;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChart {
ChartPanel frame1;
public BarChart(){
CategoryDataset dataset = getDataSet();
JFreeChart chart = ChartFactory.createBarChart3D(
"水果", // 图表标题
"水果种类", // 目录轴的显示标签
"数量", // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
false, // 是否生成工具
false // 是否生成URL链接
);
//从这里开始
CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象
CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题
ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体
//到这 <SUF>
frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame
}
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "北京", "苹果");
dataset.addValue(100, "上海", "苹果");
dataset.addValue(100, "广州", "苹果");
dataset.addValue(200, "北京", "梨子");
dataset.addValue(200, "上海", "梨子");
dataset.addValue(200, "广州", "梨子");
dataset.addValue(300, "北京", "葡萄");
dataset.addValue(300, "上海", "葡萄");
dataset.addValue(300, "广州", "葡萄");
dataset.addValue(400, "北京", "香蕉");
dataset.addValue(400, "上海", "香蕉");
dataset.addValue(400, "广州", "香蕉");
dataset.addValue(500, "北京", "荔枝");
dataset.addValue(500, "上海", "荔枝");
dataset.addValue(500, "广州", "荔枝");
return dataset;
}
public ChartPanel getChartPanel(){
return frame1;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFrame jframe = new JFrame();
jframe.setSize(1200,600);
jframe.setLocationRelativeTo(null);
jframe.setDefaultCloseOperation(3);
BarChart bar = new BarChart();
ChartPanel panel = bar.getChartPanel();
jframe.add(panel);
jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| 1 | 32 | 1 |
53514_4 | package HOther;
import jdk.internal.org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
public class xmlDemo {
public static void main(String[] args) {
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder的对象
try {
//创建DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下
Document document = db.parse("./src/HOther/book.xml");
//获取所有book节点的集合
NodeList bookList = document.getElementsByTagName("book");
//通过nodelist的getLength()方法可以获取bookList的长度
System.out.println("一共有" + bookList.getLength() + "本书");
//遍历每一个book节点
for (int i = 0; i < bookList.getLength(); i++) {
System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容=================");
//通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始
Node book = bookList.item(i);
//获取book节点的所有属性集合
NamedNodeMap attrs = book.getAttributes();
System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性");
//遍历book的属性
for (int j = 0; j < attrs.getLength(); j++) {
//通过item(index)方法获取book节点的某一个属性
Node attr = attrs.item(j);
//获取属性名
System.out.print("属性名:" + attr.getNodeName());
//获取属性值
System.out.println("--属性值" + attr.getNodeValue());
}
//解析book节点的子节点
NodeList childNodes = book.getChildNodes();
//遍历childNodes获取每个节点的节点名和节点值
System.out.println("第" + (i+1) + "本书共有" +
childNodes.getLength() + "个子节点");
for (int k = 0; k < childNodes.getLength(); k++) {
//区分出text类型的node以及element类型的node
if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
//获取了element类型节点的节点名
System.out.print("第" + (k + 1) + "个节点的节点名:"
+ childNodes.item(k).getNodeName());
//获取了element类型节点的节点值
System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue());
//System.out.println("--节点值是:" + childNodes.item(k).getTextContent());
}
}
System.out.println("======================结束遍历第" + (i + 1) + "本书的内容=================");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| CodeCoderCoding/Java-Demo | src/HOther/xmlDemo.java | 808 | //获取所有book节点的集合 | line_comment | zh-cn | package HOther;
import jdk.internal.org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
public class xmlDemo {
public static void main(String[] args) {
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder的对象
try {
//创建DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下
Document document = db.parse("./src/HOther/book.xml");
//获取 <SUF>
NodeList bookList = document.getElementsByTagName("book");
//通过nodelist的getLength()方法可以获取bookList的长度
System.out.println("一共有" + bookList.getLength() + "本书");
//遍历每一个book节点
for (int i = 0; i < bookList.getLength(); i++) {
System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容=================");
//通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始
Node book = bookList.item(i);
//获取book节点的所有属性集合
NamedNodeMap attrs = book.getAttributes();
System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性");
//遍历book的属性
for (int j = 0; j < attrs.getLength(); j++) {
//通过item(index)方法获取book节点的某一个属性
Node attr = attrs.item(j);
//获取属性名
System.out.print("属性名:" + attr.getNodeName());
//获取属性值
System.out.println("--属性值" + attr.getNodeValue());
}
//解析book节点的子节点
NodeList childNodes = book.getChildNodes();
//遍历childNodes获取每个节点的节点名和节点值
System.out.println("第" + (i+1) + "本书共有" +
childNodes.getLength() + "个子节点");
for (int k = 0; k < childNodes.getLength(); k++) {
//区分出text类型的node以及element类型的node
if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
//获取了element类型节点的节点名
System.out.print("第" + (k + 1) + "个节点的节点名:"
+ childNodes.item(k).getNodeName());
//获取了element类型节点的节点值
System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue());
//System.out.println("--节点值是:" + childNodes.item(k).getTextContent());
}
}
System.out.println("======================结束遍历第" + (i + 1) + "本书的内容=================");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1 | 15 | 1 |
55793_6 | package com.dcl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import mediautil.gen.directio.SplitInputStream;
import mediautil.image.ImageResources;
import mediautil.image.jpeg.AbstractImageInfo;
import mediautil.image.jpeg.Entry;
import mediautil.image.jpeg.Exif;
import mediautil.image.jpeg.LLJTran;
import mediautil.image.jpeg.LLJTranException;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifDirectory;
public class MainExif {
/**
* 写入图片的exif信息
*
* @param args
* @see [类、类#方法、类#成员]
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
File oldFile = new File("C://Users//DELL//Desktop//1.jpeg");
File newFile = new File("C://Users//DELL//Desktop//2.jpeg");
try {
// 源图片exif信息读取
Metadata metadata = JpegMetadataReader.readMetadata(oldFile);
Directory directory = metadata.getDirectory(ExifDirectory.class);// 这里要稍微注意下
Iterator<Tag> tags = directory.getTagIterator();
while (tags.hasNext()) {
Tag tag = (Tag) tags.next();
System.out.println("old" + tag);
}
// 新图片exif信息读取
metadata = JpegMetadataReader.readMetadata(newFile);
directory = metadata.getDirectory(ExifDirectory.class);// 这里要稍微注意下
tags = directory.getTagIterator();
while (tags.hasNext()) {
Tag tag = (Tag) tags.next();
System.out.println("new" + tag);
}
// 从旧文件中获取Thumbnail信息,长度和偏移量
InputStream inOld = new BufferedInputStream(new FileInputStream(
"C://Users//DELL//Desktop//1.jpeg"));
SplitInputStream sipOld = new SplitInputStream(inOld);
InputStream subIpOld = sipOld.createSubStream();
LLJTran lljOld = new LLJTran(subIpOld);
lljOld.initRead(LLJTran.READ_HEADER, true, true);
sipOld.attachSubReader(lljOld, subIpOld);
sipOld.wrapup();
inOld.close();
AbstractImageInfo imageInfoOld = lljOld.getImageInfo();
Exif exifOld = (Exif) imageInfoOld;
byte[] markerDataOld = Exif.getMarkerData();
int thumbnailLengthOld = imageInfoOld.getThumbnailLength();
int offsetOld = imageInfoOld.getThumbnailOffset();// 旧文件的偏移量
String thumbnailExtensionOld = imageInfoOld.getThumbnailExtension();// 旧文件的扩展名
InputStream thumbnailStreamOld = lljOld.getThumbnailAsStream();
byte[] thumbOld = new byte[thumbnailLengthOld];
thumbnailStreamOld.read(thumbOld);
thumbnailStreamOld.close();
sipOld.close();
// 目标文件exif信息修改
InputStream fip = new BufferedInputStream(new FileInputStream(
"c:/new.jpg"));
SplitInputStream sip = new SplitInputStream(fip);
InputStream subIp = sip.createSubStream();
LLJTran llj = new LLJTran(subIp);
llj.initRead(LLJTran.READ_HEADER, true, true);
sip.attachSubReader(llj, subIp);
sip.wrapup();
fip.close();
// Check llj for errors
String msg = llj.getErrorMsg();
if (msg != null) {
System.out.println("Error in LLJTran While Loading Image: "
+ msg);
Exception e = llj.getException();
if (e != null) {
System.out.println("Got an Exception, throwing it..");
throw e;
}
System.exit(1);
}
AbstractImageInfo imageInfo = llj.getImageInfo();
String string = imageInfo.getThumbnailExtension();
System.out.println(string);
if (imageInfo.getThumbnailLength() > 0) {
System.out.println("Image already has a Thumbnail. Exitting..");
System.exit(1);
}
if (!(imageInfo instanceof Exif)) {
System.out.println("Adding a Dummy Exif Header");
llj.addAppx(markerDataOld, 0, markerDataOld.length, true);
imageInfo = llj.getImageInfo(); // This would have changed
Exif exif = (Exif) imageInfo;
// Changed Date/Time and dimensions in Dummy Exif
Entry entry = exif.getTagValue(Exif.DATETIME, true);
if (entry != null)
entry.setValue(0, "1998:08:18 11:15:00");
entry = exif.getTagValue(Exif.DATETIMEORIGINAL, true);
if (entry != null)
entry.setValue(0, "1998:08:18 11:15:00");
entry = exif.getTagValue(Exif.DATETIMEDIGITIZED, true);
if (entry != null)
entry.setValue(0, "1998:08:18 11:15:00");
int imageWidth = llj.getWidth();
int imageHeight = llj.getHeight();
if (imageWidth > 0 && imageHeight > 0) {
entry = exif.getTagValue(Exif.EXIFIMAGEWIDTH, true);
if (entry != null)
entry.setValue(0, new Integer(imageWidth));
entry = exif.getTagValue(Exif.EXIFIMAGELENGTH, true);
if (entry != null)
entry.setValue(0, new Integer(imageHeight));
}
}
if (llj.setThumbnail(thumbOld, 294, thumbOld.length,
ImageResources.EXT_JPG))
System.out.println("Successfully Set New Thumbnail");
else
System.out.println("Error Setting New Thumbnail");
fip = new BufferedInputStream(new FileInputStream("C://Users//DELL//Desktop//1.jpeg"));
OutputStream out = new BufferedOutputStream(new FileOutputStream(
"C://Users//DELL//Desktop//2.jpeg"));
// Replace the new Exif Header in llj while copying the image from
// fip
// to out
llj.xferInfo(fip, out, LLJTran.REPLACE, LLJTran.REPLACE);
fip.close();
out.close();
llj.freeMemory();
lljOld.freeMemory();
} catch (JpegProcessingException e) {
e.printStackTrace();
} catch (LLJTranException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} | CodeFromBicycleWarrior/PhotoEXIF | src/com/dcl/MainExif.java | 1,831 | // 这里要稍微注意下 | line_comment | zh-cn | package com.dcl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import mediautil.gen.directio.SplitInputStream;
import mediautil.image.ImageResources;
import mediautil.image.jpeg.AbstractImageInfo;
import mediautil.image.jpeg.Entry;
import mediautil.image.jpeg.Exif;
import mediautil.image.jpeg.LLJTran;
import mediautil.image.jpeg.LLJTranException;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifDirectory;
public class MainExif {
/**
* 写入图片的exif信息
*
* @param args
* @see [类、类#方法、类#成员]
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
File oldFile = new File("C://Users//DELL//Desktop//1.jpeg");
File newFile = new File("C://Users//DELL//Desktop//2.jpeg");
try {
// 源图片exif信息读取
Metadata metadata = JpegMetadataReader.readMetadata(oldFile);
Directory directory = metadata.getDirectory(ExifDirectory.class);// 这里要稍微注意下
Iterator<Tag> tags = directory.getTagIterator();
while (tags.hasNext()) {
Tag tag = (Tag) tags.next();
System.out.println("old" + tag);
}
// 新图片exif信息读取
metadata = JpegMetadataReader.readMetadata(newFile);
directory = metadata.getDirectory(ExifDirectory.class);// 这里 <SUF>
tags = directory.getTagIterator();
while (tags.hasNext()) {
Tag tag = (Tag) tags.next();
System.out.println("new" + tag);
}
// 从旧文件中获取Thumbnail信息,长度和偏移量
InputStream inOld = new BufferedInputStream(new FileInputStream(
"C://Users//DELL//Desktop//1.jpeg"));
SplitInputStream sipOld = new SplitInputStream(inOld);
InputStream subIpOld = sipOld.createSubStream();
LLJTran lljOld = new LLJTran(subIpOld);
lljOld.initRead(LLJTran.READ_HEADER, true, true);
sipOld.attachSubReader(lljOld, subIpOld);
sipOld.wrapup();
inOld.close();
AbstractImageInfo imageInfoOld = lljOld.getImageInfo();
Exif exifOld = (Exif) imageInfoOld;
byte[] markerDataOld = Exif.getMarkerData();
int thumbnailLengthOld = imageInfoOld.getThumbnailLength();
int offsetOld = imageInfoOld.getThumbnailOffset();// 旧文件的偏移量
String thumbnailExtensionOld = imageInfoOld.getThumbnailExtension();// 旧文件的扩展名
InputStream thumbnailStreamOld = lljOld.getThumbnailAsStream();
byte[] thumbOld = new byte[thumbnailLengthOld];
thumbnailStreamOld.read(thumbOld);
thumbnailStreamOld.close();
sipOld.close();
// 目标文件exif信息修改
InputStream fip = new BufferedInputStream(new FileInputStream(
"c:/new.jpg"));
SplitInputStream sip = new SplitInputStream(fip);
InputStream subIp = sip.createSubStream();
LLJTran llj = new LLJTran(subIp);
llj.initRead(LLJTran.READ_HEADER, true, true);
sip.attachSubReader(llj, subIp);
sip.wrapup();
fip.close();
// Check llj for errors
String msg = llj.getErrorMsg();
if (msg != null) {
System.out.println("Error in LLJTran While Loading Image: "
+ msg);
Exception e = llj.getException();
if (e != null) {
System.out.println("Got an Exception, throwing it..");
throw e;
}
System.exit(1);
}
AbstractImageInfo imageInfo = llj.getImageInfo();
String string = imageInfo.getThumbnailExtension();
System.out.println(string);
if (imageInfo.getThumbnailLength() > 0) {
System.out.println("Image already has a Thumbnail. Exitting..");
System.exit(1);
}
if (!(imageInfo instanceof Exif)) {
System.out.println("Adding a Dummy Exif Header");
llj.addAppx(markerDataOld, 0, markerDataOld.length, true);
imageInfo = llj.getImageInfo(); // This would have changed
Exif exif = (Exif) imageInfo;
// Changed Date/Time and dimensions in Dummy Exif
Entry entry = exif.getTagValue(Exif.DATETIME, true);
if (entry != null)
entry.setValue(0, "1998:08:18 11:15:00");
entry = exif.getTagValue(Exif.DATETIMEORIGINAL, true);
if (entry != null)
entry.setValue(0, "1998:08:18 11:15:00");
entry = exif.getTagValue(Exif.DATETIMEDIGITIZED, true);
if (entry != null)
entry.setValue(0, "1998:08:18 11:15:00");
int imageWidth = llj.getWidth();
int imageHeight = llj.getHeight();
if (imageWidth > 0 && imageHeight > 0) {
entry = exif.getTagValue(Exif.EXIFIMAGEWIDTH, true);
if (entry != null)
entry.setValue(0, new Integer(imageWidth));
entry = exif.getTagValue(Exif.EXIFIMAGELENGTH, true);
if (entry != null)
entry.setValue(0, new Integer(imageHeight));
}
}
if (llj.setThumbnail(thumbOld, 294, thumbOld.length,
ImageResources.EXT_JPG))
System.out.println("Successfully Set New Thumbnail");
else
System.out.println("Error Setting New Thumbnail");
fip = new BufferedInputStream(new FileInputStream("C://Users//DELL//Desktop//1.jpeg"));
OutputStream out = new BufferedOutputStream(new FileOutputStream(
"C://Users//DELL//Desktop//2.jpeg"));
// Replace the new Exif Header in llj while copying the image from
// fip
// to out
llj.xferInfo(fip, out, LLJTran.REPLACE, LLJTran.REPLACE);
fip.close();
out.close();
llj.freeMemory();
lljOld.freeMemory();
} catch (JpegProcessingException e) {
e.printStackTrace();
} catch (LLJTranException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 0 | 11 | 0 |
21911_3 | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
/**
* @author Administrator
*/
public class Controller {
private Stage primaryStage;
@FXML
private Button startServer;
@FXML
private TextField localPath;
@FXML
private Button selectFilePath;
@FXML
private TextField port;
@FXML
private TextArea dataView;
@FXML
private ProgressBar progress;
@FXML
private Label proValue;
@FXML
private ChoiceBox bufSizeChoice;
@FXML
private Button endServer;
@FXML
private Button cleanTextArea;
private String bufStr = "1024*5";
private long bufSize;
SocketThread socketThread;
@FXML
public void cleanTextArea() {
dataView.clear();
}
@FXML
public void startServe(ActionEvent actionEvent) throws Exception {
if (!valid()) {
return;
}
init();
socketThread = new SocketThread();
socketThread.start();
endServer.setDisable(false);
startServer.setDisable(true);
new Thread(new DataViewTask(dataView, "服务启动成功。。。")).start();
LogService.logInfo("服务启动成功。。。");
}
@FXML
public void endServe(ActionEvent actionEvent) throws Exception {
if (socketThread.isAlive()) {
try {
socketThread.closeServer();
} catch (Exception e) {
LogService.logError(e.getLocalizedMessage());
}
socketThread.interrupt();
}
LogService.logInfo("服务停止。。。");
new Thread(new DataViewTask(dataView, "服务停止...")).start();
endServer.setDisable(true);
port.setEditable(true);
selectFilePath.setDisable(false);
bufSizeChoice.setDisable(false);
startServer.setDisable(false);
}
@FXML
public void selectFilePath(ActionEvent actionEvent) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File file = directoryChooser.showDialog(primaryStage);
String path = file.getPath();
localPath.setText(path);
}
@FXML
public void choiceBoxBuf() {
bufStr = (String) bufSizeChoice.getSelectionModel().getSelectedItem();
}
private void init() {
switch (bufStr) {
case "1024*10":
bufSize = 1024 * 10;
break;
case "1024*100":
bufSize = 1024 * 100;
break;
default:
bufSize = 1024 * 5;
}
System.out.println(bufSize);
port.setEditable(false);
selectFilePath.setDisable(true);
bufSizeChoice.setDisable(true);
}
private boolean valid() {
String path = localPath.getText();
String portStr = port.getText();
if (portStr.length() == 0) {
LogService.logError("端口为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("端口为空");
alert.setContentText("port is null");
alert.showAndWait();
return false;
}
if (path.length() == 0) {
LogService.logError("保存路径为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("保存路径为空");
alert.setContentText("savePath is null");
alert.showAndWait();
return false;
}
return true;
}
/**
* 服务端
*
* @throws Exception
*/
class SocketThread extends Thread {
ServerSocket serverSocket;
boolean isClose = false;
int serverPort = Integer.valueOf(port.getText());
public void closeServer() throws IOException {
isClose = true;
new Socket("localhost",serverPort);
// serverSocket.close();
}
@Override
public void run() {
super.run();
try {
serverSocket = new ServerSocket(serverPort);
} catch (Exception e) {
LogService.logError("启动异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "启动异常", "start error" + e.getMessage())).start();
return;
}
while (!isClose) {
try {
Socket socket = serverSocket.accept();
if (isClose){
socket.close();
serverSocket.close();
break;
}
int bufferSize = 1024 * 1000;
byte[] buf = new byte[bufferSize];
//传输完成的数据长度
long donelen = 0;
//接入地址
new Thread(new DataViewTask(dataView, socket.getInetAddress().getHostAddress() + "---已连接")).start();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String filePath = localPath.getText() + File.separator;
String remoteFile = dis.readUTF();
String filePathTo = filePath + remoteFile;
File file = new File(filePathTo);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//文件长度
Long fileLen = dis.readLong();
new Thread(new DataViewTask(dataView, "开始接收文件---" + file.getName())).start();
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
int read = 0;
while (true) {
if (dis != null && socket.isConnected() && !socket.isClosed()) {
read = dis.read(buf);
}
if (read == -1) {
break;
}
donelen += read;
DecimalFormat df = new DecimalFormat("#.00");
String pro = df.format((double) donelen / fileLen);
new Thread(new ProgressTask(progress, Double.valueOf(pro))).start();
dos.write(buf, 0, read);
}
dos.flush();
if (donelen == fileLen) {
new Thread(new DataViewTask(dataView, file.getName() + "---接收完成" + System.lineSeparator())).start();
LogService.logInfo(file.getName() + "---接收完成");
} else {
LogService.logError("来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。");
new Thread(new DataViewTask(dataView, "来自" + socket.getInetAddress().getHostName() +
"的" + file.getName() + "---接收不完整已删除。")).start();
file.delete();
}
dis.close();
dos.close();
} catch (Exception e) {
e.printStackTrace();
LogService.logError("接收异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "接收异常", "Receive error" + e.getMessage())).start();
}
}
}
}
}
| CodeIsRunning/SocketTransServer | src/sample/Controller.java | 1,665 | //传输完成的数据长度 | line_comment | zh-cn | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
/**
* @author Administrator
*/
public class Controller {
private Stage primaryStage;
@FXML
private Button startServer;
@FXML
private TextField localPath;
@FXML
private Button selectFilePath;
@FXML
private TextField port;
@FXML
private TextArea dataView;
@FXML
private ProgressBar progress;
@FXML
private Label proValue;
@FXML
private ChoiceBox bufSizeChoice;
@FXML
private Button endServer;
@FXML
private Button cleanTextArea;
private String bufStr = "1024*5";
private long bufSize;
SocketThread socketThread;
@FXML
public void cleanTextArea() {
dataView.clear();
}
@FXML
public void startServe(ActionEvent actionEvent) throws Exception {
if (!valid()) {
return;
}
init();
socketThread = new SocketThread();
socketThread.start();
endServer.setDisable(false);
startServer.setDisable(true);
new Thread(new DataViewTask(dataView, "服务启动成功。。。")).start();
LogService.logInfo("服务启动成功。。。");
}
@FXML
public void endServe(ActionEvent actionEvent) throws Exception {
if (socketThread.isAlive()) {
try {
socketThread.closeServer();
} catch (Exception e) {
LogService.logError(e.getLocalizedMessage());
}
socketThread.interrupt();
}
LogService.logInfo("服务停止。。。");
new Thread(new DataViewTask(dataView, "服务停止...")).start();
endServer.setDisable(true);
port.setEditable(true);
selectFilePath.setDisable(false);
bufSizeChoice.setDisable(false);
startServer.setDisable(false);
}
@FXML
public void selectFilePath(ActionEvent actionEvent) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File file = directoryChooser.showDialog(primaryStage);
String path = file.getPath();
localPath.setText(path);
}
@FXML
public void choiceBoxBuf() {
bufStr = (String) bufSizeChoice.getSelectionModel().getSelectedItem();
}
private void init() {
switch (bufStr) {
case "1024*10":
bufSize = 1024 * 10;
break;
case "1024*100":
bufSize = 1024 * 100;
break;
default:
bufSize = 1024 * 5;
}
System.out.println(bufSize);
port.setEditable(false);
selectFilePath.setDisable(true);
bufSizeChoice.setDisable(true);
}
private boolean valid() {
String path = localPath.getText();
String portStr = port.getText();
if (portStr.length() == 0) {
LogService.logError("端口为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("端口为空");
alert.setContentText("port is null");
alert.showAndWait();
return false;
}
if (path.length() == 0) {
LogService.logError("保存路径为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("保存路径为空");
alert.setContentText("savePath is null");
alert.showAndWait();
return false;
}
return true;
}
/**
* 服务端
*
* @throws Exception
*/
class SocketThread extends Thread {
ServerSocket serverSocket;
boolean isClose = false;
int serverPort = Integer.valueOf(port.getText());
public void closeServer() throws IOException {
isClose = true;
new Socket("localhost",serverPort);
// serverSocket.close();
}
@Override
public void run() {
super.run();
try {
serverSocket = new ServerSocket(serverPort);
} catch (Exception e) {
LogService.logError("启动异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "启动异常", "start error" + e.getMessage())).start();
return;
}
while (!isClose) {
try {
Socket socket = serverSocket.accept();
if (isClose){
socket.close();
serverSocket.close();
break;
}
int bufferSize = 1024 * 1000;
byte[] buf = new byte[bufferSize];
//传输 <SUF>
long donelen = 0;
//接入地址
new Thread(new DataViewTask(dataView, socket.getInetAddress().getHostAddress() + "---已连接")).start();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String filePath = localPath.getText() + File.separator;
String remoteFile = dis.readUTF();
String filePathTo = filePath + remoteFile;
File file = new File(filePathTo);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//文件长度
Long fileLen = dis.readLong();
new Thread(new DataViewTask(dataView, "开始接收文件---" + file.getName())).start();
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
int read = 0;
while (true) {
if (dis != null && socket.isConnected() && !socket.isClosed()) {
read = dis.read(buf);
}
if (read == -1) {
break;
}
donelen += read;
DecimalFormat df = new DecimalFormat("#.00");
String pro = df.format((double) donelen / fileLen);
new Thread(new ProgressTask(progress, Double.valueOf(pro))).start();
dos.write(buf, 0, read);
}
dos.flush();
if (donelen == fileLen) {
new Thread(new DataViewTask(dataView, file.getName() + "---接收完成" + System.lineSeparator())).start();
LogService.logInfo(file.getName() + "---接收完成");
} else {
LogService.logError("来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。");
new Thread(new DataViewTask(dataView, "来自" + socket.getInetAddress().getHostName() +
"的" + file.getName() + "---接收不完整已删除。")).start();
file.delete();
}
dis.close();
dos.close();
} catch (Exception e) {
e.printStackTrace();
LogService.logError("接收异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "接收异常", "Receive error" + e.getMessage())).start();
}
}
}
}
}
| 1 | 11 | 1 |
56326_10 | import java.util.ArrayList;
/**
* @Author: zzStar
* @Date: 11-29-2020 10:50
* <p>
* 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。
* <p>
* 二叉树:和链表一样,动态数据结构。
* 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。
* 2)、没有孩子的节点称为叶子节点。
* 3)、每一个孩子节点最多只能有一个父亲节点。
* 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。
* <p>
* 注意:一个节点也是二叉树、空也是二叉树。
* <p>
* 二叉树的分类:
* 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。
* <p>
* <p>
* 二分搜索树:
* 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。
* 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。
* 3)、存储的元素必须有可比较性。
* 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义:
* 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。
* <p>
* 什么是遍历操作?
* 1)、遍历就是把所有的节点都访问一遍。
* 2)、访问的原因和业务相关。
* 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。
* <p>
* 如何对二叉树进行遍历?
* 对于遍历操作,两颗子树都要顾及。
* <p>
* 前序遍历:最自然和常用的遍历方式。规律:根左右
* 中序遍历:规律:左根右
* 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。
* <p>
* 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发,
* 前序遍历:当一个节点被访问第一次就记录它。
* 中序遍历:当一个节点被访问第二次的时候记录它。
* 后序遍历:当一个节点被访问第三次的时候才记录它。
* <p>
* 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。
* 对于二叉搜索树的非递归实现一般有两种写法:
* 1)、经典教科书写法。
* 2)、完全模拟系统调用栈的写法。
* <p>
* 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。
* 广度优先遍历的意义:
* 1)、在于快速地查询要搜索的元素。
* 2)、更快地找到问题的解。
* 3)、常用于算法设计中——无权图最短路径。
* 4)、联想对比图的深度优先遍历与广度优先遍历。
* <p>
* 从二分搜索树中删除最小值与最大值:
* 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。
* <p>
* 删除二分搜索树种的任意元素:
* 1)、删除只有左孩子的节点。
* 2)、删除只有右孩子的节点。
* 3)、删除具有左右孩子的节点:
* 1、找到 s = min(d->right)
* s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。
* s->right = delMin(d->right)
* s->left = d->left
* 删除 d,s 是新的子树的根。
* 2、找到 p = max(d->left)
* p 是 d 的前驱(predecessor)节点。
* <p>
* 如何高效实现 rank(E 是排名第几的元素)?
* 如何高效实现 select(查找排名第10的元素)?
* 最好的方式是实现一个维护 size 的二分搜索树:
* 给 Node 节点添加新的成员变量 size。
* 维护 depth 的二分搜索树。
* 维护 count 支持重复元素的二分搜索树。
*/
public class BSTImpl<K extends Comparable<K>, V> {
private class Node {
public K key;
public V value;
public Node left, right;
public Node(K key, V value) {
this.key = key;
this.value = value;
left = null;
right = null;
}
}
private Node root;
private int size;
public BSTImpl() {
root = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
// 向二分搜索树中添加新的元素(key, value)
public void add(K key, V value) {
root = add(root, key, value);
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value) {
if (node == null) {
size++;
return new Node(key, value);
}
if (key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if (key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
return node;
}
// 返回以node为根节点的二分搜索树中,key所在的节点
private Node getNode(Node node, K key) {
if (node == null)
return null;
if (key.equals(node.key))
return node;
else if (key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
public boolean contains(K key) {
return getNode(root, key) != null;
}
public V get(K key) {
Node node = getNode(root, key);
return node == null ? null : node.value;
}
public void set(K key, V newValue) {
Node node = getNode(root, key);
if (node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node) {
if (node.left == null)
return node;
return minimum(node.left);
}
// 删除掉以node为根的二分搜索树中的最小节点
// 返回删除节点后新的二分搜索树的根
private Node removeMin(Node node) {
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
// 从二分搜索树中删除键为key的节点
public V remove(K key) {
Node node = getNode(root, key);
if (node != null) {
root = remove(root, key);
return node.value;
}
return null;
}
private Node remove(Node node, K key) {
if (node == null)
return null;
if (key.compareTo(node.key) < 0) {
node.left = remove(node.left, key);
return node;
} else if (key.compareTo(node.key) > 0) {
node.right = remove(node.right, key);
return node;
} else { // key.compareTo(node.key) == 0
// 待删除节点左子树为空的情况
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
// 待删除节点右子树为空的情况
if (node.right == null) {
Node leftNode = node.left;
node.left = null;
size--;
return leftNode;
}
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
BSTImpl<String, Integer> map = new BSTImpl<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
}
System.out.println();
}
}
| CodePrometheus/Data-Structures-and-Algorithms | Tree/BSTImpl.java | 2,488 | // 从二分搜索树中删除键为key的节点 | line_comment | zh-cn | import java.util.ArrayList;
/**
* @Author: zzStar
* @Date: 11-29-2020 10:50
* <p>
* 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。
* <p>
* 二叉树:和链表一样,动态数据结构。
* 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。
* 2)、没有孩子的节点称为叶子节点。
* 3)、每一个孩子节点最多只能有一个父亲节点。
* 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。
* <p>
* 注意:一个节点也是二叉树、空也是二叉树。
* <p>
* 二叉树的分类:
* 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。
* <p>
* <p>
* 二分搜索树:
* 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。
* 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。
* 3)、存储的元素必须有可比较性。
* 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义:
* 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。
* <p>
* 什么是遍历操作?
* 1)、遍历就是把所有的节点都访问一遍。
* 2)、访问的原因和业务相关。
* 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。
* <p>
* 如何对二叉树进行遍历?
* 对于遍历操作,两颗子树都要顾及。
* <p>
* 前序遍历:最自然和常用的遍历方式。规律:根左右
* 中序遍历:规律:左根右
* 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。
* <p>
* 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发,
* 前序遍历:当一个节点被访问第一次就记录它。
* 中序遍历:当一个节点被访问第二次的时候记录它。
* 后序遍历:当一个节点被访问第三次的时候才记录它。
* <p>
* 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。
* 对于二叉搜索树的非递归实现一般有两种写法:
* 1)、经典教科书写法。
* 2)、完全模拟系统调用栈的写法。
* <p>
* 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。
* 广度优先遍历的意义:
* 1)、在于快速地查询要搜索的元素。
* 2)、更快地找到问题的解。
* 3)、常用于算法设计中——无权图最短路径。
* 4)、联想对比图的深度优先遍历与广度优先遍历。
* <p>
* 从二分搜索树中删除最小值与最大值:
* 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。
* <p>
* 删除二分搜索树种的任意元素:
* 1)、删除只有左孩子的节点。
* 2)、删除只有右孩子的节点。
* 3)、删除具有左右孩子的节点:
* 1、找到 s = min(d->right)
* s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。
* s->right = delMin(d->right)
* s->left = d->left
* 删除 d,s 是新的子树的根。
* 2、找到 p = max(d->left)
* p 是 d 的前驱(predecessor)节点。
* <p>
* 如何高效实现 rank(E 是排名第几的元素)?
* 如何高效实现 select(查找排名第10的元素)?
* 最好的方式是实现一个维护 size 的二分搜索树:
* 给 Node 节点添加新的成员变量 size。
* 维护 depth 的二分搜索树。
* 维护 count 支持重复元素的二分搜索树。
*/
public class BSTImpl<K extends Comparable<K>, V> {
private class Node {
public K key;
public V value;
public Node left, right;
public Node(K key, V value) {
this.key = key;
this.value = value;
left = null;
right = null;
}
}
private Node root;
private int size;
public BSTImpl() {
root = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
// 向二分搜索树中添加新的元素(key, value)
public void add(K key, V value) {
root = add(root, key, value);
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value) {
if (node == null) {
size++;
return new Node(key, value);
}
if (key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if (key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
return node;
}
// 返回以node为根节点的二分搜索树中,key所在的节点
private Node getNode(Node node, K key) {
if (node == null)
return null;
if (key.equals(node.key))
return node;
else if (key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
public boolean contains(K key) {
return getNode(root, key) != null;
}
public V get(K key) {
Node node = getNode(root, key);
return node == null ? null : node.value;
}
public void set(K key, V newValue) {
Node node = getNode(root, key);
if (node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node) {
if (node.left == null)
return node;
return minimum(node.left);
}
// 删除掉以node为根的二分搜索树中的最小节点
// 返回删除节点后新的二分搜索树的根
private Node removeMin(Node node) {
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
// 从二 <SUF>
public V remove(K key) {
Node node = getNode(root, key);
if (node != null) {
root = remove(root, key);
return node.value;
}
return null;
}
private Node remove(Node node, K key) {
if (node == null)
return null;
if (key.compareTo(node.key) < 0) {
node.left = remove(node.left, key);
return node;
} else if (key.compareTo(node.key) > 0) {
node.right = remove(node.right, key);
return node;
} else { // key.compareTo(node.key) == 0
// 待删除节点左子树为空的情况
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
// 待删除节点右子树为空的情况
if (node.right == null) {
Node leftNode = node.left;
node.left = null;
size--;
return leftNode;
}
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
BSTImpl<String, Integer> map = new BSTImpl<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
}
System.out.println();
}
}
| 1 | 20 | 1 |
40913_4 | //https://blog.csdn.net/cslbupt/article/details/53965440
动态规划过程是:每次决策依赖于当前状态,又随即引起状态的转移。一个决策序列就是在变化的状态中产生出来的,所以,这种多阶段最优化决策解决问题的过程就称为动态规划。
https://juejin.im/post/5a29d52cf265da43333e4da7
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int length1 = s1.length();
int length2 = s2.length();
int length3 = s3.length();
if (length1 + length2 != length3){
return false;//这种小判断可以大大提高程序速度
}
//声明一个二维数组dp[][];其中dp[i][j]表示s1在第个位置,s2在第j个位置,s3在遍历第i+j个位置。dp[0][0]为s1和s2都为空
boolean[][] dp = new boolean[length1 + 1][length2 + 1];
//当s1不是empty,s2为empty时。只需比较当前遍历的位置s1的字串和s3的字串是否相等
for (int i = 0; i <= length1; i++){
dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i)) ? true : false;
}
//当s2不是empty,s1是empty时
for (int j = 0; j <= length2; j++){//一个一个比较是否完全一致
dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j)) ? true : false;
}
//当s1和s2都不是空时。有两种情况,一种是从(i-1,j)到达(i,j)位置,如果(i-1,j)已经是交叉的了,只需比较s1的第i个位置的元素与s3的第i+j个位置的元素是否相等;另一种情况同理。
for (int i = 1; i <= length1; i++){
for (int j = 1; j <= length2; j++){
dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) ||
(dp[i][j-1] && s2.charAt(j - 1) == s3.charAt(i + j -1));
}
}
return dp[s1.length()][s2.length()];
}
}
| CodeStudyTogether/StudyAlgorithm | LeetCode/0097.java | 652 | //当s1不是empty,s2为empty时。只需比较当前遍历的位置s1的字串和s3的字串是否相等 | line_comment | zh-cn | //https://blog.csdn.net/cslbupt/article/details/53965440
动态规划过程是:每次决策依赖于当前状态,又随即引起状态的转移。一个决策序列就是在变化的状态中产生出来的,所以,这种多阶段最优化决策解决问题的过程就称为动态规划。
https://juejin.im/post/5a29d52cf265da43333e4da7
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int length1 = s1.length();
int length2 = s2.length();
int length3 = s3.length();
if (length1 + length2 != length3){
return false;//这种小判断可以大大提高程序速度
}
//声明一个二维数组dp[][];其中dp[i][j]表示s1在第个位置,s2在第j个位置,s3在遍历第i+j个位置。dp[0][0]为s1和s2都为空
boolean[][] dp = new boolean[length1 + 1][length2 + 1];
//当s <SUF>
for (int i = 0; i <= length1; i++){
dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i)) ? true : false;
}
//当s2不是empty,s1是empty时
for (int j = 0; j <= length2; j++){//一个一个比较是否完全一致
dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j)) ? true : false;
}
//当s1和s2都不是空时。有两种情况,一种是从(i-1,j)到达(i,j)位置,如果(i-1,j)已经是交叉的了,只需比较s1的第i个位置的元素与s3的第i+j个位置的元素是否相等;另一种情况同理。
for (int i = 1; i <= length1; i++){
for (int j = 1; j <= length2; j++){
dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) ||
(dp[i][j-1] && s2.charAt(j - 1) == s3.charAt(i + j -1));
}
}
return dp[s1.length()][s2.length()];
}
}
| 1 | 49 | 1 |
60349_4 | package acwing.basic.chapter5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author : CodeWater
* @create :2022-06-18-16:27
* @Function Description :285.没有上司的舞会
*/
public class _285ADanceWithoutABoss {
public static int N = 6010;
public static int n , idx ;
// 每个人的快乐指数
public static int[] happy = new int[N];
// 邻接表存储树
public static int[] h = new int[N];
public static int[] e = new int[N];
public static int[] ne = new int[N];
//状态方程,f[u][0/1]:所有从以u为根的子树中选择,并且不选/选u这个点的方案
public static int[][] f = new int[N][2];
// 因为题目没有告知根结点,所以还需要再求一下。也就是没有父结点的点
public static boolean[] has_father = new boolean[N];
public static void main( String[] args ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader(System.in ) );
String[] str = br.readLine().split(" ");
n = Integer.parseInt( str[0] );
// 读取初始的快乐指数 read直接读取的是一个字符
for( int i = 1 ; i <= n ; i++ ){
str = br.readLine().split(" ");
happy[i] = Integer.parseInt( str[0] );
}
//初始化头结点
Arrays.fill( h , -1 );
//读入每一条边
for( int i = 0 ; i < n - 1 ; i++ ){
//b是a的父结点
str = br.readLine().split(" ");
int a = Integer.parseInt( str[0] ), b = Integer.parseInt( str[1] );
has_father[a] = true;
add( b , a );//添加a到b的一条边
}
// //求根结点
int root = 1;
while( has_father[root] == true ) root ++;
dfs(root );
System.out.println( Math.max( f[root][0] , f[root][1] ) );
}
public static void add( int a , int b ){
e[idx] = b ; ne[idx] = h[a] ; h[a] = idx++;
}
//递归求解每个状态
public static void dfs( int u ){
//选择u结点
f[u][1] = happy[u];
for( int i = h[u] ; i != -1 ; i = ne[i] ){
//j表示u的每个儿子
int j = e[i];
dfs(j);
f[u][0] += Math.max( f[j][0] , f[j][1] );
f[u][1] += f[j][0];
}
}
}
| CodeWater404/JavaCode | Algorithm/src/acwing/basic/chapter5/_285ADanceWithoutABoss.java | 733 | // 因为题目没有告知根结点,所以还需要再求一下。也就是没有父结点的点 | line_comment | zh-cn | package acwing.basic.chapter5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author : CodeWater
* @create :2022-06-18-16:27
* @Function Description :285.没有上司的舞会
*/
public class _285ADanceWithoutABoss {
public static int N = 6010;
public static int n , idx ;
// 每个人的快乐指数
public static int[] happy = new int[N];
// 邻接表存储树
public static int[] h = new int[N];
public static int[] e = new int[N];
public static int[] ne = new int[N];
//状态方程,f[u][0/1]:所有从以u为根的子树中选择,并且不选/选u这个点的方案
public static int[][] f = new int[N][2];
// 因为 <SUF>
public static boolean[] has_father = new boolean[N];
public static void main( String[] args ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader(System.in ) );
String[] str = br.readLine().split(" ");
n = Integer.parseInt( str[0] );
// 读取初始的快乐指数 read直接读取的是一个字符
for( int i = 1 ; i <= n ; i++ ){
str = br.readLine().split(" ");
happy[i] = Integer.parseInt( str[0] );
}
//初始化头结点
Arrays.fill( h , -1 );
//读入每一条边
for( int i = 0 ; i < n - 1 ; i++ ){
//b是a的父结点
str = br.readLine().split(" ");
int a = Integer.parseInt( str[0] ), b = Integer.parseInt( str[1] );
has_father[a] = true;
add( b , a );//添加a到b的一条边
}
// //求根结点
int root = 1;
while( has_father[root] == true ) root ++;
dfs(root );
System.out.println( Math.max( f[root][0] , f[root][1] ) );
}
public static void add( int a , int b ){
e[idx] = b ; ne[idx] = h[a] ; h[a] = idx++;
}
//递归求解每个状态
public static void dfs( int u ){
//选择u结点
f[u][1] = happy[u];
for( int i = h[u] ; i != -1 ; i = ne[i] ){
//j表示u的每个儿子
int j = e[i];
dfs(j);
f[u][0] += Math.max( f[j][0] , f[j][1] );
f[u][1] += f[j][0];
}
}
}
| 1 | 35 | 1 |
41682_4 | package com.noah.spring.transaction.domain;
import com.noah.spring.transaction.entity.AopEntity;
import com.noah.spring.transaction.service.AopService;
import com.noah.spring.transaction.service.impl.LettuceConfigServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* 描述:
* 测试切面
*
* @author Noah
* @create 2021-11-25 11:50 上午
*/
@Service
public class AopDomain extends AopService {
@Resource
AopEntity aopEntity;
@Resource(name = "lettuceConfigServiceImpl")
LettuceConfigServiceImpl configService;
/**
* aop事务
*/
@Transactional
public void aopTransactional() {
//1、自身服务,主业务完成调用,此时事务已经提交了,耶稣都回滚不了
configService.right(101);
//2、发起远程dubbo调用,但是异常被切面catch了。
//2-1、导致自身主服务,事务回滚失败
//2-2、解决方案1:dubbo远程调用失败了,dubbo不抛出任何异常,自己包裹住,然后返回boolean值给我自身服务
//2-3、解决方案2:在切面回滚事务。
//2-3-1:不可行,因为自身的事务已经提交了。No transaction aspect-managed TransactionStatus in scope
//2-4、解决方案3:自身服务调用完dubbo之后,检查返回结果,再判定本次调用是否成功。
//3、如果加上了重试逻辑??
aopEntity.testAopEntity();
}
/**
* 手动提交事务
*/
public void manualCommit() {
//todo:手动提交事务
//org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction
}
}
| Codeprh/JavaFrame | transaction/spring-transaction/src/main/java/com/noah/spring/transaction/domain/AopDomain.java | 473 | //2-1、导致自身主服务,事务回滚失败 | line_comment | zh-cn | package com.noah.spring.transaction.domain;
import com.noah.spring.transaction.entity.AopEntity;
import com.noah.spring.transaction.service.AopService;
import com.noah.spring.transaction.service.impl.LettuceConfigServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* 描述:
* 测试切面
*
* @author Noah
* @create 2021-11-25 11:50 上午
*/
@Service
public class AopDomain extends AopService {
@Resource
AopEntity aopEntity;
@Resource(name = "lettuceConfigServiceImpl")
LettuceConfigServiceImpl configService;
/**
* aop事务
*/
@Transactional
public void aopTransactional() {
//1、自身服务,主业务完成调用,此时事务已经提交了,耶稣都回滚不了
configService.right(101);
//2、发起远程dubbo调用,但是异常被切面catch了。
//2- <SUF>
//2-2、解决方案1:dubbo远程调用失败了,dubbo不抛出任何异常,自己包裹住,然后返回boolean值给我自身服务
//2-3、解决方案2:在切面回滚事务。
//2-3-1:不可行,因为自身的事务已经提交了。No transaction aspect-managed TransactionStatus in scope
//2-4、解决方案3:自身服务调用完dubbo之后,检查返回结果,再判定本次调用是否成功。
//3、如果加上了重试逻辑??
aopEntity.testAopEntity();
}
/**
* 手动提交事务
*/
public void manualCommit() {
//todo:手动提交事务
//org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction
}
}
| 0 | 20 | 0 |
66489_7 | package com.ming.androidmapbox.symbol;
import androidx.annotation.NonNull;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.ming.androidmapbox.util.LogUtils;
import com.ming.androidmapbox.MapActivity;
import com.ming.androidmapbox.R;
import com.ming.androidmapbox.util.ToastUtil;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GeoActivity extends MapActivity {
@Override
public void onMapLoaded() {
super.onMapLoaded();
LatLng target = mapboxMap.getCameraPosition().target;
double lng = target.getLongitude();
double lat = target.getLatitude();
// 3.1 #在特定地区找到一个名为'Chester'的小镇
//#使用本地坐标添加proximity参数
//#这确保了新泽西州切斯特镇的成果
String url1 = "https://api.mapbox.com/geocoding/v5/mapbox.places/chester.json?proximity=" + lng + "," + lat +"&access_token=your-access-token";
// 3.2 #指定types = country以仅搜索名为Georgia的国家/地区
//#结果将排除美国佐治亚州
String url2 = "https://api.mapbox.com/geocoding/v5/mapbox.places/georgia.json?types=country&access_token=your-access-token";
// 3.3 在华盛顿特区搜索”星巴克“
//#使用边界框将结果限制在区域
String url3 = "https://api.mapbox.com/geocoding/v5/mapbox.places/starbucks.json?bbox=-77.083056,38.908611,-76.997778,38.959167&access_token=your-access-token";
// 3.4使用限制选项将结果限制为2个结果
//#尽管
//”华盛顿“ 有许多可能的匹配#,但此查询只返回2个结果
String url4 = "https://api.mapbox.com/geocoding/v5/mapbox.places/Washington.json?limit=2&access_token=your-access-token";
geoAddress(url1.replace("your-access-token", getString(R.string.mapbox_access_token)));
}
private void geoAddress(String url) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).get().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
ToastUtil.show("testMapQuest:" + e.getMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String json = response.body().string();
LogUtils.d("testMapQuest==>返回结果:onResponse " + json);
ToastUtil.show("testMapQuest json :\n" + json);
}
});
}
}
| CoderDaMing/AndroidMapbox | AndroidMapbox/app/src/main/java/com/ming/androidmapbox/symbol/GeoActivity.java | 780 | // 3.3 在华盛顿特区搜索”星巴克“ | line_comment | zh-cn | package com.ming.androidmapbox.symbol;
import androidx.annotation.NonNull;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.ming.androidmapbox.util.LogUtils;
import com.ming.androidmapbox.MapActivity;
import com.ming.androidmapbox.R;
import com.ming.androidmapbox.util.ToastUtil;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GeoActivity extends MapActivity {
@Override
public void onMapLoaded() {
super.onMapLoaded();
LatLng target = mapboxMap.getCameraPosition().target;
double lng = target.getLongitude();
double lat = target.getLatitude();
// 3.1 #在特定地区找到一个名为'Chester'的小镇
//#使用本地坐标添加proximity参数
//#这确保了新泽西州切斯特镇的成果
String url1 = "https://api.mapbox.com/geocoding/v5/mapbox.places/chester.json?proximity=" + lng + "," + lat +"&access_token=your-access-token";
// 3.2 #指定types = country以仅搜索名为Georgia的国家/地区
//#结果将排除美国佐治亚州
String url2 = "https://api.mapbox.com/geocoding/v5/mapbox.places/georgia.json?types=country&access_token=your-access-token";
// 3. <SUF>
//#使用边界框将结果限制在区域
String url3 = "https://api.mapbox.com/geocoding/v5/mapbox.places/starbucks.json?bbox=-77.083056,38.908611,-76.997778,38.959167&access_token=your-access-token";
// 3.4使用限制选项将结果限制为2个结果
//#尽管
//”华盛顿“ 有许多可能的匹配#,但此查询只返回2个结果
String url4 = "https://api.mapbox.com/geocoding/v5/mapbox.places/Washington.json?limit=2&access_token=your-access-token";
geoAddress(url1.replace("your-access-token", getString(R.string.mapbox_access_token)));
}
private void geoAddress(String url) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).get().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
ToastUtil.show("testMapQuest:" + e.getMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String json = response.body().string();
LogUtils.d("testMapQuest==>返回结果:onResponse " + json);
ToastUtil.show("testMapQuest json :\n" + json);
}
});
}
}
| 0 | 27 | 0 |
37599_39 | package com.coderdream.freeapps.util.bbc;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.coderdream.freeapps.model.SubtitleBaseEntity;
import com.coderdream.freeapps.model.TopicEntity;
import com.coderdream.freeapps.util.other.CdFileUtils;
import com.coderdream.freeapps.util.translator.text.TranslatorTextUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
/**
* @author CoderDream
*/
public class TranslateUtil {
public static void main(String[] args) {
String folderName = "210318";
// TranslateUtil.process(folderName);
// TranslateUtil.mergeScriptContent(folderName);
TranslateUtil.translateEngSrc(folderName);
// String str = "大括号外面的内容(Michael Collins)的内容(Michael Collins) ";
// str = removeEnContent(str);
// System.out.println(str);
//
// List<String> NUMBER_LIST = Arrays.asList("230406", "230413", "230420", "230427");
// TranslateUtil.translateTitle(NUMBER_LIST);
// TranslateUtil.mergeScriptContentWx(folderName);
//translateAllTitle();
// process(folderName);
}
/**
*
* @param str
* @return
*/
@NotNull
private static String removeEnContent(String str) {
do {
int startIndex = str.lastIndexOf("(");
int endIndex = str.lastIndexOf(")");
if (startIndex != -1 && endIndex != -1) {
try {
if (startIndex >= 0 && endIndex > 0) {
str = str.replaceAll(str.substring(startIndex, endIndex + 1), "");
} else {
System.out.println(
"#####x##### ERROR: startIndex is " + startIndex + "; endIndex is " + endIndex + "; str "
+ str);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("### str " + str);
}
}
} while (str.contains("(") && str.contains(")"));
return str;
}
public static List<String> translateTitle(List<String> folderNameList, String fileName) {
// if (fileName == null) {
// fileName = "script_raw";
// }
// 220303_script.txt
// if (fileName.endsWith("_script.txt")) {
// // TODO
// }
// 6 Minute English
// word-for-word transcript
List<String> titleList = new ArrayList<>();
for (String folderName : folderNameList) {
fileName = folderName + "_script"; // TODO 指定
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String title;
int size = stringList.size();
if (CollectionUtil.isNotEmpty(stringList)) {
// titleList.add(stringList.get(0));
titleList.add(getTitleString(stringList));
}
}
String textTitleList = titleList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListTitleCn = TranslatorTextUtil.translatorText(textTitleList);
String[] arr = new String[0];
for (int i = 0; i < stringListTitleCn.size(); i++) {
String temp = stringListTitleCn.get(i);
arr = temp.split("\r\n");
}
List<String> titleCnList = Arrays.asList(arr);
List<String> newList = new ArrayList<>();
String titleTranslate;
for (int i = 0; i < arr.length; i++) {
titleTranslate = folderNameList.get(i).substring(2) + "\t" + titleList.get(i) + "\t" + arr[i];
System.out.println(titleTranslate);
newList.add(titleTranslate);
}
// String srcFileNameCn = BbcConstants.ROOT_FOLDER_NAME + File.separator + "title.txt";
// 写中文翻译文本
// CdFileUtils.writeToFile(srcFileNameCn, newList);
return titleCnList;
}
private static String getTitleString(List<String> stringList) {
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < stringList.size(); i++) {
if (stringList.get(i).contains("6 Minute English")) {
startIndex = i;
}
if (stringList.get(i).contains("word-for-word transcript")) {
endIndex = i;
break;
}
}
StringBuilder result = new StringBuilder();
for (int i = startIndex + 1; i < endIndex; i++) {
result.append(stringList.get(i));
}
return result.toString();
}
/**
* 手工粘贴文本
*
* @param folderNameList
* @param fileName
* @return
*/
public static List<String> translateTitleManual(List<String> folderNameList, String fileName) {
if (fileName == null) {
fileName = "script_raw";
}
List<String> titleList = new ArrayList<>();
for (String folderName : folderNameList) {
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String title;
int size = stringList.size();
for (int i = 0; i < size; i++) {
String tempStr = stringList.get(i);
// System.out.println("tempStr: " + tempStr);
if ("INTERMEDIATE LEVEL".equals(tempStr)) {
title = stringList.get(i + 1);
titleList.add(title);
break;
}
}
}
String textTitleList = titleList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListTitleCn = TranslatorTextUtil.translatorText(textTitleList);
String[] arr = new String[0];
for (int i = 0; i < stringListTitleCn.size(); i++) {
String temp = stringListTitleCn.get(i);
arr = temp.split("\r\n");
}
List<String> titleCnList = Arrays.asList(arr);
List<String> newList = new ArrayList<>();
String titleTranslate;
for (int i = 0; i < arr.length; i++) {
titleTranslate = folderNameList.get(i).substring(2) + "\t" + titleList.get(i) + "\t" + arr[i];
System.out.println(titleTranslate);
newList.add(titleTranslate);
}
String srcFileNameCn = BbcConstants.ROOT_FOLDER_NAME + File.separator + "title.txt";
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameCn, newList);
return titleCnList;
}
/**
* 翻译脚本
*
* @param folderName
*/
public static void process(String folderName) {
String fileName = "script_dialog";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String text = stringList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
System.out.println("text: " + text);
List<String> stringListCn = TranslatorTextUtil.translatorText(text);
List<String> newList = new ArrayList<>();
for (int i = 0; i < stringListCn.size(); i++) {
String temp = stringListCn.get(i);
String[] arr = temp.split("\r\n");
for (int j = 0; j < arr.length; j++) {
upgradeTranslate(folderName, arr, j, stringList);
System.out.println(arr[j]);
newList.add(arr[j]);
// 如果最后一行不是空格,则补一个空白字符串
if (j == arr.length - 1 && StrUtil.isNotEmpty(arr[j])) {
newList.add("");
}
}
}
String srcFileNameCn = CommonUtil.getFullPathFileName(folderName, fileName, "_cn.txt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameCn, newList);
}
/**
* 优化句子
*
* @param folderName
* @param arr
* @param j
*/
private static void upgradeTranslate(String folderName, String[] arr, int j, List<String> subtitleList) {
if ("抢".equals(arr[j])) {
arr[j] = "罗伯";
}
if ("山 姆".equals(arr[j])) {
arr[j] = "山姆";
}
if ("井".equals(arr[j])) {
arr[j] = "嗯";
}
if ("右".equals(arr[j])) {
arr[j] = "是的";
}
if ("右!".equals(arr[j])) {
arr[j] = "好的!";
}
// 医 管 局!
// (Michael Collins) 去掉大括号及大括号内的内容
arr[j] = removeEnContent(arr[j]);
arr[j] = arr[j].replaceAll(" 6 Minute English ", "六分钟英语");
arr[j] = arr[j].replaceAll("医 管 局", "哈哈");
arr[j] = arr[j].replaceAll("乔吉", "乔治");
arr[j] = arr[j].replaceAll("成语", "谚语");
arr[j] = arr[j].replaceAll("Rob", "罗伯");
arr[j] = arr[j].replaceAll("伟大!", "太好了!");
arr[j] = arr[j].replaceAll("右。", "好的。"); // Right应该翻译成好的,而不是右
arr[j] = arr[j].replaceAll("山 姆", "山姆");
arr[j] = arr[j].replaceAll("6分钟", "六分钟");
arr[j] = arr[j].replaceAll(" 6 分钟", "六分钟");
arr[j] = arr[j].replaceAll(";", ";");
arr[j] = arr[j].replaceAll("“拯救大象”(Save the Elephants)", "“拯救大象”");
arr[j] = arr[j].replaceAll("六分钟又到了", "六分钟时间又到了"); // 英国广播公司(BBC)
arr[j] = arr[j].replaceAll("英国广播公司(BBC)", "英国广播公司"); // 英国广播公司(BBC)
arr[j] = arr[j].replaceAll("——", " —— ");// ——
if (-1 != arr[j].lastIndexOf("程序") && -1 != subtitleList.get(j).lastIndexOf("programme")) {
arr[j] = arr[j].replaceAll("程序", "节目");
}
if (-1 != arr[j].lastIndexOf("课程") && -1 != subtitleList.get(j).lastIndexOf("programme")) {
arr[j] = arr[j].replaceAll("课程", "节目");
}
// 维克托
arr[j] = arr[j].replaceAll("Victor;", "维克多");
arr[j] = arr[j].trim();//去掉前后空格
if ("231026".equals(folderName)) {
arr[j] = arr[j].replaceAll("一百个", "一百岁");
}
if ("231109".equals(folderName)) {
if (arr[j].equals("幸运")) {
arr[j] = arr[j].replaceAll("幸运", "幸运的是");
}
}
// 针对230413的AI翻译优化
if ("230413".equals(folderName)) {
arr[j] = arr[j].replaceAll("垃圾场", "情绪低落");
arr[j] = arr[j].replaceAll("垃圾堆", "情绪低落");
arr[j] = arr[j].replaceAll("最尖锐的", "极度");
arr[j] = arr[j].replaceAll(" Covid", "冠状病毒");
arr[j] = arr[j].replaceAll("Covid", "冠状病毒");
arr[j] = arr[j].replaceAll("英国广播公司(BBC)", "BBC");//英国广播公司(BBC)
arr[j] = arr[j].replaceAll("《纪录片》(The Documentary)", "《纪录片》");//《纪录片》(The Documentary)
arr[j] = arr[j].replaceAll("海伦·罗素(Helen Russell)", "海伦·罗素");// 海伦·罗素(Helen Russell)
arr[j] = arr[j].replaceAll("托马斯·迪克森(Thomas Dixon)", "托马斯·迪克森");// 托马斯·迪克森(Thomas Dixon)
}
// 针对230302的AI翻译优化
if ("230302".equals(folderName)) {
arr[j] = arr[j].replaceAll("Rob", "'dunk'");
arr[j] = arr[j].replaceAll("扣篮", "'dunk'");
arr[j] = arr[j].replaceAll("英国广播公司(BBC)", "BBC");//英国广播公司(BBC)
arr[j] = arr[j].replaceAll("迈克尔·罗森(Michael Rosen)", "迈克尔·罗森");
arr[j] = arr[j].replaceAll("朱莉·塞迪维(Julie Sedivy)", "朱莉·塞迪维");
arr[j] = arr[j].replaceAll("计划", "节目");
}
//
// 针对230330的AI翻译优化
if ("230330".equals(folderName)) {
arr[j] = arr[j].replaceAll("历克斯·米尔克(Alex Mielke)", "历克斯·米尔克");
}
}
public static void translateEngSrc(String folderName) {
String fileName = "eng";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".srt");
// readSrcFileContent
List<SubtitleBaseEntity> subtitleBaseEntityList = CdFileUtils.readSrcFileContent(srcFileName);
List<String> subtitleList = subtitleBaseEntityList.stream().map(SubtitleBaseEntity::getSubtitle)
.collect(Collectors.toList());
String text = subtitleList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListCn = TranslatorTextUtil.translatorText(text);
List<String> newList = new ArrayList<>();
List<String> newListEnCn = new ArrayList<>();
List<String> lrcListEnCn = new ArrayList<>();
SubtitleBaseEntity subtitleBaseEntity;
String timeStr;
String lrc;
for (int i = 0; i < stringListCn.size(); i++) {
String temp = stringListCn.get(i);
String[] arr = temp.split("\r\n");
// 检查大小
if (arr.length != subtitleBaseEntityList.size()) {
System.out.println("###");
break;
}
for (int j = 0; j < arr.length; j++) {
// 优化翻译
upgradeTranslate(folderName, arr, j, subtitleList);
System.out.println(arr[j]);
subtitleBaseEntity = subtitleBaseEntityList.get(j);
newList.add(subtitleBaseEntity.getSubIndex() + "");
newList.add(subtitleBaseEntity.getTimeStr());
newList.add(arr[j]);
newList.add("");
newListEnCn.add(subtitleBaseEntity.getSubIndex() + "");
newListEnCn.add(subtitleBaseEntity.getTimeStr());
newListEnCn.add(subtitleList.get(j) + "\r" + arr[j]);
newListEnCn.add("");
timeStr = subtitleBaseEntity.getTimeStr();
timeStr = timeStr.substring(3, 11);
timeStr = timeStr.replaceAll(",", ".");
lrc = "[" + timeStr + "]" + subtitleList.get(j) + "|" + arr[j];
lrcListEnCn.add(lrc);
}
}
String srcFileNameCn = CommonUtil.getFullPathFileName(folderName, "chn", ".srt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameCn, newList);
// // 双语字幕
// String srcFileNameEnCn = CommonUtil.getFullPathFileName(folderName, "audio5", ".srt");
// // 写双语歌词文本
// CdFileUtils.writeToFile(srcFileNameEnCn, newListEnCn);
//
// // 双语歌词
// String lrcFileNameEnCn = CommonUtil.getFullPathFileName(folderName, "audio5", ".lrc");
// // 写双语歌词文本
// CdFileUtils.writeToFile(lrcFileNameEnCn, lrcListEnCn);
}
/**
* 生成对话脚本合集
*
* @param folderName
*/
public static void mergeScriptContent(String folderName) {
String fileName = "script_dialog";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<ScriptEntity> scriptEntityListEn = CdFileUtils.genScriptEntityList(srcFileName);
String srcFileNameCn = CommonUtil.getFullPathFileName(folderName, fileName, "_cn.txt");
List<ScriptEntity> scriptEntityListCn = CdFileUtils.genScriptEntityList(srcFileNameCn);
ScriptEntity scriptEntityEn;
ScriptEntity scriptEntityCn;
String scriptEn;
String scriptCn;
List<String> newList = new ArrayList<>();
if (CollectionUtil.isNotEmpty(scriptEntityListEn) && CollectionUtil.isNotEmpty(scriptEntityListCn)
&& scriptEntityListEn.size() == scriptEntityListCn.size()) {
for (int i = 0; i < scriptEntityListEn.size(); i++) {
scriptEntityEn = scriptEntityListEn.get(i);
scriptEn = scriptEntityEn.getContent();
scriptEn = scriptEn.replaceAll("Hello. This is 6 Minute English from BBC Learning English. ", "");
scriptEntityCn = scriptEntityListCn.get(i);
scriptCn = scriptEntityCn.getContent();
scriptCn = scriptCn.replaceAll("你好。这是来自BBC学习英语的六分钟英语。", "");
newList.add(scriptEntityEn.getTalker() + "(" + scriptEntityCn.getTalker() + ")");
newList.add(scriptEn + "\r\n" + scriptCn);
newList.add("");
}
} else {
if (CollectionUtil.isEmpty(scriptEntityListEn)) {
System.out.println("scriptEntityListEn 为空。");
} else if (CollectionUtil.isEmpty(scriptEntityListCn)) {
System.out.println("scriptEntityListCn 为空。");
} else {
System.out.println(
"两个脚本格式不对,实体大小分别为:" + scriptEntityListEn.size() + "\t:\t"
+ scriptEntityListCn.size()); //
}
}
String srcFileNameMerge = CommonUtil.getFullPathFileName(folderName, folderName, "_中英双语对话脚本.txt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameMerge, newList);
}
/**
* 生成对话脚本合集
*
* @param folderName
*/
public static void mergeScriptContentWx(String folderName) {
String fileName = "script_dialog_wx2";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String text = stringList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListCn = TranslatorTextUtil.translatorText(text);
List<String> newList = new ArrayList<>();
List<String> newListEnCn = new ArrayList<>();
List<String> lrcListEnCn = new ArrayList<>();
SubtitleBaseEntity subtitleBaseEntity;
String timeStr;
String lrc;
for (int i = 0; i < stringListCn.size(); i++) {
String temp = stringListCn.get(i);
String[] arr = temp.split("\r\n");
for (int j = 0; j < arr.length; j++) {
upgradeTranslate(folderName, arr, j, stringList);
System.out.println(arr[j]);
// subtitleBaseEntity = subtitleBaseEntityList.get(j);
// newList.add(subtitleBaseEntity.getSubIndex() + "");
// newList.add(subtitleBaseEntity.getTimeStr());
// newList.add(arr[j]);
// newList.add("");
// newListEnCn.add(subtitleBaseEntity.getSubIndex() + "");
// newListEnCn.add(subtitleBaseEntity.getTimeStr());
newListEnCn.add(stringList.get(j) + "\r" + arr[j]);
newListEnCn.add("");
}
}
String srcFileNameMerge = CommonUtil.getFullPathFileName(folderName, fileName, "_merge.txt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameMerge, newListEnCn);
}
/**
* 生成对话脚本合集
*/
public static void translateAllTitle() {
String fileName = BbcConstants.ROOT_FOLDER_NAME + "all.txt";
List<TopicEntity> topicEntityList = CdFileUtils.genTopicEntityList(fileName);
// List<String> stringList = CdFileUtils.readFileContent(srcFileName);
List<String> textTopicStringList = topicEntityList.stream().map(TopicEntity::getTopic)
.collect(Collectors.toList());
List<String> stringTopicCn = translateStringList(textTopicStringList);
List<String> textDescriptionStringList = topicEntityList.stream().map(TopicEntity::getDescription)
.collect(Collectors.toList());
List<String> stringDescriptionCn = translateStringList(textDescriptionStringList);
List<String> newListEnCn = new ArrayList<>();
String titleStr;
if (CollectionUtil.isNotEmpty(stringTopicCn) && CollectionUtil.isNotEmpty(stringDescriptionCn)
&& topicEntityList.size() == stringDescriptionCn.size()
&& stringTopicCn.size() == stringDescriptionCn.size()) {
for (int i = 0; i < topicEntityList.size(); i++) {
titleStr = topicEntityList.get(i).getEpisode()
+ "\t" + topicEntityList.get(i).getTopic() + "|" + stringTopicCn.get(i)
+ "\t" + topicEntityList.get(i).getDescription() + "|" + stringDescriptionCn.get(i);
newListEnCn.add(titleStr);
}
}
String fileNameCn = BbcConstants.ROOT_FOLDER_NAME + "all_title_cn.txt";
// 写中文翻译文本
CdFileUtils.writeToFile(fileNameCn, newListEnCn);
}
/**
* 翻译字符串数组
*
* @param textTopicStringList
* @return
*/
public static List<String> translateStringList(List<String> textTopicStringList) {
List<String> result = new ArrayList<>();
String textTopic = textTopicStringList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringList = TranslatorTextUtil.translatorText(textTopic);
for (int i = 0; i < stringList.size(); i++) {
String temp = stringList.get(i);
String[] arr = temp.split("\r\n");
result = Arrays.asList(arr);
}
return result;
}
}
| CoderDream/java-architect-util | free-apps/src/main/java/com/coderdream/freeapps/util/bbc/TranslateUtil.java | 5,863 | //英国广播公司(BBC) | line_comment | zh-cn | package com.coderdream.freeapps.util.bbc;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.coderdream.freeapps.model.SubtitleBaseEntity;
import com.coderdream.freeapps.model.TopicEntity;
import com.coderdream.freeapps.util.other.CdFileUtils;
import com.coderdream.freeapps.util.translator.text.TranslatorTextUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
/**
* @author CoderDream
*/
public class TranslateUtil {
public static void main(String[] args) {
String folderName = "210318";
// TranslateUtil.process(folderName);
// TranslateUtil.mergeScriptContent(folderName);
TranslateUtil.translateEngSrc(folderName);
// String str = "大括号外面的内容(Michael Collins)的内容(Michael Collins) ";
// str = removeEnContent(str);
// System.out.println(str);
//
// List<String> NUMBER_LIST = Arrays.asList("230406", "230413", "230420", "230427");
// TranslateUtil.translateTitle(NUMBER_LIST);
// TranslateUtil.mergeScriptContentWx(folderName);
//translateAllTitle();
// process(folderName);
}
/**
*
* @param str
* @return
*/
@NotNull
private static String removeEnContent(String str) {
do {
int startIndex = str.lastIndexOf("(");
int endIndex = str.lastIndexOf(")");
if (startIndex != -1 && endIndex != -1) {
try {
if (startIndex >= 0 && endIndex > 0) {
str = str.replaceAll(str.substring(startIndex, endIndex + 1), "");
} else {
System.out.println(
"#####x##### ERROR: startIndex is " + startIndex + "; endIndex is " + endIndex + "; str "
+ str);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("### str " + str);
}
}
} while (str.contains("(") && str.contains(")"));
return str;
}
public static List<String> translateTitle(List<String> folderNameList, String fileName) {
// if (fileName == null) {
// fileName = "script_raw";
// }
// 220303_script.txt
// if (fileName.endsWith("_script.txt")) {
// // TODO
// }
// 6 Minute English
// word-for-word transcript
List<String> titleList = new ArrayList<>();
for (String folderName : folderNameList) {
fileName = folderName + "_script"; // TODO 指定
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String title;
int size = stringList.size();
if (CollectionUtil.isNotEmpty(stringList)) {
// titleList.add(stringList.get(0));
titleList.add(getTitleString(stringList));
}
}
String textTitleList = titleList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListTitleCn = TranslatorTextUtil.translatorText(textTitleList);
String[] arr = new String[0];
for (int i = 0; i < stringListTitleCn.size(); i++) {
String temp = stringListTitleCn.get(i);
arr = temp.split("\r\n");
}
List<String> titleCnList = Arrays.asList(arr);
List<String> newList = new ArrayList<>();
String titleTranslate;
for (int i = 0; i < arr.length; i++) {
titleTranslate = folderNameList.get(i).substring(2) + "\t" + titleList.get(i) + "\t" + arr[i];
System.out.println(titleTranslate);
newList.add(titleTranslate);
}
// String srcFileNameCn = BbcConstants.ROOT_FOLDER_NAME + File.separator + "title.txt";
// 写中文翻译文本
// CdFileUtils.writeToFile(srcFileNameCn, newList);
return titleCnList;
}
private static String getTitleString(List<String> stringList) {
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < stringList.size(); i++) {
if (stringList.get(i).contains("6 Minute English")) {
startIndex = i;
}
if (stringList.get(i).contains("word-for-word transcript")) {
endIndex = i;
break;
}
}
StringBuilder result = new StringBuilder();
for (int i = startIndex + 1; i < endIndex; i++) {
result.append(stringList.get(i));
}
return result.toString();
}
/**
* 手工粘贴文本
*
* @param folderNameList
* @param fileName
* @return
*/
public static List<String> translateTitleManual(List<String> folderNameList, String fileName) {
if (fileName == null) {
fileName = "script_raw";
}
List<String> titleList = new ArrayList<>();
for (String folderName : folderNameList) {
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String title;
int size = stringList.size();
for (int i = 0; i < size; i++) {
String tempStr = stringList.get(i);
// System.out.println("tempStr: " + tempStr);
if ("INTERMEDIATE LEVEL".equals(tempStr)) {
title = stringList.get(i + 1);
titleList.add(title);
break;
}
}
}
String textTitleList = titleList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListTitleCn = TranslatorTextUtil.translatorText(textTitleList);
String[] arr = new String[0];
for (int i = 0; i < stringListTitleCn.size(); i++) {
String temp = stringListTitleCn.get(i);
arr = temp.split("\r\n");
}
List<String> titleCnList = Arrays.asList(arr);
List<String> newList = new ArrayList<>();
String titleTranslate;
for (int i = 0; i < arr.length; i++) {
titleTranslate = folderNameList.get(i).substring(2) + "\t" + titleList.get(i) + "\t" + arr[i];
System.out.println(titleTranslate);
newList.add(titleTranslate);
}
String srcFileNameCn = BbcConstants.ROOT_FOLDER_NAME + File.separator + "title.txt";
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameCn, newList);
return titleCnList;
}
/**
* 翻译脚本
*
* @param folderName
*/
public static void process(String folderName) {
String fileName = "script_dialog";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String text = stringList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
System.out.println("text: " + text);
List<String> stringListCn = TranslatorTextUtil.translatorText(text);
List<String> newList = new ArrayList<>();
for (int i = 0; i < stringListCn.size(); i++) {
String temp = stringListCn.get(i);
String[] arr = temp.split("\r\n");
for (int j = 0; j < arr.length; j++) {
upgradeTranslate(folderName, arr, j, stringList);
System.out.println(arr[j]);
newList.add(arr[j]);
// 如果最后一行不是空格,则补一个空白字符串
if (j == arr.length - 1 && StrUtil.isNotEmpty(arr[j])) {
newList.add("");
}
}
}
String srcFileNameCn = CommonUtil.getFullPathFileName(folderName, fileName, "_cn.txt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameCn, newList);
}
/**
* 优化句子
*
* @param folderName
* @param arr
* @param j
*/
private static void upgradeTranslate(String folderName, String[] arr, int j, List<String> subtitleList) {
if ("抢".equals(arr[j])) {
arr[j] = "罗伯";
}
if ("山 姆".equals(arr[j])) {
arr[j] = "山姆";
}
if ("井".equals(arr[j])) {
arr[j] = "嗯";
}
if ("右".equals(arr[j])) {
arr[j] = "是的";
}
if ("右!".equals(arr[j])) {
arr[j] = "好的!";
}
// 医 管 局!
// (Michael Collins) 去掉大括号及大括号内的内容
arr[j] = removeEnContent(arr[j]);
arr[j] = arr[j].replaceAll(" 6 Minute English ", "六分钟英语");
arr[j] = arr[j].replaceAll("医 管 局", "哈哈");
arr[j] = arr[j].replaceAll("乔吉", "乔治");
arr[j] = arr[j].replaceAll("成语", "谚语");
arr[j] = arr[j].replaceAll("Rob", "罗伯");
arr[j] = arr[j].replaceAll("伟大!", "太好了!");
arr[j] = arr[j].replaceAll("右。", "好的。"); // Right应该翻译成好的,而不是右
arr[j] = arr[j].replaceAll("山 姆", "山姆");
arr[j] = arr[j].replaceAll("6分钟", "六分钟");
arr[j] = arr[j].replaceAll(" 6 分钟", "六分钟");
arr[j] = arr[j].replaceAll(";", ";");
arr[j] = arr[j].replaceAll("“拯救大象”(Save the Elephants)", "“拯救大象”");
arr[j] = arr[j].replaceAll("六分钟又到了", "六分钟时间又到了"); // 英国广播公司(BBC)
arr[j] = arr[j].replaceAll("英国广播公司(BBC)", "英国广播公司"); // 英国广播公司(BBC)
arr[j] = arr[j].replaceAll("——", " —— ");// ——
if (-1 != arr[j].lastIndexOf("程序") && -1 != subtitleList.get(j).lastIndexOf("programme")) {
arr[j] = arr[j].replaceAll("程序", "节目");
}
if (-1 != arr[j].lastIndexOf("课程") && -1 != subtitleList.get(j).lastIndexOf("programme")) {
arr[j] = arr[j].replaceAll("课程", "节目");
}
// 维克托
arr[j] = arr[j].replaceAll("Victor;", "维克多");
arr[j] = arr[j].trim();//去掉前后空格
if ("231026".equals(folderName)) {
arr[j] = arr[j].replaceAll("一百个", "一百岁");
}
if ("231109".equals(folderName)) {
if (arr[j].equals("幸运")) {
arr[j] = arr[j].replaceAll("幸运", "幸运的是");
}
}
// 针对230413的AI翻译优化
if ("230413".equals(folderName)) {
arr[j] = arr[j].replaceAll("垃圾场", "情绪低落");
arr[j] = arr[j].replaceAll("垃圾堆", "情绪低落");
arr[j] = arr[j].replaceAll("最尖锐的", "极度");
arr[j] = arr[j].replaceAll(" Covid", "冠状病毒");
arr[j] = arr[j].replaceAll("Covid", "冠状病毒");
arr[j] = arr[j].replaceAll("英国广播公司(BBC)", "BBC");//英国 <SUF>
arr[j] = arr[j].replaceAll("《纪录片》(The Documentary)", "《纪录片》");//《纪录片》(The Documentary)
arr[j] = arr[j].replaceAll("海伦·罗素(Helen Russell)", "海伦·罗素");// 海伦·罗素(Helen Russell)
arr[j] = arr[j].replaceAll("托马斯·迪克森(Thomas Dixon)", "托马斯·迪克森");// 托马斯·迪克森(Thomas Dixon)
}
// 针对230302的AI翻译优化
if ("230302".equals(folderName)) {
arr[j] = arr[j].replaceAll("Rob", "'dunk'");
arr[j] = arr[j].replaceAll("扣篮", "'dunk'");
arr[j] = arr[j].replaceAll("英国广播公司(BBC)", "BBC");//英国广播公司(BBC)
arr[j] = arr[j].replaceAll("迈克尔·罗森(Michael Rosen)", "迈克尔·罗森");
arr[j] = arr[j].replaceAll("朱莉·塞迪维(Julie Sedivy)", "朱莉·塞迪维");
arr[j] = arr[j].replaceAll("计划", "节目");
}
//
// 针对230330的AI翻译优化
if ("230330".equals(folderName)) {
arr[j] = arr[j].replaceAll("历克斯·米尔克(Alex Mielke)", "历克斯·米尔克");
}
}
public static void translateEngSrc(String folderName) {
String fileName = "eng";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".srt");
// readSrcFileContent
List<SubtitleBaseEntity> subtitleBaseEntityList = CdFileUtils.readSrcFileContent(srcFileName);
List<String> subtitleList = subtitleBaseEntityList.stream().map(SubtitleBaseEntity::getSubtitle)
.collect(Collectors.toList());
String text = subtitleList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListCn = TranslatorTextUtil.translatorText(text);
List<String> newList = new ArrayList<>();
List<String> newListEnCn = new ArrayList<>();
List<String> lrcListEnCn = new ArrayList<>();
SubtitleBaseEntity subtitleBaseEntity;
String timeStr;
String lrc;
for (int i = 0; i < stringListCn.size(); i++) {
String temp = stringListCn.get(i);
String[] arr = temp.split("\r\n");
// 检查大小
if (arr.length != subtitleBaseEntityList.size()) {
System.out.println("###");
break;
}
for (int j = 0; j < arr.length; j++) {
// 优化翻译
upgradeTranslate(folderName, arr, j, subtitleList);
System.out.println(arr[j]);
subtitleBaseEntity = subtitleBaseEntityList.get(j);
newList.add(subtitleBaseEntity.getSubIndex() + "");
newList.add(subtitleBaseEntity.getTimeStr());
newList.add(arr[j]);
newList.add("");
newListEnCn.add(subtitleBaseEntity.getSubIndex() + "");
newListEnCn.add(subtitleBaseEntity.getTimeStr());
newListEnCn.add(subtitleList.get(j) + "\r" + arr[j]);
newListEnCn.add("");
timeStr = subtitleBaseEntity.getTimeStr();
timeStr = timeStr.substring(3, 11);
timeStr = timeStr.replaceAll(",", ".");
lrc = "[" + timeStr + "]" + subtitleList.get(j) + "|" + arr[j];
lrcListEnCn.add(lrc);
}
}
String srcFileNameCn = CommonUtil.getFullPathFileName(folderName, "chn", ".srt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameCn, newList);
// // 双语字幕
// String srcFileNameEnCn = CommonUtil.getFullPathFileName(folderName, "audio5", ".srt");
// // 写双语歌词文本
// CdFileUtils.writeToFile(srcFileNameEnCn, newListEnCn);
//
// // 双语歌词
// String lrcFileNameEnCn = CommonUtil.getFullPathFileName(folderName, "audio5", ".lrc");
// // 写双语歌词文本
// CdFileUtils.writeToFile(lrcFileNameEnCn, lrcListEnCn);
}
/**
* 生成对话脚本合集
*
* @param folderName
*/
public static void mergeScriptContent(String folderName) {
String fileName = "script_dialog";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<ScriptEntity> scriptEntityListEn = CdFileUtils.genScriptEntityList(srcFileName);
String srcFileNameCn = CommonUtil.getFullPathFileName(folderName, fileName, "_cn.txt");
List<ScriptEntity> scriptEntityListCn = CdFileUtils.genScriptEntityList(srcFileNameCn);
ScriptEntity scriptEntityEn;
ScriptEntity scriptEntityCn;
String scriptEn;
String scriptCn;
List<String> newList = new ArrayList<>();
if (CollectionUtil.isNotEmpty(scriptEntityListEn) && CollectionUtil.isNotEmpty(scriptEntityListCn)
&& scriptEntityListEn.size() == scriptEntityListCn.size()) {
for (int i = 0; i < scriptEntityListEn.size(); i++) {
scriptEntityEn = scriptEntityListEn.get(i);
scriptEn = scriptEntityEn.getContent();
scriptEn = scriptEn.replaceAll("Hello. This is 6 Minute English from BBC Learning English. ", "");
scriptEntityCn = scriptEntityListCn.get(i);
scriptCn = scriptEntityCn.getContent();
scriptCn = scriptCn.replaceAll("你好。这是来自BBC学习英语的六分钟英语。", "");
newList.add(scriptEntityEn.getTalker() + "(" + scriptEntityCn.getTalker() + ")");
newList.add(scriptEn + "\r\n" + scriptCn);
newList.add("");
}
} else {
if (CollectionUtil.isEmpty(scriptEntityListEn)) {
System.out.println("scriptEntityListEn 为空。");
} else if (CollectionUtil.isEmpty(scriptEntityListCn)) {
System.out.println("scriptEntityListCn 为空。");
} else {
System.out.println(
"两个脚本格式不对,实体大小分别为:" + scriptEntityListEn.size() + "\t:\t"
+ scriptEntityListCn.size()); //
}
}
String srcFileNameMerge = CommonUtil.getFullPathFileName(folderName, folderName, "_中英双语对话脚本.txt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameMerge, newList);
}
/**
* 生成对话脚本合集
*
* @param folderName
*/
public static void mergeScriptContentWx(String folderName) {
String fileName = "script_dialog_wx2";
String srcFileName = CommonUtil.getFullPathFileName(folderName, fileName, ".txt");
List<String> stringList = CdFileUtils.readFileContent(srcFileName);
String text = stringList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringListCn = TranslatorTextUtil.translatorText(text);
List<String> newList = new ArrayList<>();
List<String> newListEnCn = new ArrayList<>();
List<String> lrcListEnCn = new ArrayList<>();
SubtitleBaseEntity subtitleBaseEntity;
String timeStr;
String lrc;
for (int i = 0; i < stringListCn.size(); i++) {
String temp = stringListCn.get(i);
String[] arr = temp.split("\r\n");
for (int j = 0; j < arr.length; j++) {
upgradeTranslate(folderName, arr, j, stringList);
System.out.println(arr[j]);
// subtitleBaseEntity = subtitleBaseEntityList.get(j);
// newList.add(subtitleBaseEntity.getSubIndex() + "");
// newList.add(subtitleBaseEntity.getTimeStr());
// newList.add(arr[j]);
// newList.add("");
// newListEnCn.add(subtitleBaseEntity.getSubIndex() + "");
// newListEnCn.add(subtitleBaseEntity.getTimeStr());
newListEnCn.add(stringList.get(j) + "\r" + arr[j]);
newListEnCn.add("");
}
}
String srcFileNameMerge = CommonUtil.getFullPathFileName(folderName, fileName, "_merge.txt");
// 写中文翻译文本
CdFileUtils.writeToFile(srcFileNameMerge, newListEnCn);
}
/**
* 生成对话脚本合集
*/
public static void translateAllTitle() {
String fileName = BbcConstants.ROOT_FOLDER_NAME + "all.txt";
List<TopicEntity> topicEntityList = CdFileUtils.genTopicEntityList(fileName);
// List<String> stringList = CdFileUtils.readFileContent(srcFileName);
List<String> textTopicStringList = topicEntityList.stream().map(TopicEntity::getTopic)
.collect(Collectors.toList());
List<String> stringTopicCn = translateStringList(textTopicStringList);
List<String> textDescriptionStringList = topicEntityList.stream().map(TopicEntity::getDescription)
.collect(Collectors.toList());
List<String> stringDescriptionCn = translateStringList(textDescriptionStringList);
List<String> newListEnCn = new ArrayList<>();
String titleStr;
if (CollectionUtil.isNotEmpty(stringTopicCn) && CollectionUtil.isNotEmpty(stringDescriptionCn)
&& topicEntityList.size() == stringDescriptionCn.size()
&& stringTopicCn.size() == stringDescriptionCn.size()) {
for (int i = 0; i < topicEntityList.size(); i++) {
titleStr = topicEntityList.get(i).getEpisode()
+ "\t" + topicEntityList.get(i).getTopic() + "|" + stringTopicCn.get(i)
+ "\t" + topicEntityList.get(i).getDescription() + "|" + stringDescriptionCn.get(i);
newListEnCn.add(titleStr);
}
}
String fileNameCn = BbcConstants.ROOT_FOLDER_NAME + "all_title_cn.txt";
// 写中文翻译文本
CdFileUtils.writeToFile(fileNameCn, newListEnCn);
}
/**
* 翻译字符串数组
*
* @param textTopicStringList
* @return
*/
public static List<String> translateStringList(List<String> textTopicStringList) {
List<String> result = new ArrayList<>();
String textTopic = textTopicStringList.stream().map(String::valueOf).collect(Collectors.joining("\r\n"));
List<String> stringList = TranslatorTextUtil.translatorText(textTopic);
for (int i = 0; i < stringList.size(); i++) {
String temp = stringList.get(i);
String[] arr = temp.split("\r\n");
result = Arrays.asList(arr);
}
return result;
}
}
| 0 | 13 | 0 |
36075_14 | package com.coderdream.service;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.coderdream.bean.Logging;
import com.coderdream.dao.LoggingDao;
import com.coderdream.dao.UserLocationDao;
import com.coderdream.model.Article;
import com.coderdream.model.BaiduPlace;
import com.coderdream.model.Music;
import com.coderdream.model.MusicMessage;
import com.coderdream.model.NewsMessage;
import com.coderdream.model.TextMessage;
import com.coderdream.model.UserLocation;
import com.coderdream.util.BaiduMapUtil;
import com.coderdream.util.MessageUtil;
/**
* 核心服务类
*/
public class CoreService {
public static String TAG = "CoreService";
private Logger logger = Logger.getLogger(CoreService.class);
private LoggingDao loggingDao = new LoggingDao(this.getClass().getName());
private UserLocationDao userLocationDao = new UserLocationDao();
/**
* 处理微信发来的请求
*
* @param request
* @return xml
*/
public String processRequest(InputStream inputStream) {
logger.debug(TAG + " #1# processRequest");
SimpleDateFormat f_timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Logging logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#1# processRequest");
loggingDao.addLogging(logging);
// xml格式的消息数据
String respXml = null;
// 默认返回的文本消息内容
String respContent = "未知的消息类型!";
try {
// 调用parseXml方法解析请求消息
Map<String, String> requestMap = MessageUtil.parseXml(inputStream);
// 发送方帐号
String fromUserName = requestMap.get("FromUserName");
// 开发者微信号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
String logStr = "#2# fromUserName: " + fromUserName + ", toUserName: " + toUserName + ", msgType: "
+ msgType;
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
// 回复文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.MESSAGE_TYPE_TEXT);
logStr = "#3# textMessage: " + textMessage.toString();
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
// 文本消息
if (msgType.equals(MessageUtil.MESSAGE_TYPE_TEXT)) {
// respContent = "您发送的是文本消息!";
// 接收用户发送的文本消息内容
String content = requestMap.get("Content").trim();
// 创建图文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
List<Article> articleList = new ArrayList<Article>();
// 翻译
if (content.startsWith("翻译")) {
String keyWord = content.replaceAll("^翻译", "").trim();
if ("".equals(keyWord)) {
textMessage.setContent(getTranslateUsage());
} else {
textMessage.setContent(BaiduTranslateService.translate(keyWord));
}
respContent = textMessage.getContent();
}
// 如果以“歌曲”2个字开头
else if (content.startsWith("歌曲")) {
// 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉
String keyWord = content.replaceAll("^歌曲[\\+ ~!@#%^-_=]?", "");
// 如果歌曲名称为空
if ("".equals(keyWord)) {
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#歌曲名称为空#");
loggingDao.addLogging(logging);
respContent = getMusicUsage();
} else {
String[] kwArr = keyWord.split("@");
// 歌曲名称
String musicTitle = kwArr[0];
// 演唱者默认为空
String musicAuthor = "";
if (2 == kwArr.length) {
musicAuthor = kwArr[1];
}
// 搜索音乐
Music music = BaiduMusicService.searchMusic(musicTitle, musicAuthor);
// 未搜索到音乐
if (null == music) {
respContent = "对不起,没有找到你想听的歌曲<" + musicTitle + ">。";
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#未搜索到音乐 respContent# " + respContent);
loggingDao.addLogging(logging);
} else {
// 音乐消息
logger.info("找到 " + musicTitle + " 了!!!");
MusicMessage musicMessage = new MusicMessage();
musicMessage.setToUserName(fromUserName);
musicMessage.setFromUserName(toUserName);
musicMessage.setCreateTime(new Date().getTime());
musicMessage.setMsgType(MessageUtil.MESSAGE_TYPE_MUSIC);
musicMessage.setMusic(music);
newsMessage.setFuncFlag(0);
respXml = MessageUtil.messageToXml(musicMessage);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#return respXml# " + respXml);
loggingDao.addLogging(logging);
return respXml;
}
}
}
// 如果以“历史”2个字开头
else if (content.startsWith("历史")) {
// 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉
String dayStr = content.substring(2);
// 如果只输入历史两个字,在输出当天的历史
if (null == dayStr || "".equals(dayStr.trim())) {
DateFormat df = new SimpleDateFormat("MMdd");
dayStr = df.format(Calendar.getInstance().getTime());
}
respContent = TodayInHistoryService.getTodayInHistoryInfoFromDB(dayStr);
}
// 周边搜索
else if (content.startsWith("附近")) {
String keyWord = content.replaceAll("附近", "").trim();
// 获取用户最后一次发送的地理位置
UserLocation location = userLocationDao.getLastLocation(fromUserName);
// 未获取到
if (null == location) {
respContent = getLocationUsage();
} else {
// 根据转换后(纠偏)的坐标搜索周边POI
List<BaiduPlace> placeList = BaiduMapUtil.searchPlace(keyWord, location.getBd09Lng(),
location.getBd09Lat());
// 未搜索到POI
if (null == placeList || 0 == placeList.size()) {
respContent = String.format("/难过,您发送的位置附近未搜索到“%s”信息!", keyWord);
} else {
articleList = BaiduMapUtil.makeArticleList(placeList, location.getBd09Lng(),
location.getBd09Lat());
// 回复图文消息
newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.MESSAGE_TYPE_NEWS);
newsMessage.setArticles(articleList);
newsMessage.setArticleCount(articleList.size());
return MessageUtil.messageToXml(newsMessage);
}
}
}
// 单图文消息
else if ("1".equals(content)) {
Article article = new Article();
article.setTitle("微信公众帐号开发教程Java版");
article.setDescription("柳峰,80后,微信公众帐号开发经验4个月。为帮助初学者入门,特推出此系列教程,也希望借此机会认识更多同行!");
article.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article.setUrl("http://blog.csdn.net/lyq8479?toUserName=" + fromUserName + "&toUserName="
+ toUserName);
articleList.add(article);
// 设置图文消息个数
newsMessage.setArticleCount(articleList.size());
// 设置图文消息包含的图文集合
newsMessage.setArticles(articleList);
// 将图文消息对象转换成xml字符串
return MessageUtil.messageToXml(newsMessage);
}
// 单图文消息---不含图片
else if ("2".equals(content)) {
Article article = new Article();
article.setTitle("微信公众帐号开发教程Java版");
// 图文消息中可以使用QQ表情、符号表情
article.setDescription("柳峰,80后,"
// + emoji(0x1F6B9)
+ ",微信公众帐号开发经验4个月。为帮助初学者入门,特推出此系列连载教程,也希望借此机会认识更多同行!\n\n目前已推出教程共12篇,包括接口配置、消息封装、框架搭建、QQ表情发送、符号表情发送等。\n\n后期还计划推出一些实用功能的开发讲解,例如:天气预报、周边搜索、聊天功能等。");
// 将图片置为空
article.setPicUrl("");
article.setUrl("http://blog.csdn.net/lyq8479?toUserName=" + fromUserName + "&toUserName="
+ toUserName);
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 多图文消息
else if ("3".equals(content)) {
Article article1 = new Article();
article1.setTitle("微信公众帐号开发教程\n引言");
article1.setDescription("");
article1.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article1.setUrl("http://blog.csdn.net/lyq8479/article/details/8937622?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article2 = new Article();
article2.setTitle("第2篇\n微信公众帐号的类型");
article2.setDescription("");
article2.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article2.setUrl("http://blog.csdn.net/lyq8479/article/details/8941577?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article3 = new Article();
article3.setTitle("关注页面");
article3.setDescription("关注页面");
article3.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article3.setUrl("http://wxquan.sinaapp.com/follow.jsp?toUserName=" + fromUserName + "&toUserName="
+ toUserName);
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 多图文消息---首条消息不含图片
else if ("4".equals(content)) {
Article article1 = new Article();
article1.setTitle("微信公众帐号开发教程Java版");
article1.setDescription("");
// 将图片置为空
article1.setPicUrl("");
article1.setUrl("http://blog.csdn.net/lyq8479");
Article article2 = new Article();
article2.setTitle("第4篇\n消息及消息处理工具的封装");
article2.setDescription("");
article2.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article2.setUrl("http://blog.csdn.net/lyq8479/article/details/8949088?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article3 = new Article();
article3.setTitle("第5篇\n各种消息的接收与响应");
article3.setDescription("");
article3.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article3.setUrl("http://blog.csdn.net/lyq8479/article/details/8952173?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article4 = new Article();
article4.setTitle("第6篇\n文本消息的内容长度限制揭秘");
article4.setDescription("");
article4.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article4.setUrl("http://blog.csdn.net/lyq8479/article/details/8967824?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
articleList.add(article4);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 多图文消息---最后一条消息不含图片
else if ("5".equals(content)) {
Article article1 = new Article();
article1.setTitle("第7篇\n文本消息中换行符的使用");
article1.setDescription("");
article1.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article1.setUrl("http://blog.csdn.net/lyq8479/article/details/9141467?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article2 = new Article();
article2.setTitle("第8篇\n文本消息中使用网页超链接");
article2.setDescription("");
article2.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article2.setUrl("http://blog.csdn.net/lyq8479/article/details/9157455?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article3 = new Article();
article3.setTitle("如果觉得文章对你有所帮助,请通过博客留言或关注微信公众帐号xiaoqrobot来支持柳峰!");
article3.setDescription("");
// 将图片置为空
article3.setPicUrl("");
article3.setUrl("http://blog.csdn.net/lyq8479");
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 其他,弹出帮助信息
else {
respContent = getUsage();
}
}
// 图片消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
}
// 语音消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是语音消息!";
}
// 视频消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_VIDEO)) {
respContent = "您发送的是视频消息!";
}
// 地理位置消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
// 用户发送的经纬度
String lng = requestMap.get("Location_Y");
String lat = requestMap.get("Location_X");
// 坐标转换后的经纬度
String bd09Lng = null;
String bd09Lat = null;
// 调用接口转换坐标
UserLocation userLocation = BaiduMapUtil.convertCoord(lng, lat);
if (null != userLocation) {
bd09Lng = userLocation.getBd09Lng();
bd09Lat = userLocation.getBd09Lat();
}
logger.info("lng= " + lng + "; lat= " + lat);
logger.info("bd09Lng= " + bd09Lng + "; bd09Lat= " + bd09Lat);
// 保存用户地理位置
int count = userLocationDao.saveUserLocation(fromUserName, lng, lat, bd09Lng, bd09Lat);
loggingDao.debug("fromUserName" + fromUserName + "lng= " + lng + "; lat= " + lat + "bd09Lng= "
+ bd09Lng + "; bd09Lat= " + bd09Lat + "count" + count);
StringBuffer buffer = new StringBuffer();
buffer.append("[愉快]").append("成功接收您的位置!").append("\n\n");
buffer.append("您可以输入搜索关键词获取周边信息了,例如:").append("\n");
buffer.append(" 附近ATM").append("\n");
buffer.append(" 附近KTV").append("\n");
buffer.append(" 附近厕所").append("\n");
buffer.append("必须以“附近”两个字开头!");
respContent = buffer.toString();
}
// 链接消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
}
// 事件推送
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = requestMap.get("Event");
// 关注
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
respContent = "谢谢您的关注!/n";
respContent += getSubscribeMsg();
}
// 取消关注
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消订阅后用户不会再收到公众账号发送的消息,因此不需要回复
}
// 扫描带参数二维码
else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
// TODO 处理扫描带参数二维码事件
}
// 上报地理位置
else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
// TODO 处理上报地理位置事件
}
// 自定义菜单
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// TODO 处理菜单点击事件
}
}
logStr = "#4# respContent: " + respContent;
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
// 设置文本消息的内容
textMessage.setContent(respContent);
// 将文本消息对象转换成xml
respXml = MessageUtil.messageToXml(textMessage);
logStr = "#5# respXml: " + respXml;
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
} catch (Exception e) {
e.printStackTrace();
}
return respXml;
}
/**
* 翻译使用指南
*
* @return
*/
public static String getTranslateUsage() {
StringBuffer buffer = new StringBuffer();
// buffer.append(XiaoqUtil.emoji(0xe148)).append("Q译通使用指南").append("\n\n");
buffer.append("Q译通为用户提供专业的多语言翻译服务,目前支持以下翻译方向:").append("\n");
buffer.append(" 中 -> 英").append("\n");
buffer.append(" 英 -> 中").append("\n");
buffer.append(" 日 -> 中").append("\n\n");
buffer.append("使用示例:").append("\n");
buffer.append(" 翻译我是中国人").append("\n");
buffer.append(" 翻译dream").append("\n");
buffer.append(" 翻译さようなら").append("\n\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}
/**
* 歌曲点播使用指南
*
* @return
*/
public static String getMusicUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("歌曲点播操作指南").append("\n\n");
buffer.append("回复:歌曲+歌名").append("\n");
buffer.append("例如:歌曲存在").append("\n");
buffer.append("或者:歌曲存在@汪峰").append("\n\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}
/**
* 歌曲点播使用指南
*
* @return
*/
public static String getUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("历史年月(历史0403)").append("\n");
buffer.append("歌曲歌名(歌曲)").append("\n");
buffer.append("翻译词语(翻译明天)-支持中英日语").append("\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}
/**
* 关注提示语
*
* @return
*/
public static String getSubscribeMsg() {
StringBuffer buffer = new StringBuffer();
buffer.append("您是否有过出门在外四处找ATM或厕所的经历?").append("\n\n");
buffer.append("您是否有过出差在外搜寻美食或娱乐场所的经历?").append("\n\n");
buffer.append("周边搜索为您的出行保驾护航,为您提供专业的周边生活指南,回复“附近”开始体验吧!");
return buffer.toString();
}
/**
* 使用说明
*
* @return
*/
public static String getLocationUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("周边搜索使用说明").append("\n\n");
buffer.append("1)发送地理位置").append("\n");
buffer.append("点击窗口底部的“+”按钮,选择“位置”,点“发送”").append("\n\n");
buffer.append("2)指定关键词搜索").append("\n");
buffer.append("格式:附近+关键词\n例如:附近ATM、附近KTV、附近厕所");
return buffer.toString();
}
} | CoderDream/wxquan | src/main/java/com/coderdream/service/CoreService.java | 6,044 | // 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉 | line_comment | zh-cn | package com.coderdream.service;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.coderdream.bean.Logging;
import com.coderdream.dao.LoggingDao;
import com.coderdream.dao.UserLocationDao;
import com.coderdream.model.Article;
import com.coderdream.model.BaiduPlace;
import com.coderdream.model.Music;
import com.coderdream.model.MusicMessage;
import com.coderdream.model.NewsMessage;
import com.coderdream.model.TextMessage;
import com.coderdream.model.UserLocation;
import com.coderdream.util.BaiduMapUtil;
import com.coderdream.util.MessageUtil;
/**
* 核心服务类
*/
public class CoreService {
public static String TAG = "CoreService";
private Logger logger = Logger.getLogger(CoreService.class);
private LoggingDao loggingDao = new LoggingDao(this.getClass().getName());
private UserLocationDao userLocationDao = new UserLocationDao();
/**
* 处理微信发来的请求
*
* @param request
* @return xml
*/
public String processRequest(InputStream inputStream) {
logger.debug(TAG + " #1# processRequest");
SimpleDateFormat f_timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Logging logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#1# processRequest");
loggingDao.addLogging(logging);
// xml格式的消息数据
String respXml = null;
// 默认返回的文本消息内容
String respContent = "未知的消息类型!";
try {
// 调用parseXml方法解析请求消息
Map<String, String> requestMap = MessageUtil.parseXml(inputStream);
// 发送方帐号
String fromUserName = requestMap.get("FromUserName");
// 开发者微信号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
String logStr = "#2# fromUserName: " + fromUserName + ", toUserName: " + toUserName + ", msgType: "
+ msgType;
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
// 回复文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.MESSAGE_TYPE_TEXT);
logStr = "#3# textMessage: " + textMessage.toString();
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
// 文本消息
if (msgType.equals(MessageUtil.MESSAGE_TYPE_TEXT)) {
// respContent = "您发送的是文本消息!";
// 接收用户发送的文本消息内容
String content = requestMap.get("Content").trim();
// 创建图文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
List<Article> articleList = new ArrayList<Article>();
// 翻译
if (content.startsWith("翻译")) {
String keyWord = content.replaceAll("^翻译", "").trim();
if ("".equals(keyWord)) {
textMessage.setContent(getTranslateUsage());
} else {
textMessage.setContent(BaiduTranslateService.translate(keyWord));
}
respContent = textMessage.getContent();
}
// 如果以“歌曲”2个字开头
else if (content.startsWith("歌曲")) {
// 将歌 <SUF>
String keyWord = content.replaceAll("^歌曲[\\+ ~!@#%^-_=]?", "");
// 如果歌曲名称为空
if ("".equals(keyWord)) {
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#歌曲名称为空#");
loggingDao.addLogging(logging);
respContent = getMusicUsage();
} else {
String[] kwArr = keyWord.split("@");
// 歌曲名称
String musicTitle = kwArr[0];
// 演唱者默认为空
String musicAuthor = "";
if (2 == kwArr.length) {
musicAuthor = kwArr[1];
}
// 搜索音乐
Music music = BaiduMusicService.searchMusic(musicTitle, musicAuthor);
// 未搜索到音乐
if (null == music) {
respContent = "对不起,没有找到你想听的歌曲<" + musicTitle + ">。";
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#未搜索到音乐 respContent# " + respContent);
loggingDao.addLogging(logging);
} else {
// 音乐消息
logger.info("找到 " + musicTitle + " 了!!!");
MusicMessage musicMessage = new MusicMessage();
musicMessage.setToUserName(fromUserName);
musicMessage.setFromUserName(toUserName);
musicMessage.setCreateTime(new Date().getTime());
musicMessage.setMsgType(MessageUtil.MESSAGE_TYPE_MUSIC);
musicMessage.setMusic(music);
newsMessage.setFuncFlag(0);
respXml = MessageUtil.messageToXml(musicMessage);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG,
"#return respXml# " + respXml);
loggingDao.addLogging(logging);
return respXml;
}
}
}
// 如果以“历史”2个字开头
else if (content.startsWith("历史")) {
// 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉
String dayStr = content.substring(2);
// 如果只输入历史两个字,在输出当天的历史
if (null == dayStr || "".equals(dayStr.trim())) {
DateFormat df = new SimpleDateFormat("MMdd");
dayStr = df.format(Calendar.getInstance().getTime());
}
respContent = TodayInHistoryService.getTodayInHistoryInfoFromDB(dayStr);
}
// 周边搜索
else if (content.startsWith("附近")) {
String keyWord = content.replaceAll("附近", "").trim();
// 获取用户最后一次发送的地理位置
UserLocation location = userLocationDao.getLastLocation(fromUserName);
// 未获取到
if (null == location) {
respContent = getLocationUsage();
} else {
// 根据转换后(纠偏)的坐标搜索周边POI
List<BaiduPlace> placeList = BaiduMapUtil.searchPlace(keyWord, location.getBd09Lng(),
location.getBd09Lat());
// 未搜索到POI
if (null == placeList || 0 == placeList.size()) {
respContent = String.format("/难过,您发送的位置附近未搜索到“%s”信息!", keyWord);
} else {
articleList = BaiduMapUtil.makeArticleList(placeList, location.getBd09Lng(),
location.getBd09Lat());
// 回复图文消息
newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.MESSAGE_TYPE_NEWS);
newsMessage.setArticles(articleList);
newsMessage.setArticleCount(articleList.size());
return MessageUtil.messageToXml(newsMessage);
}
}
}
// 单图文消息
else if ("1".equals(content)) {
Article article = new Article();
article.setTitle("微信公众帐号开发教程Java版");
article.setDescription("柳峰,80后,微信公众帐号开发经验4个月。为帮助初学者入门,特推出此系列教程,也希望借此机会认识更多同行!");
article.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article.setUrl("http://blog.csdn.net/lyq8479?toUserName=" + fromUserName + "&toUserName="
+ toUserName);
articleList.add(article);
// 设置图文消息个数
newsMessage.setArticleCount(articleList.size());
// 设置图文消息包含的图文集合
newsMessage.setArticles(articleList);
// 将图文消息对象转换成xml字符串
return MessageUtil.messageToXml(newsMessage);
}
// 单图文消息---不含图片
else if ("2".equals(content)) {
Article article = new Article();
article.setTitle("微信公众帐号开发教程Java版");
// 图文消息中可以使用QQ表情、符号表情
article.setDescription("柳峰,80后,"
// + emoji(0x1F6B9)
+ ",微信公众帐号开发经验4个月。为帮助初学者入门,特推出此系列连载教程,也希望借此机会认识更多同行!\n\n目前已推出教程共12篇,包括接口配置、消息封装、框架搭建、QQ表情发送、符号表情发送等。\n\n后期还计划推出一些实用功能的开发讲解,例如:天气预报、周边搜索、聊天功能等。");
// 将图片置为空
article.setPicUrl("");
article.setUrl("http://blog.csdn.net/lyq8479?toUserName=" + fromUserName + "&toUserName="
+ toUserName);
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 多图文消息
else if ("3".equals(content)) {
Article article1 = new Article();
article1.setTitle("微信公众帐号开发教程\n引言");
article1.setDescription("");
article1.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article1.setUrl("http://blog.csdn.net/lyq8479/article/details/8937622?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article2 = new Article();
article2.setTitle("第2篇\n微信公众帐号的类型");
article2.setDescription("");
article2.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article2.setUrl("http://blog.csdn.net/lyq8479/article/details/8941577?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article3 = new Article();
article3.setTitle("关注页面");
article3.setDescription("关注页面");
article3.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article3.setUrl("http://wxquan.sinaapp.com/follow.jsp?toUserName=" + fromUserName + "&toUserName="
+ toUserName);
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 多图文消息---首条消息不含图片
else if ("4".equals(content)) {
Article article1 = new Article();
article1.setTitle("微信公众帐号开发教程Java版");
article1.setDescription("");
// 将图片置为空
article1.setPicUrl("");
article1.setUrl("http://blog.csdn.net/lyq8479");
Article article2 = new Article();
article2.setTitle("第4篇\n消息及消息处理工具的封装");
article2.setDescription("");
article2.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article2.setUrl("http://blog.csdn.net/lyq8479/article/details/8949088?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article3 = new Article();
article3.setTitle("第5篇\n各种消息的接收与响应");
article3.setDescription("");
article3.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article3.setUrl("http://blog.csdn.net/lyq8479/article/details/8952173?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article4 = new Article();
article4.setTitle("第6篇\n文本消息的内容长度限制揭秘");
article4.setDescription("");
article4.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article4.setUrl("http://blog.csdn.net/lyq8479/article/details/8967824?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
articleList.add(article4);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 多图文消息---最后一条消息不含图片
else if ("5".equals(content)) {
Article article1 = new Article();
article1.setTitle("第7篇\n文本消息中换行符的使用");
article1.setDescription("");
article1.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article1.setUrl("http://blog.csdn.net/lyq8479/article/details/9141467?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article2 = new Article();
article2.setTitle("第8篇\n文本消息中使用网页超链接");
article2.setDescription("");
article2.setPicUrl("http://wxquan.sinaapp.com/meal.jpg");
article2.setUrl("http://blog.csdn.net/lyq8479/article/details/9157455?toUserName=" + fromUserName
+ "&toUserName=" + toUserName);
Article article3 = new Article();
article3.setTitle("如果觉得文章对你有所帮助,请通过博客留言或关注微信公众帐号xiaoqrobot来支持柳峰!");
article3.setDescription("");
// 将图片置为空
article3.setPicUrl("");
article3.setUrl("http://blog.csdn.net/lyq8479");
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
return MessageUtil.messageToXml(newsMessage);
}
// 其他,弹出帮助信息
else {
respContent = getUsage();
}
}
// 图片消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
}
// 语音消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是语音消息!";
}
// 视频消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_VIDEO)) {
respContent = "您发送的是视频消息!";
}
// 地理位置消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
// 用户发送的经纬度
String lng = requestMap.get("Location_Y");
String lat = requestMap.get("Location_X");
// 坐标转换后的经纬度
String bd09Lng = null;
String bd09Lat = null;
// 调用接口转换坐标
UserLocation userLocation = BaiduMapUtil.convertCoord(lng, lat);
if (null != userLocation) {
bd09Lng = userLocation.getBd09Lng();
bd09Lat = userLocation.getBd09Lat();
}
logger.info("lng= " + lng + "; lat= " + lat);
logger.info("bd09Lng= " + bd09Lng + "; bd09Lat= " + bd09Lat);
// 保存用户地理位置
int count = userLocationDao.saveUserLocation(fromUserName, lng, lat, bd09Lng, bd09Lat);
loggingDao.debug("fromUserName" + fromUserName + "lng= " + lng + "; lat= " + lat + "bd09Lng= "
+ bd09Lng + "; bd09Lat= " + bd09Lat + "count" + count);
StringBuffer buffer = new StringBuffer();
buffer.append("[愉快]").append("成功接收您的位置!").append("\n\n");
buffer.append("您可以输入搜索关键词获取周边信息了,例如:").append("\n");
buffer.append(" 附近ATM").append("\n");
buffer.append(" 附近KTV").append("\n");
buffer.append(" 附近厕所").append("\n");
buffer.append("必须以“附近”两个字开头!");
respContent = buffer.toString();
}
// 链接消息
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
}
// 事件推送
else if (msgType.equals(MessageUtil.MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = requestMap.get("Event");
// 关注
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
respContent = "谢谢您的关注!/n";
respContent += getSubscribeMsg();
}
// 取消关注
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消订阅后用户不会再收到公众账号发送的消息,因此不需要回复
}
// 扫描带参数二维码
else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
// TODO 处理扫描带参数二维码事件
}
// 上报地理位置
else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
// TODO 处理上报地理位置事件
}
// 自定义菜单
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// TODO 处理菜单点击事件
}
}
logStr = "#4# respContent: " + respContent;
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
// 设置文本消息的内容
textMessage.setContent(respContent);
// 将文本消息对象转换成xml
respXml = MessageUtil.messageToXml(textMessage);
logStr = "#5# respXml: " + respXml;
logger.debug(TAG + logStr);
logging = new Logging(f_timestamp.format(Calendar.getInstance().getTime()), "DEBUG", TAG, logStr);
loggingDao.addLogging(logging);
} catch (Exception e) {
e.printStackTrace();
}
return respXml;
}
/**
* 翻译使用指南
*
* @return
*/
public static String getTranslateUsage() {
StringBuffer buffer = new StringBuffer();
// buffer.append(XiaoqUtil.emoji(0xe148)).append("Q译通使用指南").append("\n\n");
buffer.append("Q译通为用户提供专业的多语言翻译服务,目前支持以下翻译方向:").append("\n");
buffer.append(" 中 -> 英").append("\n");
buffer.append(" 英 -> 中").append("\n");
buffer.append(" 日 -> 中").append("\n\n");
buffer.append("使用示例:").append("\n");
buffer.append(" 翻译我是中国人").append("\n");
buffer.append(" 翻译dream").append("\n");
buffer.append(" 翻译さようなら").append("\n\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}
/**
* 歌曲点播使用指南
*
* @return
*/
public static String getMusicUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("歌曲点播操作指南").append("\n\n");
buffer.append("回复:歌曲+歌名").append("\n");
buffer.append("例如:歌曲存在").append("\n");
buffer.append("或者:歌曲存在@汪峰").append("\n\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}
/**
* 歌曲点播使用指南
*
* @return
*/
public static String getUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("历史年月(历史0403)").append("\n");
buffer.append("歌曲歌名(歌曲)").append("\n");
buffer.append("翻译词语(翻译明天)-支持中英日语").append("\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}
/**
* 关注提示语
*
* @return
*/
public static String getSubscribeMsg() {
StringBuffer buffer = new StringBuffer();
buffer.append("您是否有过出门在外四处找ATM或厕所的经历?").append("\n\n");
buffer.append("您是否有过出差在外搜寻美食或娱乐场所的经历?").append("\n\n");
buffer.append("周边搜索为您的出行保驾护航,为您提供专业的周边生活指南,回复“附近”开始体验吧!");
return buffer.toString();
}
/**
* 使用说明
*
* @return
*/
public static String getLocationUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("周边搜索使用说明").append("\n\n");
buffer.append("1)发送地理位置").append("\n");
buffer.append("点击窗口底部的“+”按钮,选择“位置”,点“发送”").append("\n\n");
buffer.append("2)指定关键词搜索").append("\n");
buffer.append("格式:附近+关键词\n例如:附近ATM、附近KTV、附近厕所");
return buffer.toString();
}
} | 0 | 28 | 0 |
36252_1 | public class Main {
/**
* 费用:
* 儿童片 前3天一共1.5 超过3天每天1.5
* 新片 每天3元
* 普通片 前两天 一共2元, 2天后每天1.5
*/
/**
* 积分: 新片且大于一天租赁 2个积分, 其他片每部一积分
*/
public static void main(String[] args) {
Movie movie = new Movie("猫和老鼠", 2);
Rental rental = new Rental(movie, 7);
Movie movie1 = new Movie("功夫", 0);
Rental rental1 = new Rental(movie1, 3);
Movie movie2 = new Movie("水门桥", 1);
Rental rental2 = new Rental(movie2, 2);
Customer customer = new Customer("齐秦");
customer.addRental(rental);
customer.addRental(rental1);
customer.addRental(rental2);
System.out.println(customer.statement());
}
}
/**
* 重构
* 单元测试: 重构的第一步, 写好用例后, 会反复对修改的代码进行测试
* 提取方法: 降低复杂度, 更轻松的修改和移动, 防止代码产生重复
* 移动方法: 移动到合适的类下(领域)
* 重命名符号: 更加语义化, 提高代码的清晰度
* 消除局部变量: 局部变量会被滥用进行传递, 很多时候根本不需要
* 消除额外参数: 返回值在外部进行累加,减少了方法多余的传参, 方法内聚处理并返回
* 方法委托: 常见重构后, 保持调用方稳定不修改, 将新方法在原api上进行调用
* switch的方法应该移动至与对应属性的类, 如果两个对象都可以放置方法, 一定要考虑移动至具有变化和不稳定倾向的类, 另一个不会被影响, 同时, 有变化时, 在一个类中就可以完成处理
* 类上可以定义一些常量, 方便逻辑中判断
* 消除switch: 使用类继承 与 多态的机制
* 总结: 通过不断的封装, 提取, 移动等重构方法, 代码越来越清晰, 并且不再耦合, 每层的调用链非常薄, 在movie类和价格频繁变化时, 依赖他们的类完全无感知, 维护性非常高
*/
| CoderQiQin521/java-refactory | Main.java | 645 | /**
* 积分: 新片且大于一天租赁 2个积分, 其他片每部一积分
*/ | block_comment | zh-cn | public class Main {
/**
* 费用:
* 儿童片 前3天一共1.5 超过3天每天1.5
* 新片 每天3元
* 普通片 前两天 一共2元, 2天后每天1.5
*/
/**
* 积分: <SUF>*/
public static void main(String[] args) {
Movie movie = new Movie("猫和老鼠", 2);
Rental rental = new Rental(movie, 7);
Movie movie1 = new Movie("功夫", 0);
Rental rental1 = new Rental(movie1, 3);
Movie movie2 = new Movie("水门桥", 1);
Rental rental2 = new Rental(movie2, 2);
Customer customer = new Customer("齐秦");
customer.addRental(rental);
customer.addRental(rental1);
customer.addRental(rental2);
System.out.println(customer.statement());
}
}
/**
* 重构
* 单元测试: 重构的第一步, 写好用例后, 会反复对修改的代码进行测试
* 提取方法: 降低复杂度, 更轻松的修改和移动, 防止代码产生重复
* 移动方法: 移动到合适的类下(领域)
* 重命名符号: 更加语义化, 提高代码的清晰度
* 消除局部变量: 局部变量会被滥用进行传递, 很多时候根本不需要
* 消除额外参数: 返回值在外部进行累加,减少了方法多余的传参, 方法内聚处理并返回
* 方法委托: 常见重构后, 保持调用方稳定不修改, 将新方法在原api上进行调用
* switch的方法应该移动至与对应属性的类, 如果两个对象都可以放置方法, 一定要考虑移动至具有变化和不稳定倾向的类, 另一个不会被影响, 同时, 有变化时, 在一个类中就可以完成处理
* 类上可以定义一些常量, 方便逻辑中判断
* 消除switch: 使用类继承 与 多态的机制
* 总结: 通过不断的封装, 提取, 移动等重构方法, 代码越来越清晰, 并且不再耦合, 每层的调用链非常薄, 在movie类和价格频繁变化时, 依赖他们的类完全无感知, 维护性非常高
*/
| 0 | 48 | 0 |
62484_0 | interface Ipeople {
public void eat();
}
public class Person implements Ipeople {
String name;
public Person(String name) {
this.name = name;
}
public static void main(String[] args) {
Ipeople xiaoming = new Person("小明");
xiaoming.eat();
}
public void eat() {
System.out.println(this.name + "在吃东西");
}
}
// 两个类 实现 接口,各自的逻辑不一样
class People implements Ipeople {
public static void main(String[] args) {
int myAge = 20;
Ipeople zhangsan = new People();
zhangsan.eat();
System.out.println(myAge);
}
public void eat() {
System.out.println("张三吃饭中");
}
} | CoderQiQin521/learn-java | Person.java | 200 | // 两个类 实现 接口,各自的逻辑不一样 | line_comment | zh-cn | interface Ipeople {
public void eat();
}
public class Person implements Ipeople {
String name;
public Person(String name) {
this.name = name;
}
public static void main(String[] args) {
Ipeople xiaoming = new Person("小明");
xiaoming.eat();
}
public void eat() {
System.out.println(this.name + "在吃东西");
}
}
// 两个 <SUF>
class People implements Ipeople {
public static void main(String[] args) {
int myAge = 20;
Ipeople zhangsan = new People();
zhangsan.eat();
System.out.println(myAge);
}
public void eat() {
System.out.println("张三吃饭中");
}
} | 0 | 21 | 0 |
39798_12 | package com.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/**
* created by viking on 2018/07/17
* 测试邮件发送controller
*/
@RestController
@RequestMapping("mail")
public class SendMailController {
@Autowired
private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
@RequestMapping("send")
public Object sendMail03(){
MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
MimeMessageHelper mMessageHelper;
Properties prop = new Properties();
String from;
try {
//从配置文件中拿到发件人邮箱地址
prop.load(this.getClass().getResourceAsStream("/config/mail.properties"));
from = prop.get("mail.smtp.username")+"";
mMessageHelper=new MimeMessageHelper(mMessage,true);
mMessageHelper.setFrom(from);//发件人邮箱
mMessageHelper.setTo("[email protected]");//收件人邮箱
mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题
mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" +
"<a href='https://blog.csdn.net/Mr__Viking'>打开我的博客主页</a><br/>" +
"<img src='cid:fengye'>",true);//邮件的文本内容,true表示文本以html格式打开
File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片
FileSystemResource resource=new FileSystemResource(file);
mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用
mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件
javaMailSender.send(mMessage);//发送邮件
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "发送成功";
}
public void sendMail(){
SimpleMailMessage smm=new SimpleMailMessage();
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("收件人的邮件地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有");//邮件的内容
javaMailSender.send(smm);//发送邮件
System.out.println("发送成功");
}
public void sendMail01(){
/**
* 使用另一种的方式发送邮件,然后在邮件 使html格式生效
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=new MimeMessageHelper(mm);
try {
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈,猜猜我是谁?");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有<br><a href='http://www.baidu.com'>去百度吧!</a>",true);//邮件的内容 true 是代表的html格式生效
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
public void sendMail02(){
/**
* 使用另一种的方式发送邮件,然后在邮件,发送一个照片
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=null;
try {
smm=new MimeMessageHelper(mm,true);
smm.setFrom("发送人的邮件");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("你丫的吃了狗屎了,你还不发送成功");//邮件的标题 这里多此测试 有可能会导致报错,说你发送的邮件内容不合法,注意看报错码,然后在去找报错码的意思,我这里也是报错了的,我是在他们官网上面看到的
smm.setText("山东凯撒第三款<a href='http://www.baidu.com'>去百度吧!</a><img src='cid:identifier1234'>",true);//邮件的内容 true 是代表的html格式生效
File file=new File("D:/1.jpg");//发送邮件的图片
FileSystemResource resource=new FileSystemResource(file);
smm.addInline("identifier1234", resource);//这里指定一个id,在上面引用
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
}
| CoderViking/SSMDemo | src/main/java/com/ssm/controller/SendMailController.java | 1,294 | //发送邮件 | line_comment | zh-cn | package com.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/**
* created by viking on 2018/07/17
* 测试邮件发送controller
*/
@RestController
@RequestMapping("mail")
public class SendMailController {
@Autowired
private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
@RequestMapping("send")
public Object sendMail03(){
MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
MimeMessageHelper mMessageHelper;
Properties prop = new Properties();
String from;
try {
//从配置文件中拿到发件人邮箱地址
prop.load(this.getClass().getResourceAsStream("/config/mail.properties"));
from = prop.get("mail.smtp.username")+"";
mMessageHelper=new MimeMessageHelper(mMessage,true);
mMessageHelper.setFrom(from);//发件人邮箱
mMessageHelper.setTo("[email protected]");//收件人邮箱
mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题
mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" +
"<a href='https://blog.csdn.net/Mr__Viking'>打开我的博客主页</a><br/>" +
"<img src='cid:fengye'>",true);//邮件的文本内容,true表示文本以html格式打开
File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片
FileSystemResource resource=new FileSystemResource(file);
mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用
mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件
javaMailSender.send(mMessage);//发送 <SUF>
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "发送成功";
}
public void sendMail(){
SimpleMailMessage smm=new SimpleMailMessage();
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("收件人的邮件地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有");//邮件的内容
javaMailSender.send(smm);//发送邮件
System.out.println("发送成功");
}
public void sendMail01(){
/**
* 使用另一种的方式发送邮件,然后在邮件 使html格式生效
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=new MimeMessageHelper(mm);
try {
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈,猜猜我是谁?");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有<br><a href='http://www.baidu.com'>去百度吧!</a>",true);//邮件的内容 true 是代表的html格式生效
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
public void sendMail02(){
/**
* 使用另一种的方式发送邮件,然后在邮件,发送一个照片
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=null;
try {
smm=new MimeMessageHelper(mm,true);
smm.setFrom("发送人的邮件");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("你丫的吃了狗屎了,你还不发送成功");//邮件的标题 这里多此测试 有可能会导致报错,说你发送的邮件内容不合法,注意看报错码,然后在去找报错码的意思,我这里也是报错了的,我是在他们官网上面看到的
smm.setText("山东凯撒第三款<a href='http://www.baidu.com'>去百度吧!</a><img src='cid:identifier1234'>",true);//邮件的内容 true 是代表的html格式生效
File file=new File("D:/1.jpg");//发送邮件的图片
FileSystemResource resource=new FileSystemResource(file);
smm.addInline("identifier1234", resource);//这里指定一个id,在上面引用
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
}
| 1 | 6 | 1 |
35952_5 | package com.thinkinginjava;
import com.commonsjar.beanutils.User;
import org.junit.Test;
import java.util.Random;
public class B_Operator {
@Test
public void t(){
String a = "aaa";
a += "bbb"; //string也支持+=
System.out.println(a);
//算数运算符,先乘除后加减
System.out.println(1+3*4/6-2);
System.out.println(1+4/4*1000-2);
//rand
Random rand = new Random(47);
int j = rand.nextInt(100)+1;
System.out.println(j);
int i = 1;
System.out.println(i++);
//用小写l容易和1混淆,使用大写L
long L1 = 1L;
System.out.println(L1);
}
@Test
public void charTest(){
char x = 'x';
char y = 'y';
System.out.println(x*y);
System.out.println('2'*'6');
//char c26 = x*y; 报错,char运算后是int
char c26 = 'x'*'y'; //居然又不报错
System.out.println(x/y);
System.out.println(x%y);
System.out.println(x+y);
System.out.println(x-y);
byte b1 = 1;
byte b2 = 2;
//byte b12 = b1+b2; 报错,byte运算后是int
short s1 = 1;
short s2 = 2;
//short s12 = s1+s2; 报错,short运算后是int
System.out.println(Float.MAX_VALUE);
//不会报错,但结果是1,Integer最大值相乘已经超出了int的范围
System.out.println(Integer.MAX_VALUE * Integer.MAX_VALUE);
}
public static final String h = "outFill";
@Test
public void teste(){
String h1 = "outFill";
String h2 = "outFill";
System.out.println(h1 == h2);
User user = new User();
user.setId("outFill");
System.out.println(A_String.TEST_H == user.getId());
}
//斐波那契数列
public int fibonacciSequence(int i){
if(i == 2){
return 1;
}else if(i < 2){
return 1;
}
return fibonacciSequence(i-1) + fibonacciSequence(i-2);
}
@Test
public void testf(){
System.out.println(fibonacciSequence(9));
}
}
| CodingSoldier/java-learn | note/src/main/java/com/thinkinginjava/B_Operator.java | 674 | //居然又不报错 | line_comment | zh-cn | package com.thinkinginjava;
import com.commonsjar.beanutils.User;
import org.junit.Test;
import java.util.Random;
public class B_Operator {
@Test
public void t(){
String a = "aaa";
a += "bbb"; //string也支持+=
System.out.println(a);
//算数运算符,先乘除后加减
System.out.println(1+3*4/6-2);
System.out.println(1+4/4*1000-2);
//rand
Random rand = new Random(47);
int j = rand.nextInt(100)+1;
System.out.println(j);
int i = 1;
System.out.println(i++);
//用小写l容易和1混淆,使用大写L
long L1 = 1L;
System.out.println(L1);
}
@Test
public void charTest(){
char x = 'x';
char y = 'y';
System.out.println(x*y);
System.out.println('2'*'6');
//char c26 = x*y; 报错,char运算后是int
char c26 = 'x'*'y'; //居然 <SUF>
System.out.println(x/y);
System.out.println(x%y);
System.out.println(x+y);
System.out.println(x-y);
byte b1 = 1;
byte b2 = 2;
//byte b12 = b1+b2; 报错,byte运算后是int
short s1 = 1;
short s2 = 2;
//short s12 = s1+s2; 报错,short运算后是int
System.out.println(Float.MAX_VALUE);
//不会报错,但结果是1,Integer最大值相乘已经超出了int的范围
System.out.println(Integer.MAX_VALUE * Integer.MAX_VALUE);
}
public static final String h = "outFill";
@Test
public void teste(){
String h1 = "outFill";
String h2 = "outFill";
System.out.println(h1 == h2);
User user = new User();
user.setId("outFill");
System.out.println(A_String.TEST_H == user.getId());
}
//斐波那契数列
public int fibonacciSequence(int i){
if(i == 2){
return 1;
}else if(i < 2){
return 1;
}
return fibonacciSequence(i-1) + fibonacciSequence(i-2);
}
@Test
public void testf(){
System.out.println(fibonacciSequence(9));
}
}
| 0 | 8 | 0 |
61479_0 | package src;
import static src.Util.obj2int;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.exadel.flamingo.flex.amf.AMF0Body;
import flex.messaging.io.ASObject;
public class Garden {
public static final int[] MIN_LEVEL = new int[]{1,21,41,51,61,71,81,86,91,96,101,106,111,116,121};
public static final int[] MAX_LEVEL = new int[]{20,40,50,60,70,80,85,90,95,100,105,110,115,120,125};
private static int gradeToIndex(int grade){
if (grade>=1 && grade<=40) {
return (grade-1)/20;
}
if (grade>=41 && grade<=80) {
return (grade-1)/10-2;
}
if (grade>=81 && grade<=125) {
return (grade-1)/5-10;
}
return -1;
}
private static List<Integer> preferGrades = null;
private static String plantFilename = null;
private static int remainBeatCount = 5;
private static int remainToBeat = 5;
public static Document lookGarden(int grade, int pvzid, String name){
Log.logln("查看lv.%d %s(%d)的花园".formatted(grade,name,pvzid));
byte[] response = Request.sendGetRequest("/pvz/index.php/garden/index/id/%d/sig/c3f56017a56ae0e93716fdffbb3ade91?%d".formatted(
pvzid, new Date().getTime()
));
Document document = Util.parseXml(response);
return document;
}
private static int getRemainBeatCount(Document gardenDoc){
Element garden = (Element) gardenDoc.getElementsByTagName("garden").item(0);
return Integer.parseInt(garden.getAttribute("cn"));
}
private static List<Garden.Monster> getMonsters(Document gardenDoc){
Element monster = (Element) gardenDoc.getElementsByTagName("monster").item(0);
NodeList monList = monster.getElementsByTagName("mon");
List<Monster> res = new ArrayList<>();
for (int i = 0; i < monList.getLength(); i++) {
if (monList.item(i).getNodeType()==Node.ELEMENT_NODE){
Monster monst = new Monster((Element)monList.item(i));
res.add(monst);
}
}
return res;
}
static class Monster {
final int ownerId;
final int lx;
final int ly;
final String name;
public Monster(Element ele){
name = ele.getAttribute("name");
ownerId = Integer.parseInt(ele.getAttribute("owid"));
Element position = (Element)ele.getElementsByTagName("position").item(0);
lx = Integer.parseInt(position.getAttribute("lx"));
ly = Integer.parseInt(position.getAttribute("ly"));
}
}
public static boolean beatOnce(Monster monster){
Object[] value = new Object[4];
value[0] = monster.ownerId;
value[1] = monster.lx;
value[2] = monster.ly;
List<Integer> plants = Util.readIntegersFromFile(plantFilename);
if (plantFilename==null || plants==null) {
Log.logln("请先设置好花园战斗的植物!");
return false;
}
value[3] = Util.integerArr2int(plants.toArray());
byte[] req = Util.encodeAMF("api.garden.challenge", "/1", value);
Log.log("挑战%s(%d,%d)".formatted(monster.name,monster.lx,monster.ly));
byte[] response = Request.sendPostAmf(req, true);
AMF0Body body = Util.decodeAMF(response).getBody(0);
if(Response.isOnStatusException(body, true)){
return false;
}
ASObject obj = (ASObject)body.getValue();
boolean is_winning = (Boolean)obj.get("is_winning");
if (is_winning) {
int exp = obj2int(obj.get("exp"));
Log.println(" 成功,获得%d经验".formatted(exp));
String awards_key = obj.get("awards_key").toString();
GeneralBattle.getAward(awards_key);
remainToBeat--;
}else{
Log.println(" 失败");
}
return true;
}
public static boolean checkBeatOneGarden(int grade, int pvzid, String name){
Document gardenDoc = lookGarden(grade,pvzid, name);
return beatOneGarden(gardenDoc);
}
public static boolean beatOneGarden(Document gardenDoc){
List<Monster> monsters = getMonsters(gardenDoc);
int actualCount = Math.min(remainToBeat, monsters.size());
for (int i = 0; i < actualCount; i++) {
if (!beatOnce(monsters.get(i))) {
return false;
}
}
return true;
}
public static boolean gardenBattleRepeat(int count){
User me = User.getUser();
List<Friend> friendList = me.friends;
Document myGarden = lookGarden(me.grade,me.id, me.name);
remainBeatCount = getRemainBeatCount(myGarden);
if (count==-1) remainToBeat=remainBeatCount;
else remainToBeat=Math.min(count, remainBeatCount);
if (preferGrades==null) {
Log.logln("请先设置花园打怪等级优先顺序!");
return false;
}
// 按照设置的等级顺序去打
for (Integer index : preferGrades) {
if (remainToBeat<=0) return true;
if (me.grade >= MIN_LEVEL[index] && me.grade <= MAX_LEVEL[index]) {
if (!beatOneGarden(myGarden)){
return false;
}
}
List<Friend> tofight = friendList.stream().filter(new Predicate<Friend>() {
@Override
public boolean test(Friend t) {
return t.grade>=MIN_LEVEL[index]&& t.grade <= MAX_LEVEL[index];
}
}).toList();
for (Friend friend : tofight) {
if (remainToBeat<=0) return true;
if (!checkBeatOneGarden(friend.grade, friend.id_pvz, friend.name)){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
if (args.length==2&&args[0].equals("battle")) {
int count;
if (args[1].equals("auto")) {
count=-1;
}else{
count=Integer.parseInt(args[1]);
}
gardenBattleRepeat(count);
return;
}
else if (args.length>=1 && args[0].equals("bgrade")){
preferGrades = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
int tmpgrade = Integer.parseInt(args[i]);
preferGrades.add(gradeToIndex(tmpgrade));
}
return;
}
else if (args.length==2 && args[0].equals("bplant")){
plantFilename = args[1];
return;
}
System.out.println("args: battle auto|<count>");
System.out.println("or : bplant <plant_filename>");
System.out.println("or : bgrade <grade_to_beat>...");
}
} | CodingZn/PvzScript | src/Garden.java | 1,936 | // 按照设置的等级顺序去打 | line_comment | zh-cn | package src;
import static src.Util.obj2int;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.exadel.flamingo.flex.amf.AMF0Body;
import flex.messaging.io.ASObject;
public class Garden {
public static final int[] MIN_LEVEL = new int[]{1,21,41,51,61,71,81,86,91,96,101,106,111,116,121};
public static final int[] MAX_LEVEL = new int[]{20,40,50,60,70,80,85,90,95,100,105,110,115,120,125};
private static int gradeToIndex(int grade){
if (grade>=1 && grade<=40) {
return (grade-1)/20;
}
if (grade>=41 && grade<=80) {
return (grade-1)/10-2;
}
if (grade>=81 && grade<=125) {
return (grade-1)/5-10;
}
return -1;
}
private static List<Integer> preferGrades = null;
private static String plantFilename = null;
private static int remainBeatCount = 5;
private static int remainToBeat = 5;
public static Document lookGarden(int grade, int pvzid, String name){
Log.logln("查看lv.%d %s(%d)的花园".formatted(grade,name,pvzid));
byte[] response = Request.sendGetRequest("/pvz/index.php/garden/index/id/%d/sig/c3f56017a56ae0e93716fdffbb3ade91?%d".formatted(
pvzid, new Date().getTime()
));
Document document = Util.parseXml(response);
return document;
}
private static int getRemainBeatCount(Document gardenDoc){
Element garden = (Element) gardenDoc.getElementsByTagName("garden").item(0);
return Integer.parseInt(garden.getAttribute("cn"));
}
private static List<Garden.Monster> getMonsters(Document gardenDoc){
Element monster = (Element) gardenDoc.getElementsByTagName("monster").item(0);
NodeList monList = monster.getElementsByTagName("mon");
List<Monster> res = new ArrayList<>();
for (int i = 0; i < monList.getLength(); i++) {
if (monList.item(i).getNodeType()==Node.ELEMENT_NODE){
Monster monst = new Monster((Element)monList.item(i));
res.add(monst);
}
}
return res;
}
static class Monster {
final int ownerId;
final int lx;
final int ly;
final String name;
public Monster(Element ele){
name = ele.getAttribute("name");
ownerId = Integer.parseInt(ele.getAttribute("owid"));
Element position = (Element)ele.getElementsByTagName("position").item(0);
lx = Integer.parseInt(position.getAttribute("lx"));
ly = Integer.parseInt(position.getAttribute("ly"));
}
}
public static boolean beatOnce(Monster monster){
Object[] value = new Object[4];
value[0] = monster.ownerId;
value[1] = monster.lx;
value[2] = monster.ly;
List<Integer> plants = Util.readIntegersFromFile(plantFilename);
if (plantFilename==null || plants==null) {
Log.logln("请先设置好花园战斗的植物!");
return false;
}
value[3] = Util.integerArr2int(plants.toArray());
byte[] req = Util.encodeAMF("api.garden.challenge", "/1", value);
Log.log("挑战%s(%d,%d)".formatted(monster.name,monster.lx,monster.ly));
byte[] response = Request.sendPostAmf(req, true);
AMF0Body body = Util.decodeAMF(response).getBody(0);
if(Response.isOnStatusException(body, true)){
return false;
}
ASObject obj = (ASObject)body.getValue();
boolean is_winning = (Boolean)obj.get("is_winning");
if (is_winning) {
int exp = obj2int(obj.get("exp"));
Log.println(" 成功,获得%d经验".formatted(exp));
String awards_key = obj.get("awards_key").toString();
GeneralBattle.getAward(awards_key);
remainToBeat--;
}else{
Log.println(" 失败");
}
return true;
}
public static boolean checkBeatOneGarden(int grade, int pvzid, String name){
Document gardenDoc = lookGarden(grade,pvzid, name);
return beatOneGarden(gardenDoc);
}
public static boolean beatOneGarden(Document gardenDoc){
List<Monster> monsters = getMonsters(gardenDoc);
int actualCount = Math.min(remainToBeat, monsters.size());
for (int i = 0; i < actualCount; i++) {
if (!beatOnce(monsters.get(i))) {
return false;
}
}
return true;
}
public static boolean gardenBattleRepeat(int count){
User me = User.getUser();
List<Friend> friendList = me.friends;
Document myGarden = lookGarden(me.grade,me.id, me.name);
remainBeatCount = getRemainBeatCount(myGarden);
if (count==-1) remainToBeat=remainBeatCount;
else remainToBeat=Math.min(count, remainBeatCount);
if (preferGrades==null) {
Log.logln("请先设置花园打怪等级优先顺序!");
return false;
}
// 按照 <SUF>
for (Integer index : preferGrades) {
if (remainToBeat<=0) return true;
if (me.grade >= MIN_LEVEL[index] && me.grade <= MAX_LEVEL[index]) {
if (!beatOneGarden(myGarden)){
return false;
}
}
List<Friend> tofight = friendList.stream().filter(new Predicate<Friend>() {
@Override
public boolean test(Friend t) {
return t.grade>=MIN_LEVEL[index]&& t.grade <= MAX_LEVEL[index];
}
}).toList();
for (Friend friend : tofight) {
if (remainToBeat<=0) return true;
if (!checkBeatOneGarden(friend.grade, friend.id_pvz, friend.name)){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
if (args.length==2&&args[0].equals("battle")) {
int count;
if (args[1].equals("auto")) {
count=-1;
}else{
count=Integer.parseInt(args[1]);
}
gardenBattleRepeat(count);
return;
}
else if (args.length>=1 && args[0].equals("bgrade")){
preferGrades = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
int tmpgrade = Integer.parseInt(args[i]);
preferGrades.add(gradeToIndex(tmpgrade));
}
return;
}
else if (args.length==2 && args[0].equals("bplant")){
plantFilename = args[1];
return;
}
System.out.println("args: battle auto|<count>");
System.out.println("or : bplant <plant_filename>");
System.out.println("or : bgrade <grade_to_beat>...");
}
} | 1 | 14 | 1 |
51878_8 | package com.chenx;
import com.chenx.utils.UUIDUtils;
import lombok.Data;
/**
* Created by Administrator on 2017/3/2 0002.
*/
public final class YouHaoConstant {
//旅单用户状态(0-加入,1-退出)
public static final int TOUR_USER_STATE_JOIN = 0;
public static final int TOUR_USER_STATE_EXIT = 1;
//旅单用户角色(0-发起者,1-拍摄,2-老司机,3-翻译,4-百科全书,5-后勤保障,6-吃瓜群众,7-行程指挥,8-砍价能手)
public static final int TOUR_USER_ROLE_AUTHOR = 0;
public static final int TOUR_USER_ROLE_PHOTOR = 1;
public static final int TOUR_USER_ROLE_DRIVER = 2;
public static final int TOUR_USER_ROLE_TRANSLATOR = 3;
public static final int TOUR_USER_ROLE_ENCYCLOPEDIA= 4;
public static final int TOUR_USER_ROLE_PROTECTOR = 5;
public static final int TOUR_USER_ROLE_WATCHER = 6;
public static final int TOUR_USER_ROLE_LEADER = 7;
public static final int TOUR_USER_ROLE_BARGAINER = 8;
//旅单图片类型
public static final int TOUR_IMAGE = 1; //说明图片
public static final int TOUR_COVER = 2; //封面图片
// 默认头像地址
public static final String DEFAULT_USER_IMG = "upload/default/user/images/default_head.png";
// 默认封面地址
public static final String DEFAULT_COVER_IMG = "upload/default/tour/cover/default_cover.jpg";
// 账户登录平台 1、前台 2、管理后台
public static final int LOGIN_TYPE_FRONT = 1;
public static final int LOGIN_TYPE_ADMIN = 2;
// 账户类型 1、邮箱 2、手机号
public static final int ACCOUNT_TYPE_EMAIL = 1;
public static final int ACCOUNT_TYPE_PHONE = 2;
// 用户状态 1、启用 2、禁用 3、删除
public static final int USER_STATUS_ENABLE = 1;
public static final int USER_STATUS_FORBID = 2;
public static final int USER_STATUS_DELETE = 3;
/** 验证码失效时间 3分钟 **/
public static final Long VALIDATION_CODE_EXPIRATION_TIME = 180000L;
}
| CoffeeHi/youhao-back | src/main/java/com/chenx/YouHaoConstant.java | 649 | // 账户登录平台 1、前台 2、管理后台 | line_comment | zh-cn | package com.chenx;
import com.chenx.utils.UUIDUtils;
import lombok.Data;
/**
* Created by Administrator on 2017/3/2 0002.
*/
public final class YouHaoConstant {
//旅单用户状态(0-加入,1-退出)
public static final int TOUR_USER_STATE_JOIN = 0;
public static final int TOUR_USER_STATE_EXIT = 1;
//旅单用户角色(0-发起者,1-拍摄,2-老司机,3-翻译,4-百科全书,5-后勤保障,6-吃瓜群众,7-行程指挥,8-砍价能手)
public static final int TOUR_USER_ROLE_AUTHOR = 0;
public static final int TOUR_USER_ROLE_PHOTOR = 1;
public static final int TOUR_USER_ROLE_DRIVER = 2;
public static final int TOUR_USER_ROLE_TRANSLATOR = 3;
public static final int TOUR_USER_ROLE_ENCYCLOPEDIA= 4;
public static final int TOUR_USER_ROLE_PROTECTOR = 5;
public static final int TOUR_USER_ROLE_WATCHER = 6;
public static final int TOUR_USER_ROLE_LEADER = 7;
public static final int TOUR_USER_ROLE_BARGAINER = 8;
//旅单图片类型
public static final int TOUR_IMAGE = 1; //说明图片
public static final int TOUR_COVER = 2; //封面图片
// 默认头像地址
public static final String DEFAULT_USER_IMG = "upload/default/user/images/default_head.png";
// 默认封面地址
public static final String DEFAULT_COVER_IMG = "upload/default/tour/cover/default_cover.jpg";
// 账户 <SUF>
public static final int LOGIN_TYPE_FRONT = 1;
public static final int LOGIN_TYPE_ADMIN = 2;
// 账户类型 1、邮箱 2、手机号
public static final int ACCOUNT_TYPE_EMAIL = 1;
public static final int ACCOUNT_TYPE_PHONE = 2;
// 用户状态 1、启用 2、禁用 3、删除
public static final int USER_STATUS_ENABLE = 1;
public static final int USER_STATUS_FORBID = 2;
public static final int USER_STATUS_DELETE = 3;
/** 验证码失效时间 3分钟 **/
public static final Long VALIDATION_CODE_EXPIRATION_TIME = 180000L;
}
| 0 | 26 | 0 |
48522_4 | import java.util.Arrays;
public class LeetCode1046 {
//有一堆石头,每块石头的重量都是正整数。
//
//每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
//
//如果 x == y,那么两块石头都会被完全粉碎;
//如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
//最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
public int lastStoneWeight(int[] stones) {
while(stones.length!=1) {
int index=stones.length-1;
mergeSort(stones);
stones[index-1]=stones[index]-stones[index-1];
stones=Arrays.copyOf(stones,stones.length-1);
}
return stones[0];
}
public void mergeSort(int[] arr) {
merge(arr,0,arr.length-1);
}
public void merge(int[] arr,int start,int end) {
if(start>=end) {
return ;
}
int mid=start+(end-start)/2;
merge(arr,start,mid);
merge(arr,mid+1,end);
mergeFunc(arr,start,end,mid);
}
public void mergeFunc(int[] arr,int left,int right,int mid) {
int s1=left;
int s2=mid+1;
int e1=mid;
int e2=right;
int index=0;
int[] newArr=new int[right-left+1];
while(s1<=e1&&s2<=e2) {
if(arr[s1]<=arr[s2]) {
newArr[index]=arr[s1];
s1++;
index++;
} else {
newArr[index]=arr[s2];
s2++;
index++;
}
}
while(s1<=e1) {
newArr[index++]=arr[s1++];
}
while(s2<=e2) {
newArr[index++]=arr[s2++];
}
for(int i=0;i<newArr.length;i++) {
arr[i+left]=newArr[i];
}
}
}
| ColdGoose77/Java-ds-code | LeetCode1046.java | 612 | //最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。 | line_comment | zh-cn | import java.util.Arrays;
public class LeetCode1046 {
//有一堆石头,每块石头的重量都是正整数。
//
//每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
//
//如果 x == y,那么两块石头都会被完全粉碎;
//如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
//最后 <SUF>
public int lastStoneWeight(int[] stones) {
while(stones.length!=1) {
int index=stones.length-1;
mergeSort(stones);
stones[index-1]=stones[index]-stones[index-1];
stones=Arrays.copyOf(stones,stones.length-1);
}
return stones[0];
}
public void mergeSort(int[] arr) {
merge(arr,0,arr.length-1);
}
public void merge(int[] arr,int start,int end) {
if(start>=end) {
return ;
}
int mid=start+(end-start)/2;
merge(arr,start,mid);
merge(arr,mid+1,end);
mergeFunc(arr,start,end,mid);
}
public void mergeFunc(int[] arr,int left,int right,int mid) {
int s1=left;
int s2=mid+1;
int e1=mid;
int e2=right;
int index=0;
int[] newArr=new int[right-left+1];
while(s1<=e1&&s2<=e2) {
if(arr[s1]<=arr[s2]) {
newArr[index]=arr[s1];
s1++;
index++;
} else {
newArr[index]=arr[s2];
s2++;
index++;
}
}
while(s1<=e1) {
newArr[index++]=arr[s1++];
}
while(s2<=e2) {
newArr[index++]=arr[s2++];
}
for(int i=0;i<newArr.length;i++) {
arr[i+left]=newArr[i];
}
}
}
| 0 | 40 | 0 |
23083_3 | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author WuBiao
* @date 2020/4/2 19:51
*/
public class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap<>();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);//统计每个单词出现的次数
}
List<String>[] buckets = new List[words.length + 1];
for (String word : count.keySet()) {//把词放在数组根据频率放在数组里
int num = count.get(word);
if (buckets[num] == null) {
buckets[num] = new ArrayList<>();
}
buckets[num].add(word);
}
List<String> res = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0; i--) {
if (buckets[i] == null) {
continue;
}
buckets[i].sort(String::compareTo);//同一个频率按照字母序排序
if (buckets[i].size() <= k - res.size()) {//能放下的话全放下
res.addAll(buckets[i]);
} else {//放不下的话看能放下多少
res.addAll(buckets[i].subList(0, k - res.size()));
}
}
return res;
}
} | ColdPepsi/Leetcode | 692-前K个高频单词/src/main/java/Solution.java | 364 | //同一个频率按照字母序排序 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author WuBiao
* @date 2020/4/2 19:51
*/
public class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap<>();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);//统计每个单词出现的次数
}
List<String>[] buckets = new List[words.length + 1];
for (String word : count.keySet()) {//把词放在数组根据频率放在数组里
int num = count.get(word);
if (buckets[num] == null) {
buckets[num] = new ArrayList<>();
}
buckets[num].add(word);
}
List<String> res = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0; i--) {
if (buckets[i] == null) {
continue;
}
buckets[i].sort(String::compareTo);//同一 <SUF>
if (buckets[i].size() <= k - res.size()) {//能放下的话全放下
res.addAll(buckets[i]);
} else {//放不下的话看能放下多少
res.addAll(buckets[i].subList(0, k - res.size()));
}
}
return res;
}
} | 1 | 14 | 1 |
54715_0 | /*java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例、饿汉式单例、登记式单例三种。
单例模式有一下特点:
1、单例类只能有一个实例。
2、单例类必须自己自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、
缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。
每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,
系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。
*/
public class Singleton{
private static Singleton uniqueInstance = null;
private Singleton(){
}
public static Singleton getInstance(){
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
//other methods
} | Colin6618/puzzles | java/Sinleton.java | 329 | /*java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例、饿汉式单例、登记式单例三种。
单例模式有一下特点:
1、单例类只能有一个实例。
2、单例类必须自己自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、
缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。
每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,
系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。
*/ | block_comment | zh-cn | /*jav <SUF>*/
public class Singleton{
private static Singleton uniqueInstance = null;
private Singleton(){
}
public static Singleton getInstance(){
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
//other methods
} | 0 | 375 | 0 |
32026_11 | package lee.devis.joker;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import java.util.ArrayList;
import lee.devis.joker.MyView.PathView;
import lee.devis.joker.utility.MyToaster;
public class MainActivity extends FragmentActivity implements NewestFragment.OnFragmentInteractionListener,
HotFragment.OnFragmentInteractionListener, PictureFragment.OnFragmentInteractionListener,
lee.devis.joker.MyView.PathView.OnItemClickListener {
// 页面列表
private ArrayList<android.support.v4.app.Fragment> fragmentList;
// 标题列表
ArrayList<String> titleList = new ArrayList<String>();
private PagerTitleStrip pagerTitleStrip;
private long myTime;// 两次返回的间隔
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
/* 通过pagerTabStrip可以设置标题的属性 */
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab);
// 设置下划线的颜色
// pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.holo_green_dark));
pagerTabStrip.setTabIndicatorColor(Color.RED);
pagerTabStrip.setPadding(18, 18, 18, 18);
// 文字颜色
pagerTabStrip.setTextColor(Color.WHITE);
// 设置背景的颜色
pagerTabStrip.setBackgroundColor(Color.BLACK);
// pagerTitleStrip=(PagerTitleStrip) findViewById(R.id.pagertab);
// //设置背景的颜色
// pagerTitleStrip.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
NewestFragment newestFragment = new NewestFragment();
HotFragment hotFragment = new HotFragment();
PictureFragment pictureFragment = new PictureFragment();
fragmentList = new ArrayList<android.support.v4.app.Fragment>();
fragmentList.add(newestFragment);
fragmentList.add(hotFragment);
fragmentList.add(pictureFragment);
titleList.add("最新糗事");
titleList.add("最热段子");
titleList.add("图说真相");
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyViewPagerAdapter(fragmentManager));
viewPager.setOffscreenPageLimit(3);
setupView();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return fragmentList.get(arg0);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
// 双击退出
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if ((System.currentTimeMillis() - myTime) > 2000) {// 两次按下的时间间隔如果小于2秒就退出,大于2秒就再次提示
MyToaster.showToast(this, "再按一次返回键退出程序");
myTime = System.currentTimeMillis();// 获取当前系统时间
} else {
MyToaster.showToast(this, "客观慢走,欢迎再来哟~");
finish();// 退出应用
// System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// path菜单初始化
private void setupView() {
PathView mPathView = (PathView) findViewById(R.id.mPathView);
ImageButton startMenu = new ImageButton(this);
startMenu.setBackgroundResource(R.drawable.start_menu_btn);
mPathView.setStartMenu(startMenu);
int[] drawableIds = new int[] { R.drawable.menu_contact, R.drawable.menu_background, R.drawable.menu_native,
R.drawable.menu_net };
View[] items = new View[drawableIds.length];
for (int i = 0; i < drawableIds.length; i++) {
ImageButton button = new ImageButton(this);
button.setBackgroundResource(drawableIds[i]);
items[i] = button;
}
mPathView.setItems(items);
mPathView.setOnItemClickListener(this);
}
@Override
public void onItemClick(View view, int position) {
}
}
| ColorfulCat/Joker | src/lee/devis/joker/MainActivity.java | 1,365 | // 双击退出 | line_comment | zh-cn | package lee.devis.joker;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import java.util.ArrayList;
import lee.devis.joker.MyView.PathView;
import lee.devis.joker.utility.MyToaster;
public class MainActivity extends FragmentActivity implements NewestFragment.OnFragmentInteractionListener,
HotFragment.OnFragmentInteractionListener, PictureFragment.OnFragmentInteractionListener,
lee.devis.joker.MyView.PathView.OnItemClickListener {
// 页面列表
private ArrayList<android.support.v4.app.Fragment> fragmentList;
// 标题列表
ArrayList<String> titleList = new ArrayList<String>();
private PagerTitleStrip pagerTitleStrip;
private long myTime;// 两次返回的间隔
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
/* 通过pagerTabStrip可以设置标题的属性 */
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab);
// 设置下划线的颜色
// pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.holo_green_dark));
pagerTabStrip.setTabIndicatorColor(Color.RED);
pagerTabStrip.setPadding(18, 18, 18, 18);
// 文字颜色
pagerTabStrip.setTextColor(Color.WHITE);
// 设置背景的颜色
pagerTabStrip.setBackgroundColor(Color.BLACK);
// pagerTitleStrip=(PagerTitleStrip) findViewById(R.id.pagertab);
// //设置背景的颜色
// pagerTitleStrip.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
NewestFragment newestFragment = new NewestFragment();
HotFragment hotFragment = new HotFragment();
PictureFragment pictureFragment = new PictureFragment();
fragmentList = new ArrayList<android.support.v4.app.Fragment>();
fragmentList.add(newestFragment);
fragmentList.add(hotFragment);
fragmentList.add(pictureFragment);
titleList.add("最新糗事");
titleList.add("最热段子");
titleList.add("图说真相");
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyViewPagerAdapter(fragmentManager));
viewPager.setOffscreenPageLimit(3);
setupView();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return fragmentList.get(arg0);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
// 双击 <SUF>
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if ((System.currentTimeMillis() - myTime) > 2000) {// 两次按下的时间间隔如果小于2秒就退出,大于2秒就再次提示
MyToaster.showToast(this, "再按一次返回键退出程序");
myTime = System.currentTimeMillis();// 获取当前系统时间
} else {
MyToaster.showToast(this, "客观慢走,欢迎再来哟~");
finish();// 退出应用
// System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// path菜单初始化
private void setupView() {
PathView mPathView = (PathView) findViewById(R.id.mPathView);
ImageButton startMenu = new ImageButton(this);
startMenu.setBackgroundResource(R.drawable.start_menu_btn);
mPathView.setStartMenu(startMenu);
int[] drawableIds = new int[] { R.drawable.menu_contact, R.drawable.menu_background, R.drawable.menu_native,
R.drawable.menu_net };
View[] items = new View[drawableIds.length];
for (int i = 0; i < drawableIds.length; i++) {
ImageButton button = new ImageButton(this);
button.setBackgroundResource(drawableIds[i]);
items[i] = button;
}
mPathView.setItems(items);
mPathView.setOnItemClickListener(this);
}
@Override
public void onItemClick(View view, int position) {
}
}
| 1 | 7 | 1 |
52211_6 | //package coloryr.allmusic.sql;
//
//import coloryr.allmusic.AllMusic;
//import org.apache.commons.dbcp2.BasicDataSource;
//
//import javax.sql.DataSource;
//import java.sql.*;
//
//public abstract class MysqlConn implements IEconomy{
// //建立连接的驱动驱动名称
// public final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
// //最大空闲链接
// private final int MAX_IDLE = 20;
// //最大空闲连接
// private final int MinIdle = 8;
// //最大等待时间
// private final long MAX_WAIT_Millis = 5000;
// //最大活动链接
// private final int MAX_TOTAl = 5;
// //初始化时链接池的数量
// private final int INITIAL_SIZE = 10;
// //一个被抛弃连接可以被移除的超时时间
// private final int RemoveAbandonedTimeout = 180;
// //只会发现当前连接失效,再创建一个连接供当前查询使用
// private final boolean TOBESTNORROW = true;
// private BasicDataSource DATA_SOURCE;
//
// public boolean start() {
// try {
// DATA_SOURCE = new BasicDataSource();
// DATA_SOURCE.setDriverClassName(DRIVER_CLASS_NAME);
// DATA_SOURCE.setUrl(AllMusic.getConfig().getEconomys().getMysqlUrl());
// DATA_SOURCE.setMaxTotal(MAX_TOTAl);
// DATA_SOURCE.setInitialSize(INITIAL_SIZE);
// DATA_SOURCE.setMinIdle(MinIdle);
// DATA_SOURCE.setMaxIdle(MAX_IDLE);
// DATA_SOURCE.setMaxWaitMillis(MAX_WAIT_Millis);
// DATA_SOURCE.setTestOnBorrow(TOBESTNORROW);
// DATA_SOURCE.setRemoveAbandonedTimeout(RemoveAbandonedTimeout);
//
// getConnection().createStatement().close();
//
// return test();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
//
// public abstract boolean test();
//
// public DataSource getDateSource() {
// return DATA_SOURCE;
// }
//
// //提供获得链接
// public Connection getConnection() throws SQLException {
// return DATA_SOURCE.getConnection();
// }
//
// public void stop() {
// try {
// DATA_SOURCE.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//}
| Coloryr/AllMusic_Server | core/sql/MysqlConn.java | 647 | // //建立连接的驱动驱动名称 | line_comment | zh-cn | //package coloryr.allmusic.sql;
//
//import coloryr.allmusic.AllMusic;
//import org.apache.commons.dbcp2.BasicDataSource;
//
//import javax.sql.DataSource;
//import java.sql.*;
//
//public abstract class MysqlConn implements IEconomy{
// //建立 <SUF>
// public final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
// //最大空闲链接
// private final int MAX_IDLE = 20;
// //最大空闲连接
// private final int MinIdle = 8;
// //最大等待时间
// private final long MAX_WAIT_Millis = 5000;
// //最大活动链接
// private final int MAX_TOTAl = 5;
// //初始化时链接池的数量
// private final int INITIAL_SIZE = 10;
// //一个被抛弃连接可以被移除的超时时间
// private final int RemoveAbandonedTimeout = 180;
// //只会发现当前连接失效,再创建一个连接供当前查询使用
// private final boolean TOBESTNORROW = true;
// private BasicDataSource DATA_SOURCE;
//
// public boolean start() {
// try {
// DATA_SOURCE = new BasicDataSource();
// DATA_SOURCE.setDriverClassName(DRIVER_CLASS_NAME);
// DATA_SOURCE.setUrl(AllMusic.getConfig().getEconomys().getMysqlUrl());
// DATA_SOURCE.setMaxTotal(MAX_TOTAl);
// DATA_SOURCE.setInitialSize(INITIAL_SIZE);
// DATA_SOURCE.setMinIdle(MinIdle);
// DATA_SOURCE.setMaxIdle(MAX_IDLE);
// DATA_SOURCE.setMaxWaitMillis(MAX_WAIT_Millis);
// DATA_SOURCE.setTestOnBorrow(TOBESTNORROW);
// DATA_SOURCE.setRemoveAbandonedTimeout(RemoveAbandonedTimeout);
//
// getConnection().createStatement().close();
//
// return test();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
//
// public abstract boolean test();
//
// public DataSource getDateSource() {
// return DATA_SOURCE;
// }
//
// //提供获得链接
// public Connection getConnection() throws SQLException {
// return DATA_SOURCE.getConnection();
// }
//
// public void stop() {
// try {
// DATA_SOURCE.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//}
| 0 | 19 | 0 |
49653_14 | package cn.tencent.DiscuzMob.net;
/**
* Created by cg on 2017/4/10.
*/
public class AppNetConfig {
public static final String BASE_ADDRESS = "https://guanjia.comsenz-service.com/"; //【注意】更改BASE_ADDRESS的时候,要搜索全局替换, 因为JS中也有。
// public static final String BASE_ADDRESS = "https://bbs.comsenz-service.com/"; //正式服务器
public String ChangeUrl=BASE_ADDRESS;
public String getChangeUrl() {
return ChangeUrl;
}
public void setChangeUrl(String changeUrl) {
ChangeUrl = changeUrl;
}
public static final String IMGURL = BASE_ADDRESS;
public static final String IMGURL1 = BASE_ADDRESS;
public static final String BASEURL = BASE_ADDRESS + "api/mobile/";
public static final String LIVEBASEURL = "http://bbs.wsq.comsenz-service.com/newwsq/forum.php";
public static final String LOGOURL = IMGURL1 + "static/image/common/logo.png";
public static final String IMAGES = BASEURL + "?module=iwechat&data=json&version=5&mobiletype=Android";//轮播图
public static final String ALLFORUM = BASEURL + "?module=forumindex&version=5&debug=1&mobiletype=Android";//全部版块
public static final String HOTFORUM = BASEURL + "?module=hotforum&version=5&mobiletype=Android";//热门版块
public static final String HOTPOST = BASEURL + "?module=hotthread&version=4&mobiletype=IOS&ios=1";//热帖
public static final String QUESTION = BASEURL + "?module=secure&version=5&mobiletype=Android&type=";//获取验证码/问题
public static final String LOGIN = BASEURL + "?module=login&version=5&&loginfield=auto&mobiletype=Android";//登录
public static final String LOGIN1 = BASEURL + "?module=login&loginsubmit=yes&version=5&mapifrom=wx&charset=utf-8";//登录
public static final String USERINFO1 = BASEURL + "?module=profile&version=4&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String USERINFO = BASEURL + "?module=profile&version=5&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String MYFRIEND = BASEURL + "?module=friend&checkavatar=1&version=4&uid=";//我的好友
public static final String MYFAV = BASEURL + "?module=myfavforum&version=1&android=1&debug=1";//我收藏的版块
public static final String MYFAVTHREAD = BASEURL + "?module=myfavthread&version=1&android=1&debug=1";//我收藏的帖子
public static final String SYSTEM_MESSAGE = BASEURL + "?module=mypm&filter=announcepm&version=5&mobiletype=Android&page=";//系统消息
public static final String PRIVATE_LETTER = BASEURL + "?module=mypm&touid=2&page=1&version=4&mobiletype=IOS&ios=1&debug=1";//我的消息————>私信
public static final String MESSAGE_REPLIES = BASEURL + "?module=mynoticelist&mapifrom=android";//我的消息--->回复
public static final String THEME = BASEURL + "?module=mythread&version=5&mobiletype=Android&type=thread";//我的主题
// public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String COLLECTION_BANKUAI = BASEURL + "?module=favorite&version=5&type=forum";//点击收藏板块
public static final String HISTHME = BASEURL + "?module=userthread&version=5&android=1&debug=1&mobiletype=Android";//他的回复
public static final String CONVERSATION = BASEURL + "?module=mypm&subop=view&version=5&mobiletype=Android&checkavatar=1&Android=1&smiley=no&convimg=1";//会话详情
public static final String UNCOLLECTION = BASEURL + "?module=favorite&version=5&op=delete&type=forum&mobiletype=Android&id=";//点击取消收藏
public static final String REGISTER = BASEURL + "?version=5®submit=yes&module=register&";//普通注册
public static final String GETREGISTER = BASEURL + "?version=5&module=check";//普通注册
public static final String REGISTERBANGDING = BASEURL + "?version=5&module=weiqqregister";
public static final String COMMENT = BASEURL + "?module=sendreply&version=5&replysubmit=yes&mobiletype=Android&mapifrom=android";//帖子详情跟帖
public static final String SEARCH = BASEURL + "?module=search&version=5&android=1";//搜索
public static final String JURISDICTION = BASEURL + "?module=newthread&submodule=checkpost&debug=1&version=1";//检查权限
public static final String ACTIVITYTHRADF = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//活动帖
public static final String VOTETHREAD = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//投票贴
public static final String THREAD = BASEURL + "?module=newthread&version=5&android=1&debug=1&topicsubmit=yes&fid=";//普通帖
public static final String QUOTE = BASEURL + "?module=sendreply&version=3";//回复引用
public static final String PRAISETHREAD = BASEURL + "?module=recommend&version=4";//帖子点赞
public static final String COLLECTTHEAD = BASEURL + "?module=favorite&version=5&type=thread&id=";//收藏帖子http://10.0.6.58/api/mobile/version=4&android=1&debug=1&module=favthread&id=46&favoritesubmit=true
public static final String UNCOLLECTTHEAD = BASEURL + "?module=favorite&version=5&op=delete&mobiletype=Android&id=";//取消收藏帖子
public static final String JOINACTIVITY = BASEURL + "?module=activityapplies&version=5&activitysubmit=true";//参加活动
public static final String DELETELETTER = BASEURL + "?module=delpm&version=5&deletesubmit=1";//删除我的私信
public static final String DELETEMESSAGE = BASEURL + "?version=5&module=delpmview&deletesubmit=1";//删除聊天记录
public static final String LIVETHREAD = BASEURL + "?module=livethread&version=5&mobiletype=Android";//直播列表
public static final String LIVETOADY = BASEURL + "?module=recommon_livethread&version=5&mobiletype=Android";//直播推荐
public static final String LIVEDETIAL = BASEURL + "?version=5&ppp=10&module=viewthread&ordertype=1&submodule=checkpost&mobiletype=Android";//直播
public static final String INTERACTION = BASEURL + "?module=threadreply&version=5&mobiletype=Android&ppp=10";
public static final String RECOMMEND = BASEURL + "?module=recommon_thread&version=5&mobiletype=Android&android=1";//推荐
public static final String ESSENCE = BASEURL + "?module=forumguide&view=digest&version=5&type=digest&mobiletype=Android&page=";//精华帖
public static final String NEW = BASEURL + "?module=forumguide&view=newthread&version=5&type=digest&mobiletype=Android&page=";//最新帖
public static final String MYTHRED = BASEURL + "?module=mynotelist&view=mypost&type=post&version=5&mobiletype=Android";//我的帖子
public static final String MYCOMMON = BASEURL + "?module=mynotelist&view=mypost&type=pcomment&version=3&mobiletype=Android";//点评
public static final String NEWS = BASEURL + "?module=notes&version=5&mobiletype=Android";//是否有新的消息
public static final String MYACTVITY = BASEURL + "?module=mynotelist&view=mypost&type=activity&version=3&mobiletype=Android";//我的活动
public static final String MYREWARD = BASEURL + "?module=mynotelist&view=mypost&type=reward&version=3&mobiletype=Android";//悬赏
public static final String GOODS = BASEURL + "?module=mynotelist&view=mypost&type=goods&version=3&mobiletype=Android";//商品
public static final String MENTIONME = BASEURL + "?module=mynotelist&view=mypost&type=at&version=3&mobiletype=Android";//提到我的
public static final String MYCALL = BASEURL + "?module=mynotelist&view=interactive&type=post&version=3&mobiletype=Android";//打招呼
public static final String myFriends = BASEURL + "?module=mynotelist&view=interactive&type=friend&version=3&mobiletype=Android";//好友
public static final String LEAVINGMESSAGE = BASEURL + "?module=mynotelist&view=interactive&type=wall&version=3&mobiletype=Android";//留言
public static final String MYCOMMENT = BASEURL + "?module=mynotelist&view=interactive&type=comment&version=3&mobiletype=Android";//评论
public static final String QUITE = BASEURL + "?module=mynotelist&view=interactive&type=click&version=3&mobiletype=Android";//挺你
public static final String SHARE = BASEURL + "?module=mynotelist&view=interactive&type=sharenotice&version=3&mobiletype=Android";//分享
public static final String SYSTEM = BASEURL + "?module=mynotelist&view=system&version=3&mobiletype=Android";//系统提醒
public static final String ADMINISTRATION = BASEURL + "?module=mynotelist&view=manage&version=3&mobiletype=Android";//管理工作
public static final String JOINMANAGER = BASEURL + "?module=forummisc&action=activityapplylist&version=5&mobiletype=Android";//报名管理
public static final String activity_management = BASEURL + "?module=forummisc&action=activityapplylist&applylistsubmit=yes&version=5&tid=";
} | Comsenz/Discuz-Android | app/src/main/java/cn/tencent/DiscuzMob/net/AppNetConfig.java | 2,587 | //我收藏的版块
| line_comment | zh-cn | package cn.tencent.DiscuzMob.net;
/**
* Created by cg on 2017/4/10.
*/
public class AppNetConfig {
public static final String BASE_ADDRESS = "https://guanjia.comsenz-service.com/"; //【注意】更改BASE_ADDRESS的时候,要搜索全局替换, 因为JS中也有。
// public static final String BASE_ADDRESS = "https://bbs.comsenz-service.com/"; //正式服务器
public String ChangeUrl=BASE_ADDRESS;
public String getChangeUrl() {
return ChangeUrl;
}
public void setChangeUrl(String changeUrl) {
ChangeUrl = changeUrl;
}
public static final String IMGURL = BASE_ADDRESS;
public static final String IMGURL1 = BASE_ADDRESS;
public static final String BASEURL = BASE_ADDRESS + "api/mobile/";
public static final String LIVEBASEURL = "http://bbs.wsq.comsenz-service.com/newwsq/forum.php";
public static final String LOGOURL = IMGURL1 + "static/image/common/logo.png";
public static final String IMAGES = BASEURL + "?module=iwechat&data=json&version=5&mobiletype=Android";//轮播图
public static final String ALLFORUM = BASEURL + "?module=forumindex&version=5&debug=1&mobiletype=Android";//全部版块
public static final String HOTFORUM = BASEURL + "?module=hotforum&version=5&mobiletype=Android";//热门版块
public static final String HOTPOST = BASEURL + "?module=hotthread&version=4&mobiletype=IOS&ios=1";//热帖
public static final String QUESTION = BASEURL + "?module=secure&version=5&mobiletype=Android&type=";//获取验证码/问题
public static final String LOGIN = BASEURL + "?module=login&version=5&&loginfield=auto&mobiletype=Android";//登录
public static final String LOGIN1 = BASEURL + "?module=login&loginsubmit=yes&version=5&mapifrom=wx&charset=utf-8";//登录
public static final String USERINFO1 = BASEURL + "?module=profile&version=4&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String USERINFO = BASEURL + "?module=profile&version=5&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String MYFRIEND = BASEURL + "?module=friend&checkavatar=1&version=4&uid=";//我的好友
public static final String MYFAV = BASEURL + "?module=myfavforum&version=1&android=1&debug=1";//我收 <SUF>
public static final String MYFAVTHREAD = BASEURL + "?module=myfavthread&version=1&android=1&debug=1";//我收藏的帖子
public static final String SYSTEM_MESSAGE = BASEURL + "?module=mypm&filter=announcepm&version=5&mobiletype=Android&page=";//系统消息
public static final String PRIVATE_LETTER = BASEURL + "?module=mypm&touid=2&page=1&version=4&mobiletype=IOS&ios=1&debug=1";//我的消息————>私信
public static final String MESSAGE_REPLIES = BASEURL + "?module=mynoticelist&mapifrom=android";//我的消息--->回复
public static final String THEME = BASEURL + "?module=mythread&version=5&mobiletype=Android&type=thread";//我的主题
// public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String COLLECTION_BANKUAI = BASEURL + "?module=favorite&version=5&type=forum";//点击收藏板块
public static final String HISTHME = BASEURL + "?module=userthread&version=5&android=1&debug=1&mobiletype=Android";//他的回复
public static final String CONVERSATION = BASEURL + "?module=mypm&subop=view&version=5&mobiletype=Android&checkavatar=1&Android=1&smiley=no&convimg=1";//会话详情
public static final String UNCOLLECTION = BASEURL + "?module=favorite&version=5&op=delete&type=forum&mobiletype=Android&id=";//点击取消收藏
public static final String REGISTER = BASEURL + "?version=5®submit=yes&module=register&";//普通注册
public static final String GETREGISTER = BASEURL + "?version=5&module=check";//普通注册
public static final String REGISTERBANGDING = BASEURL + "?version=5&module=weiqqregister";
public static final String COMMENT = BASEURL + "?module=sendreply&version=5&replysubmit=yes&mobiletype=Android&mapifrom=android";//帖子详情跟帖
public static final String SEARCH = BASEURL + "?module=search&version=5&android=1";//搜索
public static final String JURISDICTION = BASEURL + "?module=newthread&submodule=checkpost&debug=1&version=1";//检查权限
public static final String ACTIVITYTHRADF = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//活动帖
public static final String VOTETHREAD = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//投票贴
public static final String THREAD = BASEURL + "?module=newthread&version=5&android=1&debug=1&topicsubmit=yes&fid=";//普通帖
public static final String QUOTE = BASEURL + "?module=sendreply&version=3";//回复引用
public static final String PRAISETHREAD = BASEURL + "?module=recommend&version=4";//帖子点赞
public static final String COLLECTTHEAD = BASEURL + "?module=favorite&version=5&type=thread&id=";//收藏帖子http://10.0.6.58/api/mobile/version=4&android=1&debug=1&module=favthread&id=46&favoritesubmit=true
public static final String UNCOLLECTTHEAD = BASEURL + "?module=favorite&version=5&op=delete&mobiletype=Android&id=";//取消收藏帖子
public static final String JOINACTIVITY = BASEURL + "?module=activityapplies&version=5&activitysubmit=true";//参加活动
public static final String DELETELETTER = BASEURL + "?module=delpm&version=5&deletesubmit=1";//删除我的私信
public static final String DELETEMESSAGE = BASEURL + "?version=5&module=delpmview&deletesubmit=1";//删除聊天记录
public static final String LIVETHREAD = BASEURL + "?module=livethread&version=5&mobiletype=Android";//直播列表
public static final String LIVETOADY = BASEURL + "?module=recommon_livethread&version=5&mobiletype=Android";//直播推荐
public static final String LIVEDETIAL = BASEURL + "?version=5&ppp=10&module=viewthread&ordertype=1&submodule=checkpost&mobiletype=Android";//直播
public static final String INTERACTION = BASEURL + "?module=threadreply&version=5&mobiletype=Android&ppp=10";
public static final String RECOMMEND = BASEURL + "?module=recommon_thread&version=5&mobiletype=Android&android=1";//推荐
public static final String ESSENCE = BASEURL + "?module=forumguide&view=digest&version=5&type=digest&mobiletype=Android&page=";//精华帖
public static final String NEW = BASEURL + "?module=forumguide&view=newthread&version=5&type=digest&mobiletype=Android&page=";//最新帖
public static final String MYTHRED = BASEURL + "?module=mynotelist&view=mypost&type=post&version=5&mobiletype=Android";//我的帖子
public static final String MYCOMMON = BASEURL + "?module=mynotelist&view=mypost&type=pcomment&version=3&mobiletype=Android";//点评
public static final String NEWS = BASEURL + "?module=notes&version=5&mobiletype=Android";//是否有新的消息
public static final String MYACTVITY = BASEURL + "?module=mynotelist&view=mypost&type=activity&version=3&mobiletype=Android";//我的活动
public static final String MYREWARD = BASEURL + "?module=mynotelist&view=mypost&type=reward&version=3&mobiletype=Android";//悬赏
public static final String GOODS = BASEURL + "?module=mynotelist&view=mypost&type=goods&version=3&mobiletype=Android";//商品
public static final String MENTIONME = BASEURL + "?module=mynotelist&view=mypost&type=at&version=3&mobiletype=Android";//提到我的
public static final String MYCALL = BASEURL + "?module=mynotelist&view=interactive&type=post&version=3&mobiletype=Android";//打招呼
public static final String myFriends = BASEURL + "?module=mynotelist&view=interactive&type=friend&version=3&mobiletype=Android";//好友
public static final String LEAVINGMESSAGE = BASEURL + "?module=mynotelist&view=interactive&type=wall&version=3&mobiletype=Android";//留言
public static final String MYCOMMENT = BASEURL + "?module=mynotelist&view=interactive&type=comment&version=3&mobiletype=Android";//评论
public static final String QUITE = BASEURL + "?module=mynotelist&view=interactive&type=click&version=3&mobiletype=Android";//挺你
public static final String SHARE = BASEURL + "?module=mynotelist&view=interactive&type=sharenotice&version=3&mobiletype=Android";//分享
public static final String SYSTEM = BASEURL + "?module=mynotelist&view=system&version=3&mobiletype=Android";//系统提醒
public static final String ADMINISTRATION = BASEURL + "?module=mynotelist&view=manage&version=3&mobiletype=Android";//管理工作
public static final String JOINMANAGER = BASEURL + "?module=forummisc&action=activityapplylist&version=5&mobiletype=Android";//报名管理
public static final String activity_management = BASEURL + "?module=forummisc&action=activityapplylist&applylistsubmit=yes&version=5&tid=";
} | 1 | 9 | 1 |
60215_4 |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class A {
public static void main(String[] args) {
// Readwritel
ReadWriteLock lock = new ReentrantReadWriteLock();
// AbstractQueuedSynchronizer
// CountDownLatch
int result = new A().locate(new int[]{1,-2,3,10,9,-6,9,8});
System.out.println(result);
// System.arraycopy(args, result, lock, result, result);
int[] nums = new int[]{};
List<List<Integer>> list = new A().threeSum(nums);
System.out.println(list);
}
public int findGreatestSumOfSubArray(int[] array) {
int x = array[0];
int y = 0;
int maxsum = x;
for(int i = 1; i < array.length; i++){
//状态转移:连续子数组和最大值
y = Math.max(x + array[i], array[i]);
//维护最大值
maxsum = Math.max(maxsum, y);
//更新x的状态
x = y;
}
return maxsum;
}
private int locate(int[] array){
int low = array[0];
int high = low;
int maxAdd = -100;
for (int i = 1; i < array.length; i++) {
high = Math.max(low + array[i], array[i]);
maxAdd = Math.max(high, maxAdd);
low = high;
}
return maxAdd;
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList();
int target = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
int left = i+1;
int right = nums.length - 1;
while(left < right){
int value = nums[i] + nums[left] + nums[right];
if(value == target){
List<Integer> interList = new ArrayList<Integer>();
interList.add(nums[i]);
interList.add(nums[left]);
interList.add(nums[right]);
// if(!checkExists(list, interList)){
list.add(interList);
// }
left ++;
}else if(value < target){
left ++;
}else {
right --;
}
}
}
return list;
}
private boolean checkExists(List<List<Integer>> list, List<Integer> interList){
if(list.size() < 1){
return false;
}
for(int i = 0; i < list.size(); i++){
if(checkExists0(list.get(list.size() - 1 - i), interList)){
return true;
}
}
return false;
}
private boolean checkExists0(List<Integer> listItem, List<Integer> interList){
for(int i = 0; i < listItem.size(); i++){
if(!Objects.equals(listItem.get(i), interList.get(i))){
return false;
}
}
return true;
}
}
| Coner1/leetcode | src/A.java | 892 | //状态转移:连续子数组和最大值 | line_comment | zh-cn |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class A {
public static void main(String[] args) {
// Readwritel
ReadWriteLock lock = new ReentrantReadWriteLock();
// AbstractQueuedSynchronizer
// CountDownLatch
int result = new A().locate(new int[]{1,-2,3,10,9,-6,9,8});
System.out.println(result);
// System.arraycopy(args, result, lock, result, result);
int[] nums = new int[]{};
List<List<Integer>> list = new A().threeSum(nums);
System.out.println(list);
}
public int findGreatestSumOfSubArray(int[] array) {
int x = array[0];
int y = 0;
int maxsum = x;
for(int i = 1; i < array.length; i++){
//状态 <SUF>
y = Math.max(x + array[i], array[i]);
//维护最大值
maxsum = Math.max(maxsum, y);
//更新x的状态
x = y;
}
return maxsum;
}
private int locate(int[] array){
int low = array[0];
int high = low;
int maxAdd = -100;
for (int i = 1; i < array.length; i++) {
high = Math.max(low + array[i], array[i]);
maxAdd = Math.max(high, maxAdd);
low = high;
}
return maxAdd;
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList();
int target = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
int left = i+1;
int right = nums.length - 1;
while(left < right){
int value = nums[i] + nums[left] + nums[right];
if(value == target){
List<Integer> interList = new ArrayList<Integer>();
interList.add(nums[i]);
interList.add(nums[left]);
interList.add(nums[right]);
// if(!checkExists(list, interList)){
list.add(interList);
// }
left ++;
}else if(value < target){
left ++;
}else {
right --;
}
}
}
return list;
}
private boolean checkExists(List<List<Integer>> list, List<Integer> interList){
if(list.size() < 1){
return false;
}
for(int i = 0; i < list.size(); i++){
if(checkExists0(list.get(list.size() - 1 - i), interList)){
return true;
}
}
return false;
}
private boolean checkExists0(List<Integer> listItem, List<Integer> interList){
for(int i = 0; i < listItem.size(); i++){
if(!Objects.equals(listItem.get(i), interList.get(i))){
return false;
}
}
return true;
}
}
| 1 | 16 | 1 |
15348_10 | // public class Main{
// public static void main(String[] args){
// int n = 3300;
// n++; // 相当于 n = n + 1;
// n--; // 可以对一个整数进行加1和减1的操作
// int y = 100 + (++n);
// System.out.println(n--);
// System.out.println(y);
// }
// }
// long 可表示的整型范围更大
// 移位运算
// 位运算
// 加括号就可以保证运算的优先级正确
// public class Main {
// public static void main(String[] args) {
// double x = 1.0 / 10;
// double y = 1 - 9.0 / 10;
// // 观察x和y是否相等:
// System.out.println(x);
// System.out.println(y);
// }
// }
// 类型提升 如果参与运算的两个数其中一个是整型,那么整型可以自动提升到浮点型:
// Boolean 运算
// public class Main{
// public static void main(String[] args){
// boolean b = 5 < 3;
// boolean result = b && (5 / 0 > 0);
// System.out.println(result);
// }
// }
// 字符和字符串
// public class Main{
// public static void main(String[] args){
// String s1 = "Hello";
// String s2 = "Roxy 'Love you'";
// String s = s1 + ' '+ s2;
// System.out.println(s);
// }
// }
public class Main {
public static void main(String[] args) {
String s = "hello";
s = "world";
System.out.println(s); // 显示 world
}
}
// char c1 = 'A'; 字符只能用单引号来表示
// String c2 = "shkahfda" 字符串可以表达任意多个字符 | ConnorLi96/Java-Learning-Notes | Main.java | 513 | // 位运算 | line_comment | zh-cn | // public class Main{
// public static void main(String[] args){
// int n = 3300;
// n++; // 相当于 n = n + 1;
// n--; // 可以对一个整数进行加1和减1的操作
// int y = 100 + (++n);
// System.out.println(n--);
// System.out.println(y);
// }
// }
// long 可表示的整型范围更大
// 移位运算
// 位运 <SUF>
// 加括号就可以保证运算的优先级正确
// public class Main {
// public static void main(String[] args) {
// double x = 1.0 / 10;
// double y = 1 - 9.0 / 10;
// // 观察x和y是否相等:
// System.out.println(x);
// System.out.println(y);
// }
// }
// 类型提升 如果参与运算的两个数其中一个是整型,那么整型可以自动提升到浮点型:
// Boolean 运算
// public class Main{
// public static void main(String[] args){
// boolean b = 5 < 3;
// boolean result = b && (5 / 0 > 0);
// System.out.println(result);
// }
// }
// 字符和字符串
// public class Main{
// public static void main(String[] args){
// String s1 = "Hello";
// String s2 = "Roxy 'Love you'";
// String s = s1 + ' '+ s2;
// System.out.println(s);
// }
// }
public class Main {
public static void main(String[] args) {
String s = "hello";
s = "world";
System.out.println(s); // 显示 world
}
}
// char c1 = 'A'; 字符只能用单引号来表示
// String c2 = "shkahfda" 字符串可以表达任意多个字符 | 0 | 6 | 0 |
31204_27 | import java.util.*;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Vector<Course> clist = new Vector<Course>();
// clist.add(new Course(1, "数学分析", 0,
// new Teacher("韩老师", 1, "教授"), 20));
// clist.add(new Course(2, "高等代数", 0,
// new Teacher("李老师", 2, "教授"), 15));
// clist.add(new Course(3, "Java", 1,
// new Teacher("吴老师", 3, "副教授"), 23));
// clist.add(new Course(4, "深度学习", 0,
// new Teacher("李老师", 4, "教授"), 50));
// User user = new User();
// Courses.addCourses();
// Courses.SortCourseList();
// Courses.showCourses();
// Courses.readCourses();
menu();
// Courses.saveCourse();
// StringBuffer s1 = new StringBuffer("124");
// s1.append(266);
// s1.append("223");
// System.out.println(s1);
}
public static void menu() {
Scanner sc = new Scanner(System.in);
Vector loginInfo = login();
int identity = (int)loginInfo.get(0);
if (identity == -1) {
return;
}
database.init(); // 初始化
if (identity == 0) { // 管理员菜单
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.新建课程\n" +
"2.删除课程\n3.设置课程教师\n" +
"4.查找老师讲课课程 \n5.显示课程列表 \n" +
"6.按照选课人数进行排序\n7.显示学生列表\n" +
"8.显示教师列表\n9.添加学生\n" +
"10.添加老师\n11.删除学生\n" +
"12.删除老师\n13.初始化学生密码\n" +
"14.初始化老师密码\n0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0: //退出系统
database.dbstmt.close(); // 关数据库
break MainLoop;
case 1: // 添加课程
Courses.addCourses();
break;
case 2: // 删除课程
Courses.deleteCourse();
break;
case 3: // 设置课程教师
Courses.setCourseTeacher();
break;
case 4: // 根据授课教师查找课程
Courses.SearchCourseByTeacher();
break;
case 5: // 显示课程信息
Courses.showCourses();
break;
case 6: // 按照选课人数排序
Courses.SortCourseList();
break;
case 7: // 显示所有学生
Users.showStudents();
break;
case 8: // 显示所有教师
Users.showTeachers();
break;
case 9: // 添加学生
Users.addStudents();
break;
case 10: // 添加老师
Users.addTeachers();
break;
case 11: // 删除学生
Users.deleteStudents();
break;
case 12: // 删除老师
Users.deleteTeachers();
break;
case 13: // 初始化学生密码
Users.recoverStudentsPass();
break;
case 14: // 初始化老师密码
Users.recoverTeachersPass();
break;
default: // 非法输入
System.out.println("输入错误!!!");
}
}
}
else if (identity == 1) { // 教师菜单
Teacher loadingTeacher = (Teacher)loginInfo.get(1);
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所授课程\n3.查看课程学生名单\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingTeacher.settPassWord(); // 修改登录密码
case 2 -> loadingTeacher.teachingCourse(); // 查看所授课程
case 3 -> loadingTeacher.studentList(); // 查看所授课程学生名单
}
}
}
else {
Student loadingStudent = (Student)loginInfo.get(1);
MainLoop:
while (true) { // 学生菜单
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所上课程\n3.选课\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingStudent.setstPassWord(); // 修改登录密码
case 2 -> loadingStudent.learningCourse(); // 查看自己所上课程
case 3 -> loadingStudent.choiceCourse(); // 选课
}
}
}
}
public static Vector login() { // 登录用
Vector res = new Vector(); // result
Scanner sc = new Scanner(System.in);
System.out.println("请输入登陆身份:\n0.管理员\n" +
"1.教师\n" +
"2.学生");
int identity = sc.nextInt();
switch (identity) {
case 0 -> System.out.println("请输入管理员密码:");
case 1 -> System.out.println("请输入教师账号、密码:");
case 2 -> System.out.println("请输入学生账号、密码:");
}
if (identity == 0) {
String pass = sc.next();
if (!pass.equals(Users.admin.getPass())) {
System.out.println("密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
return res;
}
else if (identity == 1) {
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From teacher where tname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Teacher((String)selectt.get(0).get("tname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("tid"), (String)selectt.get(0).get("tlevel")));
return res;
}
else if (identity == 2){
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From student where sname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Student((String)selectt.get(0).get("sname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("sid"), (String)selectt.get(0).get("sclass")));
return res;
}
System.out.println("输入错误!系统退出!");
res.add(-1);
return res;
}
} | Control-derek/NEU_Doka_Java_Experiment1 | src/Main.java | 2,075 | // 设置课程教师 | line_comment | zh-cn | import java.util.*;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Vector<Course> clist = new Vector<Course>();
// clist.add(new Course(1, "数学分析", 0,
// new Teacher("韩老师", 1, "教授"), 20));
// clist.add(new Course(2, "高等代数", 0,
// new Teacher("李老师", 2, "教授"), 15));
// clist.add(new Course(3, "Java", 1,
// new Teacher("吴老师", 3, "副教授"), 23));
// clist.add(new Course(4, "深度学习", 0,
// new Teacher("李老师", 4, "教授"), 50));
// User user = new User();
// Courses.addCourses();
// Courses.SortCourseList();
// Courses.showCourses();
// Courses.readCourses();
menu();
// Courses.saveCourse();
// StringBuffer s1 = new StringBuffer("124");
// s1.append(266);
// s1.append("223");
// System.out.println(s1);
}
public static void menu() {
Scanner sc = new Scanner(System.in);
Vector loginInfo = login();
int identity = (int)loginInfo.get(0);
if (identity == -1) {
return;
}
database.init(); // 初始化
if (identity == 0) { // 管理员菜单
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.新建课程\n" +
"2.删除课程\n3.设置课程教师\n" +
"4.查找老师讲课课程 \n5.显示课程列表 \n" +
"6.按照选课人数进行排序\n7.显示学生列表\n" +
"8.显示教师列表\n9.添加学生\n" +
"10.添加老师\n11.删除学生\n" +
"12.删除老师\n13.初始化学生密码\n" +
"14.初始化老师密码\n0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0: //退出系统
database.dbstmt.close(); // 关数据库
break MainLoop;
case 1: // 添加课程
Courses.addCourses();
break;
case 2: // 删除课程
Courses.deleteCourse();
break;
case 3: // 设置 <SUF>
Courses.setCourseTeacher();
break;
case 4: // 根据授课教师查找课程
Courses.SearchCourseByTeacher();
break;
case 5: // 显示课程信息
Courses.showCourses();
break;
case 6: // 按照选课人数排序
Courses.SortCourseList();
break;
case 7: // 显示所有学生
Users.showStudents();
break;
case 8: // 显示所有教师
Users.showTeachers();
break;
case 9: // 添加学生
Users.addStudents();
break;
case 10: // 添加老师
Users.addTeachers();
break;
case 11: // 删除学生
Users.deleteStudents();
break;
case 12: // 删除老师
Users.deleteTeachers();
break;
case 13: // 初始化学生密码
Users.recoverStudentsPass();
break;
case 14: // 初始化老师密码
Users.recoverTeachersPass();
break;
default: // 非法输入
System.out.println("输入错误!!!");
}
}
}
else if (identity == 1) { // 教师菜单
Teacher loadingTeacher = (Teacher)loginInfo.get(1);
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所授课程\n3.查看课程学生名单\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingTeacher.settPassWord(); // 修改登录密码
case 2 -> loadingTeacher.teachingCourse(); // 查看所授课程
case 3 -> loadingTeacher.studentList(); // 查看所授课程学生名单
}
}
}
else {
Student loadingStudent = (Student)loginInfo.get(1);
MainLoop:
while (true) { // 学生菜单
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所上课程\n3.选课\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingStudent.setstPassWord(); // 修改登录密码
case 2 -> loadingStudent.learningCourse(); // 查看自己所上课程
case 3 -> loadingStudent.choiceCourse(); // 选课
}
}
}
}
public static Vector login() { // 登录用
Vector res = new Vector(); // result
Scanner sc = new Scanner(System.in);
System.out.println("请输入登陆身份:\n0.管理员\n" +
"1.教师\n" +
"2.学生");
int identity = sc.nextInt();
switch (identity) {
case 0 -> System.out.println("请输入管理员密码:");
case 1 -> System.out.println("请输入教师账号、密码:");
case 2 -> System.out.println("请输入学生账号、密码:");
}
if (identity == 0) {
String pass = sc.next();
if (!pass.equals(Users.admin.getPass())) {
System.out.println("密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
return res;
}
else if (identity == 1) {
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From teacher where tname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Teacher((String)selectt.get(0).get("tname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("tid"), (String)selectt.get(0).get("tlevel")));
return res;
}
else if (identity == 2){
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From student where sname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Student((String)selectt.get(0).get("sname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("sid"), (String)selectt.get(0).get("sclass")));
return res;
}
System.out.println("输入错误!系统退出!");
res.add(-1);
return res;
}
} | 1 | 9 | 1 |
66717_10 | package com.kot32.ksimplelibrary.widgets.view;
import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import com.kot32.ksimplelibrary.util.tools.DisplayUtil;
import com.kot32.ksimplelibrary.util.tools.reflect.FieldUtil;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by kot32 on 15/10/18.
* 实现下拉刷新的 View
* KRefreshView{SubView:HeaderView、ListView}
*/
public class KRefreshView extends LinearLayout {
private Scroller scroller = new Scroller(getContext());
private TextView default_header_tips;
private TextView default_bottom_tips;
private boolean shouldRefresh = false;
private boolean isRefreshing = false;
private boolean shouldLoadMore = false;
private boolean isLoadMoreing = false;
//是否开启上拉加载更多的开关
private LoadMoreConfig loadMoreConfig;
//头部刷新View的父容器
private RelativeLayout headerContent;
//尾部『加载更多』 View 的父容器
private RelativeLayout bottomContent;
//头部刷新View
private View headerView;
//尾部『加载更多』 的 View
private View bottomView;
//下拉刷新-控制UI更新
private RefreshViewHolder refreshViewHolder;
//下拉刷新-控制事务更新
private IRefreshAction iRefreshAction;
//下拉刷新-控制UI更新
private LoadMoreViewHolder loadMoreViewHolder;
//下拉刷新-控制事务更新
private ILoadMoreAction iLoadMoreAction;
//触摸事件传递接口
private onRefreshViewTouch onRefreshViewTouch;
//默认高度
private int HEADER_HEIGHT = 100;
private int BOTTOM_HEIGHT = 100;
private int MAX_LIMIT_SLOT = 50;
private int totalLimit;
private AtomicBoolean isInitListViewListener = new AtomicBoolean(false);
private boolean isShouldShowLoadMore = false;
public KRefreshView(Context context) {
super(context);
initView();
initData();
initController();
}
public KRefreshView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
initData();
initController();
}
private void initView() {
setOrientation(VERTICAL);
//增加头部View容器
LinearLayout.LayoutParams headerContentParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), HEADER_HEIGHT));
headerContent = new RelativeLayout(getContext());
headerContentParams.setMargins(0, -DisplayUtil.dip2px(getContext(), HEADER_HEIGHT), 0, 0);
headerContent.setLayoutParams(headerContentParams);
addView(headerContent, 0);
//增加隐藏的View
default_header_tips = new TextView(getContext());
default_header_tips.setText("继续下拉以刷新...");
RelativeLayout.LayoutParams defaultHeaderTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultHeaderTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
default_header_tips.setLayoutParams(defaultHeaderTextParams);
headerContent.addView(default_header_tips, 0);
// 尾部View容器
bottomContent = new RelativeLayout(getContext());
LayoutParams bottomContentParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT));
bottomContentParams.setMargins(0, 0, 0, -DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT));
bottomContent.setLayoutParams(bottomContentParams);
default_bottom_tips = new TextView(getContext());
default_bottom_tips.setText("上拉加载更多..");
RelativeLayout.LayoutParams defaultBottomTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultBottomTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
default_bottom_tips.setLayoutParams(defaultBottomTextParams);
bottomContent.addView(default_bottom_tips, 0);
}
private void initData() {
refreshViewHolder = new RefreshViewHolder() {
@Override
public void pullingTips(View headerView, int progress) {
default_header_tips.setText("继续下拉以刷新...");
}
@Override
public void willRefreshTips(View headerView) {
default_header_tips.setText("松开以刷新");
}
@Override
public void refreshingTips(View headerView) {
default_header_tips.setText("正在刷新...");
}
@Override
public void refreshCompleteTips(View headerView) {
default_header_tips.setText("刷新成功");
}
};
loadMoreViewHolder = new LoadMoreViewHolder() {
@Override
public void loadTips(View headerView, int progress) {
default_bottom_tips.setText("继续上拉以加载更多");
}
@Override
public void willloadTips(View headerView) {
default_bottom_tips.setText("松开以加载更多");
}
@Override
public void loadingTips(View headerView) {
default_bottom_tips.setText("正在加载");
}
@Override
public void loadCompleteTips(View headerView) {
default_bottom_tips.setText("加载完成");
}
};
totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT);
}
private void initController() {
}
public void initLoadMoreFunc() {
if (isInitListViewListener.compareAndSet(false, true)) {
View view = getChildAt(1);
if (view instanceof ListView) {
final AbsListView.OnScrollListener oldListener = (AbsListView.OnScrollListener) FieldUtil.getDefedValue("mOnScrollListener", ListView.class, view);
((ListView) view).setOnScrollListener(new AbsListView.OnScrollListener() {
private boolean scrollFlag = false;// 标记是否滑动
private int lastVisibleItemPosition = 0;// 标记上次滑动位置
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (oldListener != null) {
oldListener.onScrollStateChanged(view, scrollState);
}
switch (scrollState) {
// 当不滚动时
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
scrollFlag = false;
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
scrollFlag = true;
break;
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指,屏幕产生惯性滑动时
scrollFlag = false;
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (oldListener != null) {
oldListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
if (view.getLastVisiblePosition() == (view
.getCount() - 1)) {
if (bottomContent.getParent() == null) {
//显示加载更多View
KRefreshView.this.addView(bottomContent, 2);
}
//当滑到最下面时,控制权交给父 View
isShouldShowLoadMore = true;
} else {
isShouldShowLoadMore = false;
}
}
});
}
}
}
private float preY;
private float tmpY;
private float Y1;
private float Y2;
enum INTERCEPT_ACTION {
REFRESH, LOAD_MORE
}
private INTERCEPT_ACTION intercept_action;
//判断是否拦截事件
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//如果是方向向上,且ListView
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Y1 = ev.getRawY();
preY = ev.getRawY();
tmpY = ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
Y2 = ev.getRawY();
//没有滑动到一定距离,就不拦截
if (Math.abs(Y2 - Y1) < 3)
return false;
if (Y2 > Y1) {
View view = getChildAt(1);
if (view instanceof ListView) {
//如果ListView可见的第一个index是0,并且还没滑动
if (((ListView) view).getFirstVisiblePosition() == 0) {
View v = ((ListView) view).getChildAt(0);
if ((v == null) || (v != null && v.getTop() == 0)) {
intercept_action = INTERCEPT_ACTION.REFRESH;
return true;
}
}
} else if (view instanceof ScrollView) {
if (view.getScrollY() == 0) {
intercept_action = INTERCEPT_ACTION.REFRESH;
return true;
}
} else if (view instanceof WebView) {
if (view.getScrollY() == 0) {
intercept_action = INTERCEPT_ACTION.REFRESH;
return true;
}
}
} else {
if (loadMoreConfig != null && loadMoreConfig.canLoadMore) {
if (isShouldShowLoadMore) {
intercept_action = INTERCEPT_ACTION.LOAD_MORE;
return true;
}
}
}
break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean isRefreshTiping = false;
boolean isLoadMoreTiping = false;
if (onRefreshViewTouch != null) {
onRefreshViewTouch.onTouch((int) ev.getRawX(), (int) ev.getRawY());
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
preY = ev.getRawY();
tmpY = ev.getRawY();
isRefreshTiping = false;
isLoadMoreTiping = false;
if (refreshViewHolder != null) {
if (isRefreshing) break;
refreshViewHolder.pullingTips(headerView, 0);
}
if (loadMoreViewHolder != null) {
if (isLoadMoreing) break;
loadMoreViewHolder.loadTips(bottomView, 0);
}
break;
case MotionEvent.ACTION_MOVE:
float currentY = ev.getRawY();
float offsetY = currentY - tmpY;
float dis = currentY - preY;
//下拉刷新
if (intercept_action == INTERCEPT_ACTION.REFRESH) {
if (dis >= DisplayUtil.dip2px(getContext(), HEADER_HEIGHT)) {
if (refreshViewHolder != null) {
if (!isRefreshTiping) {
//提示只有一次
refreshViewHolder.willRefreshTips(headerView);
isRefreshTiping = true;
}
}
shouldRefresh = true;
} else {
shouldRefresh = false;
float ratio = dis / DisplayUtil.dip2px(getContext(), HEADER_HEIGHT);
if (refreshViewHolder != null && !isRefreshing)
refreshViewHolder.pullingTips(headerView, (int) (100 * Math.abs(ratio)));
}
if (dis >= 0 && (dis < totalLimit)) {
this.scrollBy(0, -(int) offsetY);
}
if (dis >= totalLimit) {
this.scrollTo(0, -totalLimit);
}
} else if ((intercept_action == INTERCEPT_ACTION.LOAD_MORE) && (dis < 0)) {
//上拉加载
this.scrollBy(0, -(int) offsetY);
if (Math.abs(dis) >= DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)) {
if (!isLoadMoreTiping) {
loadMoreViewHolder.willloadTips(bottomView);
isLoadMoreTiping = true;
}
shouldLoadMore = true;
} else {
shouldLoadMore = false;
float ratio = dis / DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT);
if (loadMoreViewHolder != null && !isLoadMoreing)
loadMoreViewHolder.loadTips(headerView, (int) (100 * Math.abs(ratio)));
}
}
tmpY = currentY;
break;
case MotionEvent.ACTION_UP:
smoothToZeroPos();
break;
case MotionEvent.ACTION_CANCEL:
smoothToZeroPos();
break;
}
return true;
}
private void startRefresh() {
if (refreshViewHolder != null) {
refreshViewHolder.refreshingTips(headerView);
//开始后台刷新任务
if (!isRefreshing)
new RefreshTask().execute();
}
}
private void startLoadMore() {
if (loadMoreViewHolder != null) {
loadMoreViewHolder.loadingTips(bottomView);
if (!isLoadMoreing) {
new LoadMoreTask().execute();
}
}
}
private void smoothToZeroPos() {
//下拉刷新
if (intercept_action == INTERCEPT_ACTION.REFRESH) {
if (shouldRefresh)
startRefresh();
} else if (intercept_action == INTERCEPT_ACTION.LOAD_MORE) {
//上拉加载更多
if (shouldLoadMore) {
startLoadMore();
}
}
smoothScrollTo(0, 0);
}
private void smoothScrollTo(int destX, int destY) {
int offsetY = destY - getScrollY();
scroller.startScroll(0, getScrollY(), 0, offsetY, 500);
invalidate();
}
@Override
public void computeScroll() {
super.computeScroll();
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
//下拉刷新-管理UI方面的接口
public interface RefreshViewHolder {
//还没到刷新点的提示
void pullingTips(View headerView, int progress);
//快要刷新时的提示
void willRefreshTips(View headerView);
//正在刷新时的状态
void refreshingTips(View headerView);
//刷新完毕
void refreshCompleteTips(View headerView);
}
//下拉刷新-管理事务方面的接口
public interface IRefreshAction {
void refresh();
void refreshComplete();
}
//上拉加载-管理UI 接口
public interface LoadMoreViewHolder {
//还没到加载点的提示
void loadTips(View headerView, int progress);
//快要加载时的提示
void willloadTips(View headerView);
//正在加载时的状态
void loadingTips(View headerView);
//加载完毕
void loadCompleteTips(View headerView);
}
public interface ILoadMoreAction {
void loadMore();
void loadMoreComplete();
}
//触摸点传递的接口,可供实现类扩展更多自定义动画
public interface onRefreshViewTouch {
void onTouch(int x, int y);
}
public View getHeaderView() {
return headerView;
}
public void setHeaderView(View headerView, RelativeLayout.LayoutParams layoutParams) {
this.headerView = headerView;
headerContent.removeViewAt(0);
RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
if (layoutParams == null)
headerView.setLayoutParams(defaultLayoutParams);
else
headerView.setLayoutParams(layoutParams);
headerContent.addView(headerView, 0);
}
public void setBottomView(View bottomView, RelativeLayout.LayoutParams layoutParams) {
this.bottomView = bottomView;
bottomContent.removeViewAt(0);
RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
if (layoutParams == null)
bottomView.setLayoutParams(defaultLayoutParams);
else
bottomView.setLayoutParams(layoutParams);
bottomContent.addView(bottomView, 0);
}
public RefreshViewHolder getRefreshViewHolder() {
return refreshViewHolder;
}
public void setRefreshViewHolder(RefreshViewHolder refreshViewHolder) {
this.refreshViewHolder = refreshViewHolder;
}
private class RefreshTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
isRefreshing = true;
shouldRefresh = false;
if (iRefreshAction != null) {
iRefreshAction.refresh();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
post(new Runnable() {
@Override
public void run() {
if (refreshViewHolder != null) {
refreshViewHolder.refreshCompleteTips(headerView);
smoothScrollTo(0, 0);
}
}
});
if (iRefreshAction != null) {
iRefreshAction.refreshComplete();
}
isRefreshing = false;
}
@Override
protected void onCancelled() {
super.onCancelled();
smoothScrollTo(0, 0);
shouldRefresh = false;
isRefreshing = false;
}
}
private class LoadMoreTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
isLoadMoreing = true;
shouldLoadMore = false;
if (iLoadMoreAction != null) {
iLoadMoreAction.loadMore();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
super.onPostExecute(aVoid);
post(new Runnable() {
@Override
public void run() {
if (loadMoreViewHolder != null) {
loadMoreViewHolder.loadCompleteTips(headerView);
smoothScrollTo(0, 0);
}
}
});
if (iLoadMoreAction != null) {
iLoadMoreAction.loadMoreComplete();
}
isLoadMoreing = false;
}
@Override
protected void onCancelled() {
super.onCancelled();
smoothScrollTo(0, 0);
shouldLoadMore = false;
isLoadMoreing = false;
}
}
public void setiRefreshAction(IRefreshAction iRefreshAction) {
this.iRefreshAction = iRefreshAction;
}
public ILoadMoreAction getiLoadMoreAction() {
return iLoadMoreAction;
}
public void setiLoadMoreAction(ILoadMoreAction iLoadMoreAction) {
this.iLoadMoreAction = iLoadMoreAction;
}
public LoadMoreViewHolder getLoadMoreViewHolder() {
return loadMoreViewHolder;
}
public void setLoadMoreViewHolder(LoadMoreViewHolder loadMoreViewHolder) {
this.loadMoreViewHolder = loadMoreViewHolder;
}
public KRefreshView.onRefreshViewTouch getOnRefreshViewTouch() {
return onRefreshViewTouch;
}
public void setOnRefreshViewTouch(KRefreshView.onRefreshViewTouch onRefreshViewTouch) {
this.onRefreshViewTouch = onRefreshViewTouch;
}
public void setHeaderHeight(int headerHeightDp) {
this.HEADER_HEIGHT = headerHeightDp;
totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT);
}
public int getMAX_LIMIT_SLOT() {
return MAX_LIMIT_SLOT;
}
public void setMAX_LIMIT_SLOT(int MAX_LIMIT_SLOT) {
this.MAX_LIMIT_SLOT = MAX_LIMIT_SLOT;
totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT);
}
public LoadMoreConfig getLoadMoreConfig() {
return loadMoreConfig;
}
public void setLoadMoreConfig(LoadMoreConfig loadMoreConfig) {
this.loadMoreConfig = loadMoreConfig;
if (loadMoreConfig.canLoadMore) {
if (loadMoreConfig.loadMoreView != null)
setBottomView(loadMoreConfig.loadMoreView, null);
if (loadMoreConfig.iLoadMoreAction != null)
setiLoadMoreAction(loadMoreConfig.iLoadMoreAction);
if (loadMoreConfig.loadMoreViewHolder != null)
setLoadMoreViewHolder(loadMoreConfig.loadMoreViewHolder);
if (loadMoreConfig.height > 0)
BOTTOM_HEIGHT = loadMoreConfig.height;
}
}
public static class LoadMoreConfig {
public boolean canLoadMore;
public View loadMoreView;
public ILoadMoreAction iLoadMoreAction;
public LoadMoreViewHolder loadMoreViewHolder;
public int height;
public LoadMoreConfig(boolean canLoadMore, View loadMoreView, ILoadMoreAction iLoadMoreAction, LoadMoreViewHolder loadMoreViewHolder, int height) {
this.canLoadMore = canLoadMore;
this.loadMoreView = loadMoreView;
this.iLoadMoreAction = iLoadMoreAction;
this.loadMoreViewHolder = loadMoreViewHolder;
this.height = height;
}
}
}
| CookieDSEU/PlantNurse | ksimplelibrary/src/main/java/com/kot32/ksimplelibrary/widgets/view/KRefreshView.java | 4,981 | //触摸事件传递接口 | line_comment | zh-cn | package com.kot32.ksimplelibrary.widgets.view;
import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import com.kot32.ksimplelibrary.util.tools.DisplayUtil;
import com.kot32.ksimplelibrary.util.tools.reflect.FieldUtil;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by kot32 on 15/10/18.
* 实现下拉刷新的 View
* KRefreshView{SubView:HeaderView、ListView}
*/
public class KRefreshView extends LinearLayout {
private Scroller scroller = new Scroller(getContext());
private TextView default_header_tips;
private TextView default_bottom_tips;
private boolean shouldRefresh = false;
private boolean isRefreshing = false;
private boolean shouldLoadMore = false;
private boolean isLoadMoreing = false;
//是否开启上拉加载更多的开关
private LoadMoreConfig loadMoreConfig;
//头部刷新View的父容器
private RelativeLayout headerContent;
//尾部『加载更多』 View 的父容器
private RelativeLayout bottomContent;
//头部刷新View
private View headerView;
//尾部『加载更多』 的 View
private View bottomView;
//下拉刷新-控制UI更新
private RefreshViewHolder refreshViewHolder;
//下拉刷新-控制事务更新
private IRefreshAction iRefreshAction;
//下拉刷新-控制UI更新
private LoadMoreViewHolder loadMoreViewHolder;
//下拉刷新-控制事务更新
private ILoadMoreAction iLoadMoreAction;
//触摸 <SUF>
private onRefreshViewTouch onRefreshViewTouch;
//默认高度
private int HEADER_HEIGHT = 100;
private int BOTTOM_HEIGHT = 100;
private int MAX_LIMIT_SLOT = 50;
private int totalLimit;
private AtomicBoolean isInitListViewListener = new AtomicBoolean(false);
private boolean isShouldShowLoadMore = false;
public KRefreshView(Context context) {
super(context);
initView();
initData();
initController();
}
public KRefreshView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
initData();
initController();
}
private void initView() {
setOrientation(VERTICAL);
//增加头部View容器
LinearLayout.LayoutParams headerContentParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), HEADER_HEIGHT));
headerContent = new RelativeLayout(getContext());
headerContentParams.setMargins(0, -DisplayUtil.dip2px(getContext(), HEADER_HEIGHT), 0, 0);
headerContent.setLayoutParams(headerContentParams);
addView(headerContent, 0);
//增加隐藏的View
default_header_tips = new TextView(getContext());
default_header_tips.setText("继续下拉以刷新...");
RelativeLayout.LayoutParams defaultHeaderTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultHeaderTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
default_header_tips.setLayoutParams(defaultHeaderTextParams);
headerContent.addView(default_header_tips, 0);
// 尾部View容器
bottomContent = new RelativeLayout(getContext());
LayoutParams bottomContentParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT));
bottomContentParams.setMargins(0, 0, 0, -DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT));
bottomContent.setLayoutParams(bottomContentParams);
default_bottom_tips = new TextView(getContext());
default_bottom_tips.setText("上拉加载更多..");
RelativeLayout.LayoutParams defaultBottomTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultBottomTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
default_bottom_tips.setLayoutParams(defaultBottomTextParams);
bottomContent.addView(default_bottom_tips, 0);
}
private void initData() {
refreshViewHolder = new RefreshViewHolder() {
@Override
public void pullingTips(View headerView, int progress) {
default_header_tips.setText("继续下拉以刷新...");
}
@Override
public void willRefreshTips(View headerView) {
default_header_tips.setText("松开以刷新");
}
@Override
public void refreshingTips(View headerView) {
default_header_tips.setText("正在刷新...");
}
@Override
public void refreshCompleteTips(View headerView) {
default_header_tips.setText("刷新成功");
}
};
loadMoreViewHolder = new LoadMoreViewHolder() {
@Override
public void loadTips(View headerView, int progress) {
default_bottom_tips.setText("继续上拉以加载更多");
}
@Override
public void willloadTips(View headerView) {
default_bottom_tips.setText("松开以加载更多");
}
@Override
public void loadingTips(View headerView) {
default_bottom_tips.setText("正在加载");
}
@Override
public void loadCompleteTips(View headerView) {
default_bottom_tips.setText("加载完成");
}
};
totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT);
}
private void initController() {
}
public void initLoadMoreFunc() {
if (isInitListViewListener.compareAndSet(false, true)) {
View view = getChildAt(1);
if (view instanceof ListView) {
final AbsListView.OnScrollListener oldListener = (AbsListView.OnScrollListener) FieldUtil.getDefedValue("mOnScrollListener", ListView.class, view);
((ListView) view).setOnScrollListener(new AbsListView.OnScrollListener() {
private boolean scrollFlag = false;// 标记是否滑动
private int lastVisibleItemPosition = 0;// 标记上次滑动位置
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (oldListener != null) {
oldListener.onScrollStateChanged(view, scrollState);
}
switch (scrollState) {
// 当不滚动时
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
scrollFlag = false;
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
scrollFlag = true;
break;
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指,屏幕产生惯性滑动时
scrollFlag = false;
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (oldListener != null) {
oldListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
if (view.getLastVisiblePosition() == (view
.getCount() - 1)) {
if (bottomContent.getParent() == null) {
//显示加载更多View
KRefreshView.this.addView(bottomContent, 2);
}
//当滑到最下面时,控制权交给父 View
isShouldShowLoadMore = true;
} else {
isShouldShowLoadMore = false;
}
}
});
}
}
}
private float preY;
private float tmpY;
private float Y1;
private float Y2;
enum INTERCEPT_ACTION {
REFRESH, LOAD_MORE
}
private INTERCEPT_ACTION intercept_action;
//判断是否拦截事件
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//如果是方向向上,且ListView
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Y1 = ev.getRawY();
preY = ev.getRawY();
tmpY = ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
Y2 = ev.getRawY();
//没有滑动到一定距离,就不拦截
if (Math.abs(Y2 - Y1) < 3)
return false;
if (Y2 > Y1) {
View view = getChildAt(1);
if (view instanceof ListView) {
//如果ListView可见的第一个index是0,并且还没滑动
if (((ListView) view).getFirstVisiblePosition() == 0) {
View v = ((ListView) view).getChildAt(0);
if ((v == null) || (v != null && v.getTop() == 0)) {
intercept_action = INTERCEPT_ACTION.REFRESH;
return true;
}
}
} else if (view instanceof ScrollView) {
if (view.getScrollY() == 0) {
intercept_action = INTERCEPT_ACTION.REFRESH;
return true;
}
} else if (view instanceof WebView) {
if (view.getScrollY() == 0) {
intercept_action = INTERCEPT_ACTION.REFRESH;
return true;
}
}
} else {
if (loadMoreConfig != null && loadMoreConfig.canLoadMore) {
if (isShouldShowLoadMore) {
intercept_action = INTERCEPT_ACTION.LOAD_MORE;
return true;
}
}
}
break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean isRefreshTiping = false;
boolean isLoadMoreTiping = false;
if (onRefreshViewTouch != null) {
onRefreshViewTouch.onTouch((int) ev.getRawX(), (int) ev.getRawY());
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
preY = ev.getRawY();
tmpY = ev.getRawY();
isRefreshTiping = false;
isLoadMoreTiping = false;
if (refreshViewHolder != null) {
if (isRefreshing) break;
refreshViewHolder.pullingTips(headerView, 0);
}
if (loadMoreViewHolder != null) {
if (isLoadMoreing) break;
loadMoreViewHolder.loadTips(bottomView, 0);
}
break;
case MotionEvent.ACTION_MOVE:
float currentY = ev.getRawY();
float offsetY = currentY - tmpY;
float dis = currentY - preY;
//下拉刷新
if (intercept_action == INTERCEPT_ACTION.REFRESH) {
if (dis >= DisplayUtil.dip2px(getContext(), HEADER_HEIGHT)) {
if (refreshViewHolder != null) {
if (!isRefreshTiping) {
//提示只有一次
refreshViewHolder.willRefreshTips(headerView);
isRefreshTiping = true;
}
}
shouldRefresh = true;
} else {
shouldRefresh = false;
float ratio = dis / DisplayUtil.dip2px(getContext(), HEADER_HEIGHT);
if (refreshViewHolder != null && !isRefreshing)
refreshViewHolder.pullingTips(headerView, (int) (100 * Math.abs(ratio)));
}
if (dis >= 0 && (dis < totalLimit)) {
this.scrollBy(0, -(int) offsetY);
}
if (dis >= totalLimit) {
this.scrollTo(0, -totalLimit);
}
} else if ((intercept_action == INTERCEPT_ACTION.LOAD_MORE) && (dis < 0)) {
//上拉加载
this.scrollBy(0, -(int) offsetY);
if (Math.abs(dis) >= DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)) {
if (!isLoadMoreTiping) {
loadMoreViewHolder.willloadTips(bottomView);
isLoadMoreTiping = true;
}
shouldLoadMore = true;
} else {
shouldLoadMore = false;
float ratio = dis / DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT);
if (loadMoreViewHolder != null && !isLoadMoreing)
loadMoreViewHolder.loadTips(headerView, (int) (100 * Math.abs(ratio)));
}
}
tmpY = currentY;
break;
case MotionEvent.ACTION_UP:
smoothToZeroPos();
break;
case MotionEvent.ACTION_CANCEL:
smoothToZeroPos();
break;
}
return true;
}
private void startRefresh() {
if (refreshViewHolder != null) {
refreshViewHolder.refreshingTips(headerView);
//开始后台刷新任务
if (!isRefreshing)
new RefreshTask().execute();
}
}
private void startLoadMore() {
if (loadMoreViewHolder != null) {
loadMoreViewHolder.loadingTips(bottomView);
if (!isLoadMoreing) {
new LoadMoreTask().execute();
}
}
}
private void smoothToZeroPos() {
//下拉刷新
if (intercept_action == INTERCEPT_ACTION.REFRESH) {
if (shouldRefresh)
startRefresh();
} else if (intercept_action == INTERCEPT_ACTION.LOAD_MORE) {
//上拉加载更多
if (shouldLoadMore) {
startLoadMore();
}
}
smoothScrollTo(0, 0);
}
private void smoothScrollTo(int destX, int destY) {
int offsetY = destY - getScrollY();
scroller.startScroll(0, getScrollY(), 0, offsetY, 500);
invalidate();
}
@Override
public void computeScroll() {
super.computeScroll();
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
//下拉刷新-管理UI方面的接口
public interface RefreshViewHolder {
//还没到刷新点的提示
void pullingTips(View headerView, int progress);
//快要刷新时的提示
void willRefreshTips(View headerView);
//正在刷新时的状态
void refreshingTips(View headerView);
//刷新完毕
void refreshCompleteTips(View headerView);
}
//下拉刷新-管理事务方面的接口
public interface IRefreshAction {
void refresh();
void refreshComplete();
}
//上拉加载-管理UI 接口
public interface LoadMoreViewHolder {
//还没到加载点的提示
void loadTips(View headerView, int progress);
//快要加载时的提示
void willloadTips(View headerView);
//正在加载时的状态
void loadingTips(View headerView);
//加载完毕
void loadCompleteTips(View headerView);
}
public interface ILoadMoreAction {
void loadMore();
void loadMoreComplete();
}
//触摸点传递的接口,可供实现类扩展更多自定义动画
public interface onRefreshViewTouch {
void onTouch(int x, int y);
}
public View getHeaderView() {
return headerView;
}
public void setHeaderView(View headerView, RelativeLayout.LayoutParams layoutParams) {
this.headerView = headerView;
headerContent.removeViewAt(0);
RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
if (layoutParams == null)
headerView.setLayoutParams(defaultLayoutParams);
else
headerView.setLayoutParams(layoutParams);
headerContent.addView(headerView, 0);
}
public void setBottomView(View bottomView, RelativeLayout.LayoutParams layoutParams) {
this.bottomView = bottomView;
bottomContent.removeViewAt(0);
RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
if (layoutParams == null)
bottomView.setLayoutParams(defaultLayoutParams);
else
bottomView.setLayoutParams(layoutParams);
bottomContent.addView(bottomView, 0);
}
public RefreshViewHolder getRefreshViewHolder() {
return refreshViewHolder;
}
public void setRefreshViewHolder(RefreshViewHolder refreshViewHolder) {
this.refreshViewHolder = refreshViewHolder;
}
private class RefreshTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
isRefreshing = true;
shouldRefresh = false;
if (iRefreshAction != null) {
iRefreshAction.refresh();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
post(new Runnable() {
@Override
public void run() {
if (refreshViewHolder != null) {
refreshViewHolder.refreshCompleteTips(headerView);
smoothScrollTo(0, 0);
}
}
});
if (iRefreshAction != null) {
iRefreshAction.refreshComplete();
}
isRefreshing = false;
}
@Override
protected void onCancelled() {
super.onCancelled();
smoothScrollTo(0, 0);
shouldRefresh = false;
isRefreshing = false;
}
}
private class LoadMoreTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
isLoadMoreing = true;
shouldLoadMore = false;
if (iLoadMoreAction != null) {
iLoadMoreAction.loadMore();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
super.onPostExecute(aVoid);
post(new Runnable() {
@Override
public void run() {
if (loadMoreViewHolder != null) {
loadMoreViewHolder.loadCompleteTips(headerView);
smoothScrollTo(0, 0);
}
}
});
if (iLoadMoreAction != null) {
iLoadMoreAction.loadMoreComplete();
}
isLoadMoreing = false;
}
@Override
protected void onCancelled() {
super.onCancelled();
smoothScrollTo(0, 0);
shouldLoadMore = false;
isLoadMoreing = false;
}
}
public void setiRefreshAction(IRefreshAction iRefreshAction) {
this.iRefreshAction = iRefreshAction;
}
public ILoadMoreAction getiLoadMoreAction() {
return iLoadMoreAction;
}
public void setiLoadMoreAction(ILoadMoreAction iLoadMoreAction) {
this.iLoadMoreAction = iLoadMoreAction;
}
public LoadMoreViewHolder getLoadMoreViewHolder() {
return loadMoreViewHolder;
}
public void setLoadMoreViewHolder(LoadMoreViewHolder loadMoreViewHolder) {
this.loadMoreViewHolder = loadMoreViewHolder;
}
public KRefreshView.onRefreshViewTouch getOnRefreshViewTouch() {
return onRefreshViewTouch;
}
public void setOnRefreshViewTouch(KRefreshView.onRefreshViewTouch onRefreshViewTouch) {
this.onRefreshViewTouch = onRefreshViewTouch;
}
public void setHeaderHeight(int headerHeightDp) {
this.HEADER_HEIGHT = headerHeightDp;
totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT);
}
public int getMAX_LIMIT_SLOT() {
return MAX_LIMIT_SLOT;
}
public void setMAX_LIMIT_SLOT(int MAX_LIMIT_SLOT) {
this.MAX_LIMIT_SLOT = MAX_LIMIT_SLOT;
totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT);
}
public LoadMoreConfig getLoadMoreConfig() {
return loadMoreConfig;
}
public void setLoadMoreConfig(LoadMoreConfig loadMoreConfig) {
this.loadMoreConfig = loadMoreConfig;
if (loadMoreConfig.canLoadMore) {
if (loadMoreConfig.loadMoreView != null)
setBottomView(loadMoreConfig.loadMoreView, null);
if (loadMoreConfig.iLoadMoreAction != null)
setiLoadMoreAction(loadMoreConfig.iLoadMoreAction);
if (loadMoreConfig.loadMoreViewHolder != null)
setLoadMoreViewHolder(loadMoreConfig.loadMoreViewHolder);
if (loadMoreConfig.height > 0)
BOTTOM_HEIGHT = loadMoreConfig.height;
}
}
public static class LoadMoreConfig {
public boolean canLoadMore;
public View loadMoreView;
public ILoadMoreAction iLoadMoreAction;
public LoadMoreViewHolder loadMoreViewHolder;
public int height;
public LoadMoreConfig(boolean canLoadMore, View loadMoreView, ILoadMoreAction iLoadMoreAction, LoadMoreViewHolder loadMoreViewHolder, int height) {
this.canLoadMore = canLoadMore;
this.loadMoreView = loadMoreView;
this.iLoadMoreAction = iLoadMoreAction;
this.loadMoreViewHolder = loadMoreViewHolder;
this.height = height;
}
}
}
| 1 | 10 | 1 |
13778_4 | package com.hotel.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
/**
* @author guangyong.yang
* @date 2019-01-15
* @description 客人
*/
@Getter
@Setter
@Entity
@Table(name = "customer")
public class Customer {
/**
* id
*/
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 姓名
*/
@Column(nullable = false,length = 80)
private String name;
/**
* 身份证号
*/
@Column(nullable = false,length = 18)
private String idCard;
/**
* 手机号
*/
@Column(length = 11)
private String phoneNo;
/**
* 房间
*/
@ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "customers")
private List<Room> rooms;
@Column(length = 100)
private String comment;
}
| Cool-Coding/angular-springboot-demo | hotel-server/src/main/java/com/hotel/entity/Customer.java | 263 | /**
* 手机号
*/ | block_comment | zh-cn | package com.hotel.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
/**
* @author guangyong.yang
* @date 2019-01-15
* @description 客人
*/
@Getter
@Setter
@Entity
@Table(name = "customer")
public class Customer {
/**
* id
*/
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 姓名
*/
@Column(nullable = false,length = 80)
private String name;
/**
* 身份证号
*/
@Column(nullable = false,length = 18)
private String idCard;
/**
* 手机号 <SUF>*/
@Column(length = 11)
private String phoneNo;
/**
* 房间
*/
@ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "customers")
private List<Room> rooms;
@Column(length = 100)
private String comment;
}
| 1 | 22 | 1 |
34852_9 | package cn.yang.domain;
import java.sql.Blob;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 用户(会员)
* @author <a href="mailto:[email protected]">ygy</a>
*2011-4-7
*
*/
@Entity
public class User {
// --- 基本信息
private String loginName;// 登录名(唯一),最长为128个字符
private String password;// 密码,最长为128个字符
private String email;// Email地址,最长为128个字符
// --- 个人信息
private String nickname;// 昵称,最多128个字符,64个汉字
private Gender gender; // 性别
private byte[] avatar;// 头像
private String signature;// 签名,最多127个汉字
private Integer score=0;//积分
private String rank;//等级
// --- 其他
private Date registrationTime;// 注册时间
private Date lastVisitTime; // 最后(上次)访问时间
private String lastVisitIpAddr; // 最后(上次)访问时所使用的ip地址
private int themeCount=0;// 发表的总主题数
private int replyCount=0;// 发表的总回复数
private boolean locked;// 是否被锁定
private String autoLoginAuthKey;// 用于自动登陆的一个认证的字符串
// private String activationKey;// 锁定用户自己激活帐号所用的激活码
private Set<Role> roles = new HashSet<Role>(0);// 所拥有的角色(权限)
public User(){}
public User(String loginName){
this.loginName=loginName;
}
@Id @Column(length=128)
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
@Column(length=128)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length=128)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(length=128)
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Enumerated(EnumType.STRING)
@Column(length=6)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
@Lob @Basic(fetch=FetchType.LAZY)
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
@Column(length=255)
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getRegistrationTime() {
return registrationTime;
}
public void setRegistrationTime(Date registrationTime) {
this.registrationTime = registrationTime;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date lastVisitTime) {
this.lastVisitTime = lastVisitTime;
}
@Column(length=15)
public String getLastVisitIpAddr() {
return lastVisitIpAddr;
}
public void setLastVisitIpAddr(String lastVisitIpAddr) {
this.lastVisitIpAddr = lastVisitIpAddr;
}
@Column(length=1)
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Column(nullable=false)
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Column(length=20)
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
@Column(nullable=false)
public int getThemeCount() {
return themeCount;
}
public void setThemeCount(int themeCount) {
this.themeCount = themeCount;
}
@Column(nullable=false)
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
@Column(length=128)
public String getAutoLoginAuthKey() {
return autoLoginAuthKey;
}
public void setAutoLoginAuthKey(String autoLoginAuthKey) {
this.autoLoginAuthKey = autoLoginAuthKey;
}
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="user_loginName", referencedColumnName="loginName"),
inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id")
)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return new StringBuffer().append("[User: ")//
.append(",loginName=").append(loginName)//
.append(",email=").append(email)//
.append(",registrationTime=").append(registrationTime)//
.append(",nickname=").append(nickname)//
.append(",replyCount=").append(themeCount)//
.append(",replyCount=").append(replyCount)//
.append("]")//
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((loginName == null) ? 0 : loginName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (loginName == null) {
if (other.loginName != null)
return false;
} else if (!loginName.equals(other.loginName))
return false;
return true;
}
}
| Cool-Coding/bbs | src/cn/yang/domain/User.java | 1,828 | // 注册时间 | line_comment | zh-cn | package cn.yang.domain;
import java.sql.Blob;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 用户(会员)
* @author <a href="mailto:[email protected]">ygy</a>
*2011-4-7
*
*/
@Entity
public class User {
// --- 基本信息
private String loginName;// 登录名(唯一),最长为128个字符
private String password;// 密码,最长为128个字符
private String email;// Email地址,最长为128个字符
// --- 个人信息
private String nickname;// 昵称,最多128个字符,64个汉字
private Gender gender; // 性别
private byte[] avatar;// 头像
private String signature;// 签名,最多127个汉字
private Integer score=0;//积分
private String rank;//等级
// --- 其他
private Date registrationTime;// 注册 <SUF>
private Date lastVisitTime; // 最后(上次)访问时间
private String lastVisitIpAddr; // 最后(上次)访问时所使用的ip地址
private int themeCount=0;// 发表的总主题数
private int replyCount=0;// 发表的总回复数
private boolean locked;// 是否被锁定
private String autoLoginAuthKey;// 用于自动登陆的一个认证的字符串
// private String activationKey;// 锁定用户自己激活帐号所用的激活码
private Set<Role> roles = new HashSet<Role>(0);// 所拥有的角色(权限)
public User(){}
public User(String loginName){
this.loginName=loginName;
}
@Id @Column(length=128)
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
@Column(length=128)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length=128)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(length=128)
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Enumerated(EnumType.STRING)
@Column(length=6)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
@Lob @Basic(fetch=FetchType.LAZY)
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
@Column(length=255)
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getRegistrationTime() {
return registrationTime;
}
public void setRegistrationTime(Date registrationTime) {
this.registrationTime = registrationTime;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date lastVisitTime) {
this.lastVisitTime = lastVisitTime;
}
@Column(length=15)
public String getLastVisitIpAddr() {
return lastVisitIpAddr;
}
public void setLastVisitIpAddr(String lastVisitIpAddr) {
this.lastVisitIpAddr = lastVisitIpAddr;
}
@Column(length=1)
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Column(nullable=false)
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Column(length=20)
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
@Column(nullable=false)
public int getThemeCount() {
return themeCount;
}
public void setThemeCount(int themeCount) {
this.themeCount = themeCount;
}
@Column(nullable=false)
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
@Column(length=128)
public String getAutoLoginAuthKey() {
return autoLoginAuthKey;
}
public void setAutoLoginAuthKey(String autoLoginAuthKey) {
this.autoLoginAuthKey = autoLoginAuthKey;
}
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="user_loginName", referencedColumnName="loginName"),
inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id")
)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return new StringBuffer().append("[User: ")//
.append(",loginName=").append(loginName)//
.append(",email=").append(email)//
.append(",registrationTime=").append(registrationTime)//
.append(",nickname=").append(nickname)//
.append(",replyCount=").append(themeCount)//
.append(",replyCount=").append(replyCount)//
.append("]")//
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((loginName == null) ? 0 : loginName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (loginName == null) {
if (other.loginName != null)
return false;
} else if (!loginName.equals(other.loginName))
return false;
return true;
}
}
| 1 | 7 | 1 |
58594_9 | package fun.fifu.ridwk;
import com.alkaidmc.alkaid.bukkit.command.AlkaidCommand;
import com.alkaidmc.alkaid.bukkit.event.AlkaidEvent;
import lombok.Data;
import lombok.experimental.Accessors;
import org.bukkit.Bukkit;
import org.bukkit.GameRule;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
public class RandomItemDropsWhenKilled extends JavaPlugin implements Listener {
private static final Random random = new Random();
// 受害者 -> 施暴者
public static final Map<Player, Player> damageMap = new HashMap<>();
public static RandomItemDropsWhenKilled randomItemDropsWhenKilled;
@Override
public void onLoad() {
randomItemDropsWhenKilled = this;
}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
// 死亡不掉落
new AlkaidEvent(this).simple()
.event(WorldLoadEvent.class)
.listener(event -> {
event.getWorld().setGameRule(GameRule.KEEP_INVENTORY, true);
getLogger().info(event.getWorld().getName() + " 的死亡不掉落已开启");
})
.priority(EventPriority.HIGHEST)
.ignore(false)
.register();
// 进服欢迎
new AlkaidEvent(this).simple()
.event(PlayerJoinEvent.class)
.listener(event -> {
Bukkit.getOnlinePlayers().forEach(player -> {
player.sendMessage("欢迎" + event.getPlayer().getDisplayName() + "来到服务器");
});
})
.priority(EventPriority.HIGHEST)
.ignore(false)
.register();
// 掠夺 劫夺图腾
new AlkaidEvent(this).simple()
.event(PlayerDeathEvent.class)
.listener(event -> {
randomDropItems(event.getEntity());
dropAllItems(event.getEntity());
})
.priority(EventPriority.HIGHEST)
.ignore(false)
.register();
// 命令:给物品标记掠夺属性
new AlkaidCommand(this).simple()
.command("ridwkAddPlunder")
.description("将手上的物品标记为" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "物品")
.permission("ridwk.add-plunder")
.usage("/ridwkAddPlunder 将手上的物品标记为" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "物品")
.executor((sender, command, label, args) -> {
if (!(sender instanceof Player player))
return true;
ItemStack itemInMainHand = player.getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return true;
makePlunderItem(itemInMainHand);
player.sendMessage("已为物品添加" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "属性");
return true;
})
.register();
// 伪命令:写物品标签
NekoUtil.makePlayerConmmand("ridwk.add-plunder.writeTag", "#ridwk-writeTag", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
NekoUtil.makeTagItem(itemInMainHand, res.args()[1]);
res.player().sendMessage("已标记 " + res.args()[1] + " 标签");
});
// TODO 临时命令:给物品标记掠夺属性
makePlayerConmmand("ridwk.add-plunder", "ridwkAddPlunder", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
makePlunderItem(itemInMainHand);
res.player().sendMessage("已为物品添加" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "属性");
});
// TODO 临时命令:查看手上物品耐久
makePlayerConmmand("ridwk.add-plunder", "readDurable", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
res.player().sendMessage("物品耐久为" + readItemDurable(itemInMainHand));
});
// TODO 临时命令:设置手上物品耐久
makePlayerConmmand("ridwk.add-plunder", "writeDurable", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
var num = Integer.parseInt(res.args()[1]);
writeItemDurable(itemInMainHand, num);
res.player().sendMessage("物品耐久已经设置为" + num);
});
}
@Override
public void onDisable() {
damageMap.clear();
}
@EventHandler
public void tagDamage(EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player player && event.getDamager() instanceof Player damage) {
damageMap.put(player, damage);
}
}
/**
* 检查玩家背包是否携带掠夺物品,若检查到,则消费该物品一个耐久
*
* @return true:携带 false:不携带
*/
public boolean hasPlunderItemAndSpend(Player player) {
AtomicBoolean has = new AtomicBoolean(false);
player.getInventory().forEach(itemStack -> {
if (itemStack == null || itemStack.getType().isAir())
return;
if (hasPlunderItem(itemStack)) {
var num = readItemDurable(itemStack);
if (--num > 0) {
has.set(true);
writeItemDurable(itemStack, num);
} else {
itemStack.setAmount(0);
player.sendMessage("因为使用次数耗尽,你消耗了一个掠夺符");
}
}
});
return has.get();
}
/**
* 检查物品是否携带掠夺物品
*
* @return true:携带 false:不携带
*/
public boolean hasPlunderItem(ItemStack itemStack) {
AtomicBoolean is = new AtomicBoolean(false);
if (itemStack == null || itemStack.getType().isAir())
return false;
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null)
return false;
List<String> lore = itemMeta.getLore();
if (lore == null)
return false;
lore.stream().filter(s -> s.contains(PluginConfig.INSTEN_CONFIG.getPlunderTag())).forEach(s -> is.set(true));
return is.get();
}
/**
* 标记物品为掠夺物品
*
* @param itemStack 待标记的物品
*/
public void makePlunderItem(ItemStack itemStack) {
if (hasPlunderItem(itemStack))
return;
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null)
return;
List<String> lore = itemMeta.getLore();
if (lore == null)
lore = new ArrayList<>();
lore.add(0, PluginConfig.INSTEN_CONFIG.getPlunderTag());
itemMeta.setLore(lore);
itemStack.setItemMeta(itemMeta);
writeItemDurable(itemStack, PluginConfig.INSTEN_CONFIG.getDefaultDurableNum());
}
/**
* 让指定玩家随机掉落物品
*
* @param player 目标玩家
*/
public void randomDropItems(Player player) {
PlayerInventory inventory = player.getInventory();
Player damage = damageMap.get(player);
if (damage == null)
return;
if (!hasPlunderItemAndSpend(damage))
return;
inventory.forEach(itemStack -> {
if (random.nextDouble() > PluginConfig.INSTEN_CONFIG.getDropProbability())
return;
if (itemStack == null || itemStack.getType().isAir())
return;
int dropNum = random.nextInt(itemStack.getAmount());
int num = itemStack.getAmount() - dropNum;
if (num < 0) {
num = 0;
dropNum = itemStack.getAmount();
}
if (dropNum == 0)
return;
ItemStack drop = itemStack.clone();
drop.setAmount(dropNum);
itemStack.setAmount(num);
player.getWorld().dropItem(player.getLocation(), drop);
});
}
/**
* 让指定玩家掉落所有物品
*
* @param player 目标玩家
*/
public void dropAllItems(Player player) {
var tag = "劫夺图腾";
PlayerInventory inventory = player.getInventory();
Player damage = damageMap.get(player);
if (damage == null)
return;
if (!NekoUtil.hasTagItem(damage.getInventory(), tag))
return;
NekoUtil.spendTagItem(damage.getInventory(), tag);
damage.sendMessage("你使用了一个 " + tag);
inventory.forEach(itemStack -> {
if (itemStack == null || itemStack.getType().isAir())
return;
int dropNum = itemStack.getAmount();
int num = itemStack.getAmount() - dropNum;
if (num < 0) {
num = 0;
dropNum = itemStack.getAmount();
}
if (dropNum == 0)
return;
ItemStack drop = itemStack.clone();
drop.setAmount(dropNum);
itemStack.setAmount(num);
player.getWorld().dropItem(player.getLocation(), drop);
});
}
/**
* 读取指定物品堆的耐久
*
* @param itemStack 要读取耐久的物品堆
* @return 该物品的剩余使用次数
*/
public int readItemDurable(ItemStack itemStack) {
var itemMeta = itemStack.getItemMeta();
if (!itemMeta.hasLore())
return -1;
String text = itemMeta.getLore().stream()
.filter(s -> s.contains(PluginConfig.INSTEN_CONFIG.getDurableTag()))
.findFirst().orElse("-1");
if (text == null)
return 0;
return Integer.parseInt(text.replaceAll(PluginConfig.INSTEN_CONFIG.getDurableTag(), ""));
}
/**
* 设置指定物品堆的耐久
*
* @param itemStack 要设置耐久的物品堆
*/
public void writeItemDurable(ItemStack itemStack, int num) {
var itemMeta = itemStack.getItemMeta();
var lore = itemMeta.getLore();
if (lore == null)
lore = new ArrayList<>();
if (readItemDurable(itemStack) == -1) {
lore.add(PluginConfig.INSTEN_CONFIG.durableTag + num);
} else {
for (int i = 0; i < lore.size(); i++)
if (lore.get(i).contains(PluginConfig.INSTEN_CONFIG.getDurableTag()))
lore.set(i, PluginConfig.INSTEN_CONFIG.durableTag + num);
}
if (num <= 0) {
for (int i = 0; i < lore.size(); i++)
if (lore.get(i).contains(PluginConfig.INSTEN_CONFIG.getDurableTag()))
lore.remove(i);
}
itemMeta.setLore(lore);
itemStack.setItemMeta(itemMeta);
}
@Data
@Accessors(fluent = true, chain = true)
private static class Res {
private Player player;
private String[] args;
}
/**
* 构建一个伪命令,玩家用聊天的形式触发
*
* @param permission 触发命令所需的权限
* @param command 命令内容
* @param exec 触发后执行的代码
*/
public static void makePlayerConmmand(String permission, String command, Consumer<Res> exec) {
new AlkaidEvent(RandomItemDropsWhenKilled.randomItemDropsWhenKilled).simple()
.event(AsyncPlayerChatEvent.class)
.listener(event -> {
var args = event.getMessage().split(" ");
if (!args[0].equalsIgnoreCase(command))
return;
Player player = event.getPlayer();
if (player.hasPermission(permission)) {
exec.accept(new Res()
.player(player)
.args(args));
} else {
player.sendMessage("你没有 " + permission + " 权限,无法使用 " + command + " 命令");
return;
}
event.setCancelled(true);
})
.priority(EventPriority.HIGHEST)
.ignore(true)
.register();
}
}
| Core2002/RandomItemDropsWhenKilled | src/main/java/fun/fifu/ridwk/RandomItemDropsWhenKilled.java | 3,265 | /**
* 检查玩家背包是否携带掠夺物品,若检查到,则消费该物品一个耐久
*
* @return true:携带 false:不携带
*/ | block_comment | zh-cn | package fun.fifu.ridwk;
import com.alkaidmc.alkaid.bukkit.command.AlkaidCommand;
import com.alkaidmc.alkaid.bukkit.event.AlkaidEvent;
import lombok.Data;
import lombok.experimental.Accessors;
import org.bukkit.Bukkit;
import org.bukkit.GameRule;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
public class RandomItemDropsWhenKilled extends JavaPlugin implements Listener {
private static final Random random = new Random();
// 受害者 -> 施暴者
public static final Map<Player, Player> damageMap = new HashMap<>();
public static RandomItemDropsWhenKilled randomItemDropsWhenKilled;
@Override
public void onLoad() {
randomItemDropsWhenKilled = this;
}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
// 死亡不掉落
new AlkaidEvent(this).simple()
.event(WorldLoadEvent.class)
.listener(event -> {
event.getWorld().setGameRule(GameRule.KEEP_INVENTORY, true);
getLogger().info(event.getWorld().getName() + " 的死亡不掉落已开启");
})
.priority(EventPriority.HIGHEST)
.ignore(false)
.register();
// 进服欢迎
new AlkaidEvent(this).simple()
.event(PlayerJoinEvent.class)
.listener(event -> {
Bukkit.getOnlinePlayers().forEach(player -> {
player.sendMessage("欢迎" + event.getPlayer().getDisplayName() + "来到服务器");
});
})
.priority(EventPriority.HIGHEST)
.ignore(false)
.register();
// 掠夺 劫夺图腾
new AlkaidEvent(this).simple()
.event(PlayerDeathEvent.class)
.listener(event -> {
randomDropItems(event.getEntity());
dropAllItems(event.getEntity());
})
.priority(EventPriority.HIGHEST)
.ignore(false)
.register();
// 命令:给物品标记掠夺属性
new AlkaidCommand(this).simple()
.command("ridwkAddPlunder")
.description("将手上的物品标记为" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "物品")
.permission("ridwk.add-plunder")
.usage("/ridwkAddPlunder 将手上的物品标记为" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "物品")
.executor((sender, command, label, args) -> {
if (!(sender instanceof Player player))
return true;
ItemStack itemInMainHand = player.getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return true;
makePlunderItem(itemInMainHand);
player.sendMessage("已为物品添加" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "属性");
return true;
})
.register();
// 伪命令:写物品标签
NekoUtil.makePlayerConmmand("ridwk.add-plunder.writeTag", "#ridwk-writeTag", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
NekoUtil.makeTagItem(itemInMainHand, res.args()[1]);
res.player().sendMessage("已标记 " + res.args()[1] + " 标签");
});
// TODO 临时命令:给物品标记掠夺属性
makePlayerConmmand("ridwk.add-plunder", "ridwkAddPlunder", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
makePlunderItem(itemInMainHand);
res.player().sendMessage("已为物品添加" + PluginConfig.INSTEN_CONFIG.getPlunderTag() + "属性");
});
// TODO 临时命令:查看手上物品耐久
makePlayerConmmand("ridwk.add-plunder", "readDurable", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
res.player().sendMessage("物品耐久为" + readItemDurable(itemInMainHand));
});
// TODO 临时命令:设置手上物品耐久
makePlayerConmmand("ridwk.add-plunder", "writeDurable", res -> {
ItemStack itemInMainHand = res.player().getInventory().getItemInMainHand();
if (itemInMainHand.getType().isAir())
return;
var num = Integer.parseInt(res.args()[1]);
writeItemDurable(itemInMainHand, num);
res.player().sendMessage("物品耐久已经设置为" + num);
});
}
@Override
public void onDisable() {
damageMap.clear();
}
@EventHandler
public void tagDamage(EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player player && event.getDamager() instanceof Player damage) {
damageMap.put(player, damage);
}
}
/**
* 检查玩 <SUF>*/
public boolean hasPlunderItemAndSpend(Player player) {
AtomicBoolean has = new AtomicBoolean(false);
player.getInventory().forEach(itemStack -> {
if (itemStack == null || itemStack.getType().isAir())
return;
if (hasPlunderItem(itemStack)) {
var num = readItemDurable(itemStack);
if (--num > 0) {
has.set(true);
writeItemDurable(itemStack, num);
} else {
itemStack.setAmount(0);
player.sendMessage("因为使用次数耗尽,你消耗了一个掠夺符");
}
}
});
return has.get();
}
/**
* 检查物品是否携带掠夺物品
*
* @return true:携带 false:不携带
*/
public boolean hasPlunderItem(ItemStack itemStack) {
AtomicBoolean is = new AtomicBoolean(false);
if (itemStack == null || itemStack.getType().isAir())
return false;
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null)
return false;
List<String> lore = itemMeta.getLore();
if (lore == null)
return false;
lore.stream().filter(s -> s.contains(PluginConfig.INSTEN_CONFIG.getPlunderTag())).forEach(s -> is.set(true));
return is.get();
}
/**
* 标记物品为掠夺物品
*
* @param itemStack 待标记的物品
*/
public void makePlunderItem(ItemStack itemStack) {
if (hasPlunderItem(itemStack))
return;
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null)
return;
List<String> lore = itemMeta.getLore();
if (lore == null)
lore = new ArrayList<>();
lore.add(0, PluginConfig.INSTEN_CONFIG.getPlunderTag());
itemMeta.setLore(lore);
itemStack.setItemMeta(itemMeta);
writeItemDurable(itemStack, PluginConfig.INSTEN_CONFIG.getDefaultDurableNum());
}
/**
* 让指定玩家随机掉落物品
*
* @param player 目标玩家
*/
public void randomDropItems(Player player) {
PlayerInventory inventory = player.getInventory();
Player damage = damageMap.get(player);
if (damage == null)
return;
if (!hasPlunderItemAndSpend(damage))
return;
inventory.forEach(itemStack -> {
if (random.nextDouble() > PluginConfig.INSTEN_CONFIG.getDropProbability())
return;
if (itemStack == null || itemStack.getType().isAir())
return;
int dropNum = random.nextInt(itemStack.getAmount());
int num = itemStack.getAmount() - dropNum;
if (num < 0) {
num = 0;
dropNum = itemStack.getAmount();
}
if (dropNum == 0)
return;
ItemStack drop = itemStack.clone();
drop.setAmount(dropNum);
itemStack.setAmount(num);
player.getWorld().dropItem(player.getLocation(), drop);
});
}
/**
* 让指定玩家掉落所有物品
*
* @param player 目标玩家
*/
public void dropAllItems(Player player) {
var tag = "劫夺图腾";
PlayerInventory inventory = player.getInventory();
Player damage = damageMap.get(player);
if (damage == null)
return;
if (!NekoUtil.hasTagItem(damage.getInventory(), tag))
return;
NekoUtil.spendTagItem(damage.getInventory(), tag);
damage.sendMessage("你使用了一个 " + tag);
inventory.forEach(itemStack -> {
if (itemStack == null || itemStack.getType().isAir())
return;
int dropNum = itemStack.getAmount();
int num = itemStack.getAmount() - dropNum;
if (num < 0) {
num = 0;
dropNum = itemStack.getAmount();
}
if (dropNum == 0)
return;
ItemStack drop = itemStack.clone();
drop.setAmount(dropNum);
itemStack.setAmount(num);
player.getWorld().dropItem(player.getLocation(), drop);
});
}
/**
* 读取指定物品堆的耐久
*
* @param itemStack 要读取耐久的物品堆
* @return 该物品的剩余使用次数
*/
public int readItemDurable(ItemStack itemStack) {
var itemMeta = itemStack.getItemMeta();
if (!itemMeta.hasLore())
return -1;
String text = itemMeta.getLore().stream()
.filter(s -> s.contains(PluginConfig.INSTEN_CONFIG.getDurableTag()))
.findFirst().orElse("-1");
if (text == null)
return 0;
return Integer.parseInt(text.replaceAll(PluginConfig.INSTEN_CONFIG.getDurableTag(), ""));
}
/**
* 设置指定物品堆的耐久
*
* @param itemStack 要设置耐久的物品堆
*/
public void writeItemDurable(ItemStack itemStack, int num) {
var itemMeta = itemStack.getItemMeta();
var lore = itemMeta.getLore();
if (lore == null)
lore = new ArrayList<>();
if (readItemDurable(itemStack) == -1) {
lore.add(PluginConfig.INSTEN_CONFIG.durableTag + num);
} else {
for (int i = 0; i < lore.size(); i++)
if (lore.get(i).contains(PluginConfig.INSTEN_CONFIG.getDurableTag()))
lore.set(i, PluginConfig.INSTEN_CONFIG.durableTag + num);
}
if (num <= 0) {
for (int i = 0; i < lore.size(); i++)
if (lore.get(i).contains(PluginConfig.INSTEN_CONFIG.getDurableTag()))
lore.remove(i);
}
itemMeta.setLore(lore);
itemStack.setItemMeta(itemMeta);
}
@Data
@Accessors(fluent = true, chain = true)
private static class Res {
private Player player;
private String[] args;
}
/**
* 构建一个伪命令,玩家用聊天的形式触发
*
* @param permission 触发命令所需的权限
* @param command 命令内容
* @param exec 触发后执行的代码
*/
public static void makePlayerConmmand(String permission, String command, Consumer<Res> exec) {
new AlkaidEvent(RandomItemDropsWhenKilled.randomItemDropsWhenKilled).simple()
.event(AsyncPlayerChatEvent.class)
.listener(event -> {
var args = event.getMessage().split(" ");
if (!args[0].equalsIgnoreCase(command))
return;
Player player = event.getPlayer();
if (player.hasPermission(permission)) {
exec.accept(new Res()
.player(player)
.args(args));
} else {
player.sendMessage("你没有 " + permission + " 权限,无法使用 " + command + " 命令");
return;
}
event.setCancelled(true);
})
.priority(EventPriority.HIGHEST)
.ignore(true)
.register();
}
}
| 0 | 89 | 0 |
44051_75 | package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import model.sys.Config.FILE_TYPE;
import model.sys.FCB;
import view.DocumentIconPanel;
import view.EditView;
import view.MainView;
import com.google.gson.Gson;
/**
*
* @author Tom Hu
*
*/
public class MainController {
private MainView view;
private SystemCore systemCore;
/**
* 构造函数
*/
public MainController() {
super();
// Initialize systemCore
this.systemCore = new SystemCore();
// UI Methods
this.configureMainView();
}
// UI Methods
/**
* 初始化主界面
*/
private void configureMainView() {
// 根据当前目录文件初始化view
this.view = new MainView(this.systemCore.currentDir);
// 添加右键监听
this.view.addRightClickListener(this.rightClickListener);
// 添加后退按钮监听
this.view.addBackButtonActionListener(this.backButtonActionListener);
// 添加前往按钮监听
this.view.addGoButtonActionListener(this.goButtonActionListener);
// 添加关闭事件监听
this.view.addWindowListener(this.mainWindowListener);
this.configureContentPanel();
// 显示当前路径
this.view.addressTextField.setText(this.systemCore.getCurrentPath());
}
/**
* 初始化内容面板
*/
private void configureContentPanel() {
// 为每个图标添加监听
this.addListenerForEachDocumentIcon();
}
/**
* 显示主界面
*/
public void showMainView() {
this.view.showView();
}
/**
* 显示编辑界面
*
* @param fcb
* 需要编辑的文件的FCB
*/
private void showEditView(FCB fcb) {
// 弹出Edit View,根据FCB加载
EditView editView = new EditView(fcb,
MainController.this.systemCore.readFile(fcb));
// 为Edit Window添加监听
editView.addWindowListener(MainController.this.editWindowListener);
// 显示Edit View
editView.setVisible(true);
}
// Listener
/**
* 主界面内容面板右键点击监听
*/
private MouseListener rightClickListener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// Deselect documents
if (e.getButton() == MouseEvent.BUTTON1) {
MainController.this.view.deselectDocuments();
}
// Popup menu
if (e.getButton() == MouseEvent.BUTTON3) {
boolean isRoot = (MainController.this.systemCore.currentDirFCB.fatherBlockId == -1);
JPopupMenu menu = new JPopupMenu();
JMenuItem newFileMenu = new JMenuItem("New File", KeyEvent.VK_N);
newFileMenu.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_N, ActionEvent.CTRL_MASK));
newFileMenu
.addActionListener(MainController.this.newFileActionListener);
menu.add(newFileMenu);
JMenuItem newFolderMenu = new JMenuItem("New Folder",
KeyEvent.VK_F);
newFolderMenu.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F, ActionEvent.CTRL_MASK));
newFolderMenu
.addActionListener(MainController.this.newFolderActionListener);
menu.add(newFolderMenu);
if (isRoot) {
menu.addSeparator();
JMenuItem formatMenu = new JMenuItem("Format");
formatMenu
.addActionListener(MainController.this.formatMenuActionListener);
menu.add(formatMenu);
}
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
/**
* 图标点击监听,包括单击选中,双击打开,右键弹出菜单
*/
private MouseListener documentIconPanelMouseListener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// Select current document
MainController.this.view.deselectDocuments();
DocumentIconPanel d = (DocumentIconPanel) e.getComponent();
d.setSelected(true);
// 获取文件FCB
FCB fcb = MainController.this.systemCore.getFCB(d.getFilename(),
d.getType());
// Double click
if (e.getClickCount() == 2) {
// 判断双击的类型
if (d.getType() == FILE_TYPE.DIRECTORY) {
// 双击文件夹
// model进入下一级文件夹
MainController.this.systemCore.enterDir(d.getFilename());
// 重绘view
MainController.this.refreshView();
} else {
// 双击文件
// 显示编辑窗口
MainController.this.showEditView(fcb);
}
System.out.println("Double Click");
}
// Right click
if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu documentMenu = new JPopupMenu();
JMenuItem openMenuItem = new JMenuItem("Open", KeyEvent.VK_O);
MainController.this.openMenuActionListener.fcb = fcb;
openMenuItem
.addActionListener(MainController.this.openMenuActionListener);
documentMenu.add(openMenuItem);
if (d.getType() == FILE_TYPE.FILE) {
JMenuItem editMenuItem = new JMenuItem("Edit",
KeyEvent.VK_E);
MainController.this.editMenuActionListener.fcb = fcb;
editMenuItem
.addActionListener(MainController.this.editMenuActionListener);
documentMenu.add(editMenuItem);
}
JMenuItem renameMenuItem = new JMenuItem("Rename",
KeyEvent.VK_R);
MainController.this.renameMenuActionListener.fcb = fcb;
renameMenuItem
.addActionListener(MainController.this.renameMenuActionListener);
documentMenu.add(renameMenuItem);
documentMenu.addSeparator();
JMenuItem getInfoMenuItem = new JMenuItem("Get info",
KeyEvent.VK_I);
MainController.this.getInfoMenuActionListener.fcb = fcb;
getInfoMenuItem
.addActionListener(MainController.this.getInfoMenuActionListener);
documentMenu.add(getInfoMenuItem);
documentMenu.addSeparator();
JMenuItem deleteMenuItem = new JMenuItem("Delete",
KeyEvent.VK_D);
MainController.this.deleteMenuActionListener.fcb = fcb;
deleteMenuItem
.addActionListener(MainController.this.deleteMenuActionListener);
documentMenu.add(deleteMenuItem);
documentMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
/**
* 监听新建文件的按钮
*/
private ActionListener newFileActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 新建文件
// 获取文件名
String filename = (String) JOptionPane.showInputDialog(
MainController.this.view,
"Please enter your new file's name:", "New file",
JOptionPane.INFORMATION_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
// 不允许文件名为空
while (filename.equals("")) {
filename = (String) JOptionPane
.showInputDialog(
MainController.this.view,
"Filename cannot be empty! \nPlease enter your new file's name:",
"New file", JOptionPane.WARNING_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
}
if (MainController.this.systemCore.createFile(filename)) {
// 添加到model成功,即创建文件成功
// 添加到view
DocumentIconPanel d = new DocumentIconPanel(FILE_TYPE.FILE,
filename);
d.addMouseListener(MainController.this.documentIconPanelMouseListener);
MainController.this.view.addDocument(d);
} else {
// 创建文件失败
// 可能是有重名,也可能空间不够
// 弹出错误信息框
JOptionPane
.showMessageDialog(
MainController.this.view,
"Two possible reasons:\n1. The name \""
+ filename
+ "\" is already taken. Please choose a different name.\n2. Not enough disk space available. Delete some files.",
"New file error", JOptionPane.ERROR_MESSAGE);
}
}
};
/**
* 监听新建文件夹的按钮
*/
private ActionListener newFolderActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 新建文件夹
// 获取文件名
String filename = (String) JOptionPane.showInputDialog(
MainController.this.view,
"Please enter your new folder's name:", "New folder",
JOptionPane.INFORMATION_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
// 不允许文件名为空
while (filename.equals("")) {
filename = (String) JOptionPane
.showInputDialog(
MainController.this.view,
"Folder's name cannot be empty! \nPlease enter your new folder's name:",
"New folder", JOptionPane.WARNING_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
}
if (MainController.this.systemCore.createDir(filename)) {
// 添加到model成功,即创建文件夹成功
// 添加到view
DocumentIconPanel d = new DocumentIconPanel(
FILE_TYPE.DIRECTORY, filename);
d.addMouseListener(MainController.this.documentIconPanelMouseListener);
MainController.this.view.addDocument(d);
} else {
// 创建文件夹失败
// 可能是有重名,也可能空间不够
// 弹出错误信息框
JOptionPane
.showMessageDialog(
MainController.this.view,
"Two possible reasons:\n1. The name \""
+ filename
+ "\" is already taken. Please choose a different name.\n2. Not enough disk space available. Delete some files.",
"New folder error", JOptionPane.ERROR_MESSAGE);
}
}
};
private class CustomActionListener implements ActionListener {
public FCB fcb = null;
@Override
public void actionPerformed(ActionEvent e) {
}
}
/**
* "编辑"按钮按键监听
*/
private CustomActionListener editMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MainController.this.showEditView(this.fcb);
}
};
/**
* "打开"按钮按键监听
*/
private CustomActionListener openMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (this.fcb.type == FILE_TYPE.DIRECTORY) {
// model进入下一级文件夹
MainController.this.systemCore.enterDir(this.fcb.filename);
// 重绘view
MainController.this.refreshView();
} else {
// 显示编辑窗口
MainController.this.showEditView(fcb);
}
}
};
/**
* "删除"按钮按键监听
*/
private CustomActionListener deleteMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取用户的选择
int result = JOptionPane.showConfirmDialog(
MainController.this.view,
"Are you sure you want to permanently delete this item?",
"Delete", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
// 确定删除
if (this.fcb.type == FILE_TYPE.DIRECTORY) {
// model删除文件夹
MainController.this.systemCore.deleteDir(this.fcb.filename);
} else {
// model删除文件
MainController.this.systemCore
.deleteFile(this.fcb.filename);
}
// 重绘view
MainController.this.refreshView();
}
}
};
/**
* "重命名"按钮按键监听
*/
private CustomActionListener renameMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取文件名
String filename = (String) JOptionPane.showInputDialog(
MainController.this.view, "Folder name:", "Rename",
JOptionPane.INFORMATION_MESSAGE, null, null,
this.fcb.filename);
if (filename == null) {
// 用户取消
return;
}
// 不允许文件名为空
while (filename.equals("")) {
filename = (String) JOptionPane.showInputDialog(
MainController.this.view, "Folder name:", "Rename",
JOptionPane.INFORMATION_MESSAGE, null, null,
this.fcb.filename);
}
this.fcb.filename = filename;
Gson gson = new Gson();
// 更新文件FCB
MainController.this.systemCore.updateFCB(this.fcb);
// 更新当前目录的目录文件
MainController.this.systemCore.updateFile(
MainController.this.systemCore.currentDirFCB,
gson.toJson(MainController.this.systemCore.currentDir));
// 刷新界面
MainController.this.refreshView();
}
};
/**
* "格式化"按钮按键监听
*/
private ActionListener formatMenuActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取用户的选择
int result = JOptionPane
.showConfirmDialog(
MainController.this.view,
"All the data will be erased from the disk.\nAre you sure to FORMAT disk?",
"FORMAT!!", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
// 确定格式化
MainController.this.systemCore.format();
}
// 刷新界面
MainController.this.refreshView();
}
};
/**
* "属性"按钮按键监听
*/
private CustomActionListener getInfoMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 弹出详细信息框
JOptionPane.showMessageDialog(MainController.this.view,
MainController.this.systemCore.getFileInfo(this.fcb),
"Info", JOptionPane.PLAIN_MESSAGE);
}
};
/**
* "后退"按钮按键监听
*/
private ActionListener backButtonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 点击后退按钮
if (MainController.this.systemCore.leaveDir()) {
// 确认回到上一级目录
// 重绘view
MainController.this.refreshView();
} else {
// 根目录
JOptionPane.showMessageDialog(MainController.this.view,
"Already in root directory", "Warning",
JOptionPane.WARNING_MESSAGE);
}
}
};
/**
* "前往"按钮按键监听
*/
private ActionListener goButtonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取地址栏地址
String path = MainController.this.view.addressTextField.getText();
if (path.charAt(0) != '/') {
// 路径非法
JOptionPane.showMessageDialog(MainController.this.view,
"Directory doesn't exist!", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
// 获取当前地址
String currentPath = MainController.this.systemCore
.getCurrentPath();
// 拆分
String[] pathArray = path.split("/");
String[] currentPathArray = currentPath.split("/");
if (pathArray.length == 0) {
pathArray = new String[1];
pathArray[0] = "";
}
if (currentPathArray.length == 0) {
currentPathArray = new String[1];
currentPathArray[0] = "";
}
// 对比
int length = Math.min(pathArray.length, currentPathArray.length);
int i = 0;
for (i = 0; i < length; i++) {
if (!pathArray[i].equals(currentPathArray[i])) {
break;
}
}
if (pathArray.length == currentPathArray.length && i == length) {
// 两拆分后的数组相同,即路径没变化,无需继续下面的步骤
return;
}
// 计算
// 向后退的步数
int stepOut = currentPathArray.length - i;
// 向前进的步数
int stepIn = pathArray.length - i;
// 临时保存当前目录FCB和目录文件
FCB fcb = MainController.this.systemCore.currentDirFCB;
FCB[] dir = MainController.this.systemCore.currentDir;
// 开始后退再前进
boolean success = true;
// 后退
for (int j = 0; j < stepOut; j++) {
MainController.this.systemCore.leaveDir();
}
// 前进
for (int j = 0; j < stepIn; j++) {
if (!MainController.this.systemCore.enterDir(pathArray[i++])) {
success = false;
break;
}
}
if (success) {
// 成功跳转
// 刷新界面
MainController.this.refreshView();
} else {
// 目录不存在
JOptionPane.showMessageDialog(MainController.this.view,
"Directory doesn't exist!", "Warning",
JOptionPane.WARNING_MESSAGE);
// 恢复
MainController.this.systemCore.currentDirFCB = fcb;
MainController.this.systemCore.currentDir = dir;
MainController.this.systemCore.countFiles();
}
}
};
/**
* 主窗口的监听,主要是关闭事件
*/
private WindowListener mainWindowListener = new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("窗口已关闭");
// 系统核心退出
MainController.this.systemCore.exit();
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
};
/**
* 编辑窗口的监听
*/
private WindowListener editWindowListener = new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
EditView editView = (EditView) e.getComponent();
if (!editView.edited) {
// 文本没有变化
return;
}
// 获取用户的选择
int result = JOptionPane.showConfirmDialog(editView,
"Would you like to SAVE before leaving?", "Exit",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
// 退出并保存
editView.saveOnExit = true;
editView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} else if (result == 1) {
// 退出不保存
editView.saveOnExit = false;
editView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} else {
// 取消
editView.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("编辑窗口关闭");
EditView editView = (EditView) e.getComponent();
if (editView.edited && editView.saveOnExit) {
// 保存文件
MainController.this.systemCore.updateFile(
editView.getDataFCB(), editView.getContent());
}
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
};
/**
* 根据当前FCB对应的目录文件刷新View
*/
private void refreshView() {
this.view.reloadContent(this.systemCore.currentDir);
// 重新添加监听
this.addListenerForEachDocumentIcon();
// 更新当前路径
this.view.addressTextField.setText(MainController.this.systemCore
.getCurrentPath());
}
/**
* 为每个图标添加监听
*/
private void addListenerForEachDocumentIcon() {
this.view
.addDocumentIconPanelMouseListener(this.documentIconPanelMouseListener);
}
}
| Course-Project/OS_File_Management | src/controller/MainController.java | 5,465 | // 获取用户的选择 | line_comment | zh-cn | package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import model.sys.Config.FILE_TYPE;
import model.sys.FCB;
import view.DocumentIconPanel;
import view.EditView;
import view.MainView;
import com.google.gson.Gson;
/**
*
* @author Tom Hu
*
*/
public class MainController {
private MainView view;
private SystemCore systemCore;
/**
* 构造函数
*/
public MainController() {
super();
// Initialize systemCore
this.systemCore = new SystemCore();
// UI Methods
this.configureMainView();
}
// UI Methods
/**
* 初始化主界面
*/
private void configureMainView() {
// 根据当前目录文件初始化view
this.view = new MainView(this.systemCore.currentDir);
// 添加右键监听
this.view.addRightClickListener(this.rightClickListener);
// 添加后退按钮监听
this.view.addBackButtonActionListener(this.backButtonActionListener);
// 添加前往按钮监听
this.view.addGoButtonActionListener(this.goButtonActionListener);
// 添加关闭事件监听
this.view.addWindowListener(this.mainWindowListener);
this.configureContentPanel();
// 显示当前路径
this.view.addressTextField.setText(this.systemCore.getCurrentPath());
}
/**
* 初始化内容面板
*/
private void configureContentPanel() {
// 为每个图标添加监听
this.addListenerForEachDocumentIcon();
}
/**
* 显示主界面
*/
public void showMainView() {
this.view.showView();
}
/**
* 显示编辑界面
*
* @param fcb
* 需要编辑的文件的FCB
*/
private void showEditView(FCB fcb) {
// 弹出Edit View,根据FCB加载
EditView editView = new EditView(fcb,
MainController.this.systemCore.readFile(fcb));
// 为Edit Window添加监听
editView.addWindowListener(MainController.this.editWindowListener);
// 显示Edit View
editView.setVisible(true);
}
// Listener
/**
* 主界面内容面板右键点击监听
*/
private MouseListener rightClickListener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// Deselect documents
if (e.getButton() == MouseEvent.BUTTON1) {
MainController.this.view.deselectDocuments();
}
// Popup menu
if (e.getButton() == MouseEvent.BUTTON3) {
boolean isRoot = (MainController.this.systemCore.currentDirFCB.fatherBlockId == -1);
JPopupMenu menu = new JPopupMenu();
JMenuItem newFileMenu = new JMenuItem("New File", KeyEvent.VK_N);
newFileMenu.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_N, ActionEvent.CTRL_MASK));
newFileMenu
.addActionListener(MainController.this.newFileActionListener);
menu.add(newFileMenu);
JMenuItem newFolderMenu = new JMenuItem("New Folder",
KeyEvent.VK_F);
newFolderMenu.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F, ActionEvent.CTRL_MASK));
newFolderMenu
.addActionListener(MainController.this.newFolderActionListener);
menu.add(newFolderMenu);
if (isRoot) {
menu.addSeparator();
JMenuItem formatMenu = new JMenuItem("Format");
formatMenu
.addActionListener(MainController.this.formatMenuActionListener);
menu.add(formatMenu);
}
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
/**
* 图标点击监听,包括单击选中,双击打开,右键弹出菜单
*/
private MouseListener documentIconPanelMouseListener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// Select current document
MainController.this.view.deselectDocuments();
DocumentIconPanel d = (DocumentIconPanel) e.getComponent();
d.setSelected(true);
// 获取文件FCB
FCB fcb = MainController.this.systemCore.getFCB(d.getFilename(),
d.getType());
// Double click
if (e.getClickCount() == 2) {
// 判断双击的类型
if (d.getType() == FILE_TYPE.DIRECTORY) {
// 双击文件夹
// model进入下一级文件夹
MainController.this.systemCore.enterDir(d.getFilename());
// 重绘view
MainController.this.refreshView();
} else {
// 双击文件
// 显示编辑窗口
MainController.this.showEditView(fcb);
}
System.out.println("Double Click");
}
// Right click
if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu documentMenu = new JPopupMenu();
JMenuItem openMenuItem = new JMenuItem("Open", KeyEvent.VK_O);
MainController.this.openMenuActionListener.fcb = fcb;
openMenuItem
.addActionListener(MainController.this.openMenuActionListener);
documentMenu.add(openMenuItem);
if (d.getType() == FILE_TYPE.FILE) {
JMenuItem editMenuItem = new JMenuItem("Edit",
KeyEvent.VK_E);
MainController.this.editMenuActionListener.fcb = fcb;
editMenuItem
.addActionListener(MainController.this.editMenuActionListener);
documentMenu.add(editMenuItem);
}
JMenuItem renameMenuItem = new JMenuItem("Rename",
KeyEvent.VK_R);
MainController.this.renameMenuActionListener.fcb = fcb;
renameMenuItem
.addActionListener(MainController.this.renameMenuActionListener);
documentMenu.add(renameMenuItem);
documentMenu.addSeparator();
JMenuItem getInfoMenuItem = new JMenuItem("Get info",
KeyEvent.VK_I);
MainController.this.getInfoMenuActionListener.fcb = fcb;
getInfoMenuItem
.addActionListener(MainController.this.getInfoMenuActionListener);
documentMenu.add(getInfoMenuItem);
documentMenu.addSeparator();
JMenuItem deleteMenuItem = new JMenuItem("Delete",
KeyEvent.VK_D);
MainController.this.deleteMenuActionListener.fcb = fcb;
deleteMenuItem
.addActionListener(MainController.this.deleteMenuActionListener);
documentMenu.add(deleteMenuItem);
documentMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
/**
* 监听新建文件的按钮
*/
private ActionListener newFileActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 新建文件
// 获取文件名
String filename = (String) JOptionPane.showInputDialog(
MainController.this.view,
"Please enter your new file's name:", "New file",
JOptionPane.INFORMATION_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
// 不允许文件名为空
while (filename.equals("")) {
filename = (String) JOptionPane
.showInputDialog(
MainController.this.view,
"Filename cannot be empty! \nPlease enter your new file's name:",
"New file", JOptionPane.WARNING_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
}
if (MainController.this.systemCore.createFile(filename)) {
// 添加到model成功,即创建文件成功
// 添加到view
DocumentIconPanel d = new DocumentIconPanel(FILE_TYPE.FILE,
filename);
d.addMouseListener(MainController.this.documentIconPanelMouseListener);
MainController.this.view.addDocument(d);
} else {
// 创建文件失败
// 可能是有重名,也可能空间不够
// 弹出错误信息框
JOptionPane
.showMessageDialog(
MainController.this.view,
"Two possible reasons:\n1. The name \""
+ filename
+ "\" is already taken. Please choose a different name.\n2. Not enough disk space available. Delete some files.",
"New file error", JOptionPane.ERROR_MESSAGE);
}
}
};
/**
* 监听新建文件夹的按钮
*/
private ActionListener newFolderActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 新建文件夹
// 获取文件名
String filename = (String) JOptionPane.showInputDialog(
MainController.this.view,
"Please enter your new folder's name:", "New folder",
JOptionPane.INFORMATION_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
// 不允许文件名为空
while (filename.equals("")) {
filename = (String) JOptionPane
.showInputDialog(
MainController.this.view,
"Folder's name cannot be empty! \nPlease enter your new folder's name:",
"New folder", JOptionPane.WARNING_MESSAGE);
if (filename == null) {
// 用户取消
return;
}
}
if (MainController.this.systemCore.createDir(filename)) {
// 添加到model成功,即创建文件夹成功
// 添加到view
DocumentIconPanel d = new DocumentIconPanel(
FILE_TYPE.DIRECTORY, filename);
d.addMouseListener(MainController.this.documentIconPanelMouseListener);
MainController.this.view.addDocument(d);
} else {
// 创建文件夹失败
// 可能是有重名,也可能空间不够
// 弹出错误信息框
JOptionPane
.showMessageDialog(
MainController.this.view,
"Two possible reasons:\n1. The name \""
+ filename
+ "\" is already taken. Please choose a different name.\n2. Not enough disk space available. Delete some files.",
"New folder error", JOptionPane.ERROR_MESSAGE);
}
}
};
private class CustomActionListener implements ActionListener {
public FCB fcb = null;
@Override
public void actionPerformed(ActionEvent e) {
}
}
/**
* "编辑"按钮按键监听
*/
private CustomActionListener editMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MainController.this.showEditView(this.fcb);
}
};
/**
* "打开"按钮按键监听
*/
private CustomActionListener openMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (this.fcb.type == FILE_TYPE.DIRECTORY) {
// model进入下一级文件夹
MainController.this.systemCore.enterDir(this.fcb.filename);
// 重绘view
MainController.this.refreshView();
} else {
// 显示编辑窗口
MainController.this.showEditView(fcb);
}
}
};
/**
* "删除"按钮按键监听
*/
private CustomActionListener deleteMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取用户的选择
int result = JOptionPane.showConfirmDialog(
MainController.this.view,
"Are you sure you want to permanently delete this item?",
"Delete", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
// 确定删除
if (this.fcb.type == FILE_TYPE.DIRECTORY) {
// model删除文件夹
MainController.this.systemCore.deleteDir(this.fcb.filename);
} else {
// model删除文件
MainController.this.systemCore
.deleteFile(this.fcb.filename);
}
// 重绘view
MainController.this.refreshView();
}
}
};
/**
* "重命名"按钮按键监听
*/
private CustomActionListener renameMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取文件名
String filename = (String) JOptionPane.showInputDialog(
MainController.this.view, "Folder name:", "Rename",
JOptionPane.INFORMATION_MESSAGE, null, null,
this.fcb.filename);
if (filename == null) {
// 用户取消
return;
}
// 不允许文件名为空
while (filename.equals("")) {
filename = (String) JOptionPane.showInputDialog(
MainController.this.view, "Folder name:", "Rename",
JOptionPane.INFORMATION_MESSAGE, null, null,
this.fcb.filename);
}
this.fcb.filename = filename;
Gson gson = new Gson();
// 更新文件FCB
MainController.this.systemCore.updateFCB(this.fcb);
// 更新当前目录的目录文件
MainController.this.systemCore.updateFile(
MainController.this.systemCore.currentDirFCB,
gson.toJson(MainController.this.systemCore.currentDir));
// 刷新界面
MainController.this.refreshView();
}
};
/**
* "格式化"按钮按键监听
*/
private ActionListener formatMenuActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取 <SUF>
int result = JOptionPane
.showConfirmDialog(
MainController.this.view,
"All the data will be erased from the disk.\nAre you sure to FORMAT disk?",
"FORMAT!!", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
// 确定格式化
MainController.this.systemCore.format();
}
// 刷新界面
MainController.this.refreshView();
}
};
/**
* "属性"按钮按键监听
*/
private CustomActionListener getInfoMenuActionListener = new CustomActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 弹出详细信息框
JOptionPane.showMessageDialog(MainController.this.view,
MainController.this.systemCore.getFileInfo(this.fcb),
"Info", JOptionPane.PLAIN_MESSAGE);
}
};
/**
* "后退"按钮按键监听
*/
private ActionListener backButtonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 点击后退按钮
if (MainController.this.systemCore.leaveDir()) {
// 确认回到上一级目录
// 重绘view
MainController.this.refreshView();
} else {
// 根目录
JOptionPane.showMessageDialog(MainController.this.view,
"Already in root directory", "Warning",
JOptionPane.WARNING_MESSAGE);
}
}
};
/**
* "前往"按钮按键监听
*/
private ActionListener goButtonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取地址栏地址
String path = MainController.this.view.addressTextField.getText();
if (path.charAt(0) != '/') {
// 路径非法
JOptionPane.showMessageDialog(MainController.this.view,
"Directory doesn't exist!", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
// 获取当前地址
String currentPath = MainController.this.systemCore
.getCurrentPath();
// 拆分
String[] pathArray = path.split("/");
String[] currentPathArray = currentPath.split("/");
if (pathArray.length == 0) {
pathArray = new String[1];
pathArray[0] = "";
}
if (currentPathArray.length == 0) {
currentPathArray = new String[1];
currentPathArray[0] = "";
}
// 对比
int length = Math.min(pathArray.length, currentPathArray.length);
int i = 0;
for (i = 0; i < length; i++) {
if (!pathArray[i].equals(currentPathArray[i])) {
break;
}
}
if (pathArray.length == currentPathArray.length && i == length) {
// 两拆分后的数组相同,即路径没变化,无需继续下面的步骤
return;
}
// 计算
// 向后退的步数
int stepOut = currentPathArray.length - i;
// 向前进的步数
int stepIn = pathArray.length - i;
// 临时保存当前目录FCB和目录文件
FCB fcb = MainController.this.systemCore.currentDirFCB;
FCB[] dir = MainController.this.systemCore.currentDir;
// 开始后退再前进
boolean success = true;
// 后退
for (int j = 0; j < stepOut; j++) {
MainController.this.systemCore.leaveDir();
}
// 前进
for (int j = 0; j < stepIn; j++) {
if (!MainController.this.systemCore.enterDir(pathArray[i++])) {
success = false;
break;
}
}
if (success) {
// 成功跳转
// 刷新界面
MainController.this.refreshView();
} else {
// 目录不存在
JOptionPane.showMessageDialog(MainController.this.view,
"Directory doesn't exist!", "Warning",
JOptionPane.WARNING_MESSAGE);
// 恢复
MainController.this.systemCore.currentDirFCB = fcb;
MainController.this.systemCore.currentDir = dir;
MainController.this.systemCore.countFiles();
}
}
};
/**
* 主窗口的监听,主要是关闭事件
*/
private WindowListener mainWindowListener = new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("窗口已关闭");
// 系统核心退出
MainController.this.systemCore.exit();
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
};
/**
* 编辑窗口的监听
*/
private WindowListener editWindowListener = new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
EditView editView = (EditView) e.getComponent();
if (!editView.edited) {
// 文本没有变化
return;
}
// 获取用户的选择
int result = JOptionPane.showConfirmDialog(editView,
"Would you like to SAVE before leaving?", "Exit",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
// 退出并保存
editView.saveOnExit = true;
editView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} else if (result == 1) {
// 退出不保存
editView.saveOnExit = false;
editView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} else {
// 取消
editView.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("编辑窗口关闭");
EditView editView = (EditView) e.getComponent();
if (editView.edited && editView.saveOnExit) {
// 保存文件
MainController.this.systemCore.updateFile(
editView.getDataFCB(), editView.getContent());
}
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
};
/**
* 根据当前FCB对应的目录文件刷新View
*/
private void refreshView() {
this.view.reloadContent(this.systemCore.currentDir);
// 重新添加监听
this.addListenerForEachDocumentIcon();
// 更新当前路径
this.view.addressTextField.setText(MainController.this.systemCore
.getCurrentPath());
}
/**
* 为每个图标添加监听
*/
private void addListenerForEachDocumentIcon() {
this.view
.addDocumentIconPanelMouseListener(this.documentIconPanelMouseListener);
}
}
| 1 | 10 | 1 |
54915_4 | import java.util.Arrays;
public class _76_match {
public boolean match (String str, String pattern) {
char[] strC = str.toCharArray();
char[] patternC = pattern.toCharArray();
boolean[] dp = new boolean[patternC.length + 1];
dp[0] = true;
for (int i = 1; i < patternC.length && patternC[i] == '*'; i += 2) {
dp[i + 1] = true;
}
boolean pre = true;
for (int i = 1; i <= strC.length; i++) {
dp[0] = false;
for (int j = 1; j <= patternC.length; j++) {
boolean temp = dp[j];
if (patternC[j - 1] == '.') {
dp[j] = pre;
} else if (patternC[j - 1] == '*') {
if (patternC[j - 2] == '.' || patternC[j - 2] == strC[i - 1])
dp[j] = dp[j] || dp[j - 2];
else {
dp[j] = dp[j - 2];
}
} else {
if (patternC[j - 1] == strC[i - 1])
dp[j] = pre;
else
dp[j] = false;
}
pre = temp;
}
}
return dp[patternC.length];
}
public boolean match2 (String str, String pattern) {
int n1 = str.length();
int n2 = pattern.length();
//dp[i][j]表示str前i个字符和pattern前j个字符是否匹配
boolean[][] dp = new boolean[n1 + 1][n2 + 1];
//遍历str每个长度
for(int i = 0; i <= n1; i++){
//遍历pattern每个长度
for(int j = 0; j <= n2; j++){
//空正则的情况
if(j == 0){
dp[i][j] = (i == 0 ? true : false);
//非空的情况下 星号、点号、字符
}else{
if(pattern.charAt(j - 1) != '*'){
//当前字符不为*,用.去匹配或者字符直接相同
if(i > 0 && (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')){
dp[i][j] = dp[i - 1][j - 1];
}
}else{
//碰到*
if(j >= 2){
dp[i][j] |= dp[i][j - 2];
}
//若是前一位为.或者前一位可以与这个数字匹配
if(i >= 1 && j >= 2 && (str.charAt(i - 1) == pattern.charAt(j - 2) || pattern.charAt(j - 2) == '.')){
dp[i][j] |= dp[i - 1][j];
}
}
}
}
}
return dp[n1][n2];
}
public static void main(String[] args) {
System.out.println(new _76_match().match("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
System.out.println(new _76_match().match2("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
}
}
| Cqupt-Psyduck/my_algorithm | hot_100/_76_match.java | 847 | //非空的情况下 星号、点号、字符 | line_comment | zh-cn | import java.util.Arrays;
public class _76_match {
public boolean match (String str, String pattern) {
char[] strC = str.toCharArray();
char[] patternC = pattern.toCharArray();
boolean[] dp = new boolean[patternC.length + 1];
dp[0] = true;
for (int i = 1; i < patternC.length && patternC[i] == '*'; i += 2) {
dp[i + 1] = true;
}
boolean pre = true;
for (int i = 1; i <= strC.length; i++) {
dp[0] = false;
for (int j = 1; j <= patternC.length; j++) {
boolean temp = dp[j];
if (patternC[j - 1] == '.') {
dp[j] = pre;
} else if (patternC[j - 1] == '*') {
if (patternC[j - 2] == '.' || patternC[j - 2] == strC[i - 1])
dp[j] = dp[j] || dp[j - 2];
else {
dp[j] = dp[j - 2];
}
} else {
if (patternC[j - 1] == strC[i - 1])
dp[j] = pre;
else
dp[j] = false;
}
pre = temp;
}
}
return dp[patternC.length];
}
public boolean match2 (String str, String pattern) {
int n1 = str.length();
int n2 = pattern.length();
//dp[i][j]表示str前i个字符和pattern前j个字符是否匹配
boolean[][] dp = new boolean[n1 + 1][n2 + 1];
//遍历str每个长度
for(int i = 0; i <= n1; i++){
//遍历pattern每个长度
for(int j = 0; j <= n2; j++){
//空正则的情况
if(j == 0){
dp[i][j] = (i == 0 ? true : false);
//非空 <SUF>
}else{
if(pattern.charAt(j - 1) != '*'){
//当前字符不为*,用.去匹配或者字符直接相同
if(i > 0 && (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')){
dp[i][j] = dp[i - 1][j - 1];
}
}else{
//碰到*
if(j >= 2){
dp[i][j] |= dp[i][j - 2];
}
//若是前一位为.或者前一位可以与这个数字匹配
if(i >= 1 && j >= 2 && (str.charAt(i - 1) == pattern.charAt(j - 2) || pattern.charAt(j - 2) == '.')){
dp[i][j] |= dp[i - 1][j];
}
}
}
}
}
return dp[n1][n2];
}
public static void main(String[] args) {
System.out.println(new _76_match().match("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
System.out.println(new _76_match().match2("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
}
}
| 1 | 17 | 1 |
55481_9 | /*
*
* Copyright 2017 Crab2Died
* All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Browse for more information :
* 1) https://gitee.com/Crab2Died/Excel4J
* 2) https://github.com/Crab2died/Excel4J
*
*/
package com.github.crab2died.utils;
import com.github.crab2died.annotation.ExcelField;
import com.github.crab2died.converter.DefaultConvertible;
import com.github.crab2died.converter.WriteConvertible;
import com.github.crab2died.exceptions.Excel4JException;
import com.github.crab2died.handler.ExcelHeader;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
/**
* Excel4J工具类
* author : Crab2Died
* date : 2017/5/24 9:43
*/
public class Utils {
/**
* getter或setter枚举
*/
public enum FieldAccessType {
GETTER, SETTER
}
/**
* <p>根据JAVA对象注解获取Excel表头信息</p>
*
* @param clz 类型
* @return 表头信息
*/
public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException {
List<ExcelHeader> headers = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
// 是否使用ExcelField注解
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField er = field.getAnnotation(ExcelField.class);
try {
headers.add(new ExcelHeader(
er.title(),
er.order(),
er.writeConverter().newInstance(),
er.readConverter().newInstance(),
field.getName(),
field.getType()
));
} catch (InstantiationException | IllegalAccessException e) {
throw new Excel4JException(e);
}
}
}
Collections.sort(headers);
return headers;
}
/**
* 获取excel列表头
*
* @param titleRow excel行
* @param clz 类型
* @return ExcelHeader集合
* @throws Excel4JException 异常
*/
public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz)
throws Excel4JException {
List<ExcelHeader> headers = getHeaderList(clz);
Map<Integer, ExcelHeader> maps = new HashMap<>();
for (Cell c : titleRow) {
String title = c.getStringCellValue();
for (ExcelHeader eh : headers) {
if (eh.getTitle().equals(title.trim())) {
maps.put(c.getColumnIndex(), eh);
break;
}
}
}
return maps;
}
/**
* 获取单元格内容
*
* @param c 单元格
* @return 单元格内容
*/
public static String getCellValue(Cell c) {
String o;
switch (c.getCellType()) {
case BLANK:
o = "";
break;
case BOOLEAN:
o = String.valueOf(c.getBooleanCellValue());
break;
case FORMULA:
o = calculationFormula(c);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(c)) {
o = DateUtils.date2Str(c.getDateCellValue());
} else {
o = String.valueOf(c.getNumericCellValue());
o = matchDoneBigDecimal(o);
o = RegularUtils.converNumByReg(o);
}
break;
case STRING:
o = c.getStringCellValue();
break;
default:
o = null;
break;
}
return o;
}
/**
* 字符串转对象
*
* @param strField 字符串
* @param clazz 待转类型
* @return 转换后数据
*/
public static Object str2TargetClass(String strField, Class<?> clazz) {
if (null == strField || "".equals(strField))
return null;
if ((Long.class == clazz) || (long.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Long.parseLong(strField);
}
if ((Integer.class == clazz) || (int.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Integer.parseInt(strField);
}
if ((Float.class == clazz) || (float.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Float.parseFloat(strField);
}
if ((Double.class == clazz) || (double.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Double.parseDouble(strField);
}
if ((Character.class == clazz) || (char.class == clazz)) {
return strField.toCharArray()[0];
}
if ((Boolean.class == clazz) || (boolean.class == clazz)) {
return Boolean.parseBoolean(strField);
}
if (Date.class == clazz) {
return DateUtils.str2DateUnmatch2Null(strField);
}
return strField;
}
/**
* 科学计数法数据转换
*
* @param bigDecimal 科学计数法
* @return 数据字符串
*/
private static String matchDoneBigDecimal(String bigDecimal) {
// 对科学计数法进行处理
boolean flg = Pattern.matches("^-?\\d+(\\.\\d+)?(E-?\\d+)?$", bigDecimal);
if (flg) {
BigDecimal bd = new BigDecimal(bigDecimal);
bigDecimal = bd.toPlainString();
}
return bigDecimal;
}
/**
* <p>根据java对象属性{@link Field}获取该属性的getter或setter方法名,
* 另对{@link boolean}及{@link Boolean}做了行管处理</p>
*
* @param clazz 操作对象
* @param fieldName 对象属性
* @param methodType 方法类型,getter或setter枚举
* @return getter或setter方法
* @throws IntrospectionException 异常
* @author Crab2Died
*/
public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType)
throws IntrospectionException {
if (null == fieldName || "".equals(fieldName))
return null;
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop : props) {
if (fieldName.equals(prop.getName())) {
if (FieldAccessType.SETTER == methodType) {
return prop.getWriteMethod();
}
if (FieldAccessType.GETTER == methodType) {
return prop.getReadMethod();
}
}
}
throw new IntrospectionException("Can not get the getter or setter method");
}
/**
* <p>根据对象的属性名{@code fieldName}获取某个java的属性{@link java.lang.reflect.Field}</p>
*
* @param clazz java对象的class属性
* @param fieldName 属性名
* @return {@link java.lang.reflect.Field} java对象的属性
* @author Crab2Died
*/
private static Field matchClassField(Class clazz, String fieldName) {
List<Field> fields = new ArrayList<>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
return field;
}
}
throw new IllegalArgumentException("[" + clazz.getName() + "] can`t found field with [" + fieldName + "]");
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param fieldName 字段名
* @param writeConvertible 写入转换器
* @return 对象指定字段内容
* @throws Excel4JException 异常
*/
public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible)
throws Excel4JException {
if (bean == null || fieldName == null)
throw new IllegalArgumentException("Operating bean or filed class must not be null");
Method method;
Object object;
try {
method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER);
object = method.invoke(bean);
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) {
// 写入转换器
object = writeConvertible.execWrite(object);
}
return object == null ? "" : object.toString();
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param name 字段名
* @param value 字段类型
*/
public static void copyProperty(Object bean, String name, Object value)
throws Excel4JException {
if (null == name || null == value)
return;
Field field = matchClassField(bean.getClass(), name);
if (null == field)
return;
Method method;
try {
method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER);
if (value.getClass() == field.getType()) {
method.invoke(bean, value);
} else {
method.invoke(bean, str2TargetClass(value.toString(), field.getType()));
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
}
/**
* 计算公式结果
*
* @param cell 单元格类型为公式的单元格
* @return 返回单元格计算后的值 格式化成String
* @author QingMings
* Email:[email protected]
* date 2018-01-13
*/
public static String calculationFormula(Cell cell) {
CellValue cellValue = cell.getSheet().getWorkbook().getCreationHelper()
.createFormulaEvaluator().evaluate(cell);
return cellValue.formatAsString();
}
}
| Crab2died/Excel4J | src/main/java/com/github/crab2died/utils/Utils.java | 2,754 | // 对科学计数法进行处理 | line_comment | zh-cn | /*
*
* Copyright 2017 Crab2Died
* All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Browse for more information :
* 1) https://gitee.com/Crab2Died/Excel4J
* 2) https://github.com/Crab2died/Excel4J
*
*/
package com.github.crab2died.utils;
import com.github.crab2died.annotation.ExcelField;
import com.github.crab2died.converter.DefaultConvertible;
import com.github.crab2died.converter.WriteConvertible;
import com.github.crab2died.exceptions.Excel4JException;
import com.github.crab2died.handler.ExcelHeader;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
/**
* Excel4J工具类
* author : Crab2Died
* date : 2017/5/24 9:43
*/
public class Utils {
/**
* getter或setter枚举
*/
public enum FieldAccessType {
GETTER, SETTER
}
/**
* <p>根据JAVA对象注解获取Excel表头信息</p>
*
* @param clz 类型
* @return 表头信息
*/
public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException {
List<ExcelHeader> headers = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
// 是否使用ExcelField注解
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField er = field.getAnnotation(ExcelField.class);
try {
headers.add(new ExcelHeader(
er.title(),
er.order(),
er.writeConverter().newInstance(),
er.readConverter().newInstance(),
field.getName(),
field.getType()
));
} catch (InstantiationException | IllegalAccessException e) {
throw new Excel4JException(e);
}
}
}
Collections.sort(headers);
return headers;
}
/**
* 获取excel列表头
*
* @param titleRow excel行
* @param clz 类型
* @return ExcelHeader集合
* @throws Excel4JException 异常
*/
public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz)
throws Excel4JException {
List<ExcelHeader> headers = getHeaderList(clz);
Map<Integer, ExcelHeader> maps = new HashMap<>();
for (Cell c : titleRow) {
String title = c.getStringCellValue();
for (ExcelHeader eh : headers) {
if (eh.getTitle().equals(title.trim())) {
maps.put(c.getColumnIndex(), eh);
break;
}
}
}
return maps;
}
/**
* 获取单元格内容
*
* @param c 单元格
* @return 单元格内容
*/
public static String getCellValue(Cell c) {
String o;
switch (c.getCellType()) {
case BLANK:
o = "";
break;
case BOOLEAN:
o = String.valueOf(c.getBooleanCellValue());
break;
case FORMULA:
o = calculationFormula(c);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(c)) {
o = DateUtils.date2Str(c.getDateCellValue());
} else {
o = String.valueOf(c.getNumericCellValue());
o = matchDoneBigDecimal(o);
o = RegularUtils.converNumByReg(o);
}
break;
case STRING:
o = c.getStringCellValue();
break;
default:
o = null;
break;
}
return o;
}
/**
* 字符串转对象
*
* @param strField 字符串
* @param clazz 待转类型
* @return 转换后数据
*/
public static Object str2TargetClass(String strField, Class<?> clazz) {
if (null == strField || "".equals(strField))
return null;
if ((Long.class == clazz) || (long.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Long.parseLong(strField);
}
if ((Integer.class == clazz) || (int.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Integer.parseInt(strField);
}
if ((Float.class == clazz) || (float.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Float.parseFloat(strField);
}
if ((Double.class == clazz) || (double.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Double.parseDouble(strField);
}
if ((Character.class == clazz) || (char.class == clazz)) {
return strField.toCharArray()[0];
}
if ((Boolean.class == clazz) || (boolean.class == clazz)) {
return Boolean.parseBoolean(strField);
}
if (Date.class == clazz) {
return DateUtils.str2DateUnmatch2Null(strField);
}
return strField;
}
/**
* 科学计数法数据转换
*
* @param bigDecimal 科学计数法
* @return 数据字符串
*/
private static String matchDoneBigDecimal(String bigDecimal) {
// 对科 <SUF>
boolean flg = Pattern.matches("^-?\\d+(\\.\\d+)?(E-?\\d+)?$", bigDecimal);
if (flg) {
BigDecimal bd = new BigDecimal(bigDecimal);
bigDecimal = bd.toPlainString();
}
return bigDecimal;
}
/**
* <p>根据java对象属性{@link Field}获取该属性的getter或setter方法名,
* 另对{@link boolean}及{@link Boolean}做了行管处理</p>
*
* @param clazz 操作对象
* @param fieldName 对象属性
* @param methodType 方法类型,getter或setter枚举
* @return getter或setter方法
* @throws IntrospectionException 异常
* @author Crab2Died
*/
public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType)
throws IntrospectionException {
if (null == fieldName || "".equals(fieldName))
return null;
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop : props) {
if (fieldName.equals(prop.getName())) {
if (FieldAccessType.SETTER == methodType) {
return prop.getWriteMethod();
}
if (FieldAccessType.GETTER == methodType) {
return prop.getReadMethod();
}
}
}
throw new IntrospectionException("Can not get the getter or setter method");
}
/**
* <p>根据对象的属性名{@code fieldName}获取某个java的属性{@link java.lang.reflect.Field}</p>
*
* @param clazz java对象的class属性
* @param fieldName 属性名
* @return {@link java.lang.reflect.Field} java对象的属性
* @author Crab2Died
*/
private static Field matchClassField(Class clazz, String fieldName) {
List<Field> fields = new ArrayList<>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
return field;
}
}
throw new IllegalArgumentException("[" + clazz.getName() + "] can`t found field with [" + fieldName + "]");
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param fieldName 字段名
* @param writeConvertible 写入转换器
* @return 对象指定字段内容
* @throws Excel4JException 异常
*/
public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible)
throws Excel4JException {
if (bean == null || fieldName == null)
throw new IllegalArgumentException("Operating bean or filed class must not be null");
Method method;
Object object;
try {
method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER);
object = method.invoke(bean);
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) {
// 写入转换器
object = writeConvertible.execWrite(object);
}
return object == null ? "" : object.toString();
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param name 字段名
* @param value 字段类型
*/
public static void copyProperty(Object bean, String name, Object value)
throws Excel4JException {
if (null == name || null == value)
return;
Field field = matchClassField(bean.getClass(), name);
if (null == field)
return;
Method method;
try {
method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER);
if (value.getClass() == field.getType()) {
method.invoke(bean, value);
} else {
method.invoke(bean, str2TargetClass(value.toString(), field.getType()));
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
}
/**
* 计算公式结果
*
* @param cell 单元格类型为公式的单元格
* @return 返回单元格计算后的值 格式化成String
* @author QingMings
* Email:[email protected]
* date 2018-01-13
*/
public static String calculationFormula(Cell cell) {
CellValue cellValue = cell.getSheet().getWorkbook().getCreationHelper()
.createFormulaEvaluator().evaluate(cell);
return cellValue.formatAsString();
}
}
| 1 | 13 | 1 |
51139_4 | import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
/**
* 你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8',
* '9' 。每个拨轮可以自由旋转:例如把 '9' 变为 '0','0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。
*
* 锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。
*
* 列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。
*
* 字符串 target 代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1。
*
*
*
* 示例 1:
*
* 输入:deadends = ["0201","0101","0102","1212","2002"], target = "0202" 输出:6 解释:
* 可能的移动序列为 "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202"。
* 注意 "0000" -> "0001" -> "0002" -> "0102" -> "0202" 这样的序列是不能解锁的, 因为当拨动到 "0102"
* 时这个锁就会被锁定。
*
* 示例 2:
*
* 输入: deadends = ["8888"], target = "0009" 输出:1
*
* 解释: 把最后一位反向旋转一次即可 "0000" ->
* "0009"。
*
* 示例 3:
*
* 输入: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"],
* target = "8888"
*
* 输出:-1
*
* 解释: 无法旋转到目标数字且不被锁定。
*
* 示例 4:
*
* 输入: deadends = ["0000"], target = "8888"
*
* 输出:-1
*
* 提示:
*
* 死亡列表 deadends 的长度范围为 [1, 500]。 目标数字 target 不会在 deadends 之中。 每个 deadends 和
* target 中的字符串的数字会在 10,000 个可能的情况 '0000' 到 '9999' 中产生。 通过次数12,331提交次数25,068
* 在真实的面试中遇到过这道题?
*
* 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/open-the-lock
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
/**
*
* 作者:LeetCode
* 链接:https://leetcode-cn.com/problems/open-the-lock/solution/da-kai-zhuan-pan-suo-by-leetcode/
* 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*
*/
/*
* 这里的最短路径指的是由起始状态"0000"转换为目标状态所需要的最少变换次数,可以用bfs来解决这一类最短路径问题。
* 每一位的数字都会有+1或者-1的状态,一共4位数,共有8种情况
**/
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> dead = new HashSet<>();
dead.addAll(Arrays.asList(deadends));
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
queue.offer(null);
Set<String> seen = new HashSet<>(); // 已经看过的数字 ,可以尝试使用map
seen.add("0000");
int depth = 0;
while (!queue.isEmpty()) {
String node = queue.poll();
/**
* 这个null 用来判断是否这一层遍历完了,没次取到null就说明当前层遍历完了,深度+1并且开始遍历下一层
* (在遍历下一层之前先判断是否有下一层,如果有就在队列尾巴插入null来隔断遍历下一层插入的数据)
*/
if (node == null) {
depth++;
if (queue.peek() != null)
queue.offer(null);
} else if (node.equals(target)) {
return depth;
} else if (!dead.contains(node)) {
for (int i = 0; i < 4; ++i) {
for (int d = -1; d <= 1; d += 2) {
int y = ((node.charAt(i) - '0') + d + 10) % 10; // 第 i 个数发生变化以后的数值
String nei = node.substring(0, i) + ("" + y) + node.substring(i + 1); // 拼接字符串
if (!seen.contains(nei)) {
seen.add(nei);
queue.offer(nei);
}
}
}
}
}
return -1;
}
} | CrabMen/DataStructureAndAlgorithms-365Days | Leetcode/Stack&Queue/_752. 打开转盘锁.java | 1,454 | /**
* 这个null 用来判断是否这一层遍历完了,没次取到null就说明当前层遍历完了,深度+1并且开始遍历下一层
* (在遍历下一层之前先判断是否有下一层,如果有就在队列尾巴插入null来隔断遍历下一层插入的数据)
*/ | block_comment | zh-cn | import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
/**
* 你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8',
* '9' 。每个拨轮可以自由旋转:例如把 '9' 变为 '0','0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。
*
* 锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。
*
* 列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。
*
* 字符串 target 代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1。
*
*
*
* 示例 1:
*
* 输入:deadends = ["0201","0101","0102","1212","2002"], target = "0202" 输出:6 解释:
* 可能的移动序列为 "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202"。
* 注意 "0000" -> "0001" -> "0002" -> "0102" -> "0202" 这样的序列是不能解锁的, 因为当拨动到 "0102"
* 时这个锁就会被锁定。
*
* 示例 2:
*
* 输入: deadends = ["8888"], target = "0009" 输出:1
*
* 解释: 把最后一位反向旋转一次即可 "0000" ->
* "0009"。
*
* 示例 3:
*
* 输入: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"],
* target = "8888"
*
* 输出:-1
*
* 解释: 无法旋转到目标数字且不被锁定。
*
* 示例 4:
*
* 输入: deadends = ["0000"], target = "8888"
*
* 输出:-1
*
* 提示:
*
* 死亡列表 deadends 的长度范围为 [1, 500]。 目标数字 target 不会在 deadends 之中。 每个 deadends 和
* target 中的字符串的数字会在 10,000 个可能的情况 '0000' 到 '9999' 中产生。 通过次数12,331提交次数25,068
* 在真实的面试中遇到过这道题?
*
* 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/open-the-lock
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
/**
*
* 作者:LeetCode
* 链接:https://leetcode-cn.com/problems/open-the-lock/solution/da-kai-zhuan-pan-suo-by-leetcode/
* 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*
*/
/*
* 这里的最短路径指的是由起始状态"0000"转换为目标状态所需要的最少变换次数,可以用bfs来解决这一类最短路径问题。
* 每一位的数字都会有+1或者-1的状态,一共4位数,共有8种情况
**/
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> dead = new HashSet<>();
dead.addAll(Arrays.asList(deadends));
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
queue.offer(null);
Set<String> seen = new HashSet<>(); // 已经看过的数字 ,可以尝试使用map
seen.add("0000");
int depth = 0;
while (!queue.isEmpty()) {
String node = queue.poll();
/**
* 这个n <SUF>*/
if (node == null) {
depth++;
if (queue.peek() != null)
queue.offer(null);
} else if (node.equals(target)) {
return depth;
} else if (!dead.contains(node)) {
for (int i = 0; i < 4; ++i) {
for (int d = -1; d <= 1; d += 2) {
int y = ((node.charAt(i) - '0') + d + 10) % 10; // 第 i 个数发生变化以后的数值
String nei = node.substring(0, i) + ("" + y) + node.substring(i + 1); // 拼接字符串
if (!seen.contains(nei)) {
seen.add(nei);
queue.offer(nei);
}
}
}
}
}
return -1;
}
} | 0 | 152 | 0 |
35741_11 | package com.tencent.crypt;
import java.io.ByteArrayOutputStream;
import java.util.Random;
public class Crypt {
// 指向当前的明文块
private byte[] plain;
// 这指向前面一个明文块
private byte[] prePlain;
// 输出的密文或者明文
private byte[] out;
// 当前加密的密文位置和上一次加密的密文块位置,他们相差8
private int crypt, preCrypt;
// 当前处理的加密解密块的位置
private int pos;
// 填充数
private int padding;
// 密钥
private byte[] key;
// 用于加密时,表示当前是否是第一个8字节块,因为加密算法是反馈的
// 但是最开始的8个字节没有反馈可用,所有需要标明这种情况
private boolean header = true;
// 这个表示当前解密开始的位置,之所以要这么一个变量是为了避免当解密到最后时
// 后面已经没有数据,这时候就会出错,这个变量就是用来判断这种情况免得出错
private int contextStart;
// 随机数对象
private static final Random random = new Random();
// 字节输出流
private final ByteArrayOutputStream bas;
/**
* 构造函数
*/
public Crypt() {
bas = new ByteArrayOutputStream(8);
}
/**
* 解密
*
* @param in 密文
* @param offset 密文开始的位置
* @param len 密文长度
* @param k 密钥
* @return 明文
*/
public byte[] decrypt(byte[] in, int offset, int len, byte[] k) {
// 检查密钥
if (k == null)
return null;
crypt = preCrypt = 0;
this.key = k;
int count;
byte[] m = new byte[offset + 8];
// 因为QQ消息加密之后至少是16字节,并且肯定是8的倍数,这里检查这种情况
if ((len % 8 != 0) || (len < 16)) return null;
// 得到消息的头部,关键是得到真正明文开始的位置,这个信息存在第一个字节里面,所以其用解密得到的第一个字节与7做与
prePlain = decipher(in, offset);
pos = prePlain[0] & 0x7;
// 得到真正明文的长度
count = len - pos - 10;
// 如果明文长度小于0,那肯定是出错了,比如传输错误之类的,返回
if (count < 0) return null;
// 这个是临时的preCrypt,和加密时第一个8字节块没有prePlain一样,解密时
// 第一个8字节块也没有preCrypt,所有这里建一个全0的
for (int i = offset; i < m.length; i++)
m[i] = 0;
// 通过了上面的代码,密文应该是没有问题了,我们分配输出缓冲区
out = new byte[count];
// 设置preCrypt的位置等于0,注意目前的preCrypt位置是指向m的,因为java没有指针,所以我们在后面要控制当前密文buf的引用
preCrypt = 0;
// 当前的密文位置,为什么是8不是0呢?注意前面我们已经解密了头部信息了,现在当然该8了
crypt = 8;
// 自然这个也是8
contextStart = 8;
// 加1,和加密算法是对应的
pos++;
// 开始跳过头部,如果在这个过程中满了8字节,则解密下一块
// 因为是解密下一块,所以我们有一个语句 m = in,下一块当然有preCrypt了,我们不再用m了
// 但是如果不满8,这说明了什么?说明了头8个字节的密文是包含了明文信息的,当然还是要用m把明文弄出来
// 所以,很显然,满了8的话,说明了头8个字节的密文除了一个长度信息有用之外,其他都是无用的填充
padding = 1;
while (padding <= 2) {
if (pos < 8) {
pos++;
padding++;
}
if (pos == 8) {
m = in;
decrypt8Bytes(in, offset, len);
}
}
// 这里是解密的重要阶段,这个时候头部的填充都已经跳过了,开始解密
// 注意如果上面一个while没有满8,这里第一个if里面用的就是原始的m,否则这个m就是in了
int i = 0;
while (count != 0) {
if (pos < 8) {
out[i] = (byte) (m[offset + preCrypt + pos] ^ prePlain[pos]);
i++;
count--;
pos++;
}
if (pos == 8) {
m = in;
preCrypt = crypt - 8;
decrypt8Bytes(in, offset, len);
}
}
// 最后的解密部分,上面一个while已经把明文都解出来了,就剩下尾部的填充了,应该全是0
// 所以这里有检查是否解密了之后是不是0,如果不是的话那肯定出错了,返回null
for (padding = 1; padding < 8; padding++) {
if (pos < 8) {
if ((m[offset + preCrypt + pos] ^ prePlain[pos]) != 0)
return null;
pos++;
}
if (pos == 8) {
m = in;
preCrypt = crypt;
decrypt8Bytes(in, offset, len);
}
}
return out;
}
public byte[] decrypt(byte[] in, byte[] k) {
return decrypt(in, 0, in.length, k);
}
public byte[] encrypt(byte[] in, int offset, int len, byte[] k) {
// 检查密钥
if (k == null)
return in;
plain = new byte[8];
prePlain = new byte[8];
padding = 0;
crypt = preCrypt = 0;
this.key = k;
header = true;
// 计算头部填充字节数
pos = (len + 0x0A) % 8;
if (pos != 0)
pos = 8 - pos;
// 计算输出的密文长度
out = new byte[len + pos + 10];
// 这里的操作把pos存到了plain的第一个字节里面
// 0xF8后面三位是空的,正好留给pos,因为pos是0到7的值,表示文本开始的字节位置
plain[0] = (byte) ((rand() & 0xF8) | pos);
// 这里用随机产生的数填充plain[1]到plain[pos]之间的内容
for (int i = 1; i <= pos; i++)
plain[i] = (byte) (rand() & 0xFF);
pos++;
// 这个就是prePlain,第一个8字节块当然没有prePlain,所以我们做一个全0的给第一个8字节块
for (int i = 0; i < 8; i++)
prePlain[i] = 0x0;
// 继续填充2个字节的随机数,这个过程中如果满了8字节就加密之
padding = 1;
while (padding <= 2) {
if (pos < 8) {
plain[pos++] = (byte) (rand() & 0xFF);
padding++;
}
if (pos == 8)
encrypt8Bytes();
}
// 头部填充完了,这里开始填真正的明文了,也是满了8字节就加密,一直到明文读完
int i = offset;
while (len > 0) {
if (pos < 8) {
plain[pos++] = in[i++];
len--;
}
if (pos == 8)
encrypt8Bytes();
}
// 最后填上0,以保证是8字节的倍数
padding = 1;
while (padding <= 7) {
if (pos < 8) {
plain[pos++] = 0x0;
padding++;
}
if (pos == 8)
encrypt8Bytes();
}
return out;
}
public byte[] encrypt(byte[] in, byte[] k) {
return encrypt(in, 0, in.length, k);
}
private byte[] encipher(byte[] in) {
// 迭代次数,16次
int loop = 0x10;
// 得到明文和密钥的各个部分,注意java没有无符号类型,所以为了表示一个无符号的整数
// 我们用了long,这个long的前32位是全0的,我们通过这种方式模拟无符号整数,后面用到的long也都是一样的
// 而且为了保证前32位为0,需要和0xFFFFFFFF做一下位与
long y = getUnsignedInt(in, 0, 4);
long z = getUnsignedInt(in, 4, 4);
long a = getUnsignedInt(key, 0, 4);
long b = getUnsignedInt(key, 4, 4);
long c = getUnsignedInt(key, 8, 4);
long d = getUnsignedInt(key, 12, 4);
// 这是算法的一些控制变量,为什么delta是0x9E3779B9呢?
// 这个数是TEA算法的delta,实际是就是(sqr(5) - 1) * 2^31 (根号5,减1,再乘2的31次方)
long sum = 0;
long delta = 0x9E3779B9;
delta &= 0xFFFFFFFFL;
// 开始迭代了,乱七八糟的,我也看不懂,反正和DES之类的差不多,都是这样倒来倒去
while (loop-- > 0) {
sum += delta;
sum &= 0xFFFFFFFFL;
y += ((z << 4) + a) ^ (z + sum) ^ ((z >>> 5) + b);
y &= 0xFFFFFFFFL;
z += ((y << 4) + c) ^ (y + sum) ^ ((y >>> 5) + d);
z &= 0xFFFFFFFFL;
}
// 最后,我们输出密文,因为我用的long,所以需要强制转换一下变成int
bas.reset();
writeInt((int) y);
writeInt((int) z);
return bas.toByteArray();
}
/**
* 解密从offset开始的8字节密文
*
* @param in 密文字节数组
* @param offset 密文开始位置
* @return 明文
*/
private byte[] decipher(byte[] in, int offset) {
// 迭代次数,16次
int loop = 0x10;
// 得到密文和密钥的各个部分,注意java没有无符号类型,所以为了表示一个无符号的整数
// 我们用了long,这个long的前32位是全0的,我们通过这种方式模拟无符号整数,后面用到的long也都是一样的
// 而且为了保证前32位为0,需要和0xFFFFFFFF做一下位与
long y = getUnsignedInt(in, offset, 4);
long z = getUnsignedInt(in, offset + 4, 4);
long a = getUnsignedInt(key, 0, 4);
long b = getUnsignedInt(key, 4, 4);
long c = getUnsignedInt(key, 8, 4);
long d = getUnsignedInt(key, 12, 4);
// 算法的一些控制变量,sum在这里也有数了,这个sum和迭代次数有关系
// 因为delta是这么多,所以sum如果是这么多的话,迭代的时候减减减,减16次,最后
// 得到0。反正这就是为了得到和加密时相反顺序的控制变量,这样才能解密呀~~
long sum = 0xE3779B90;
sum &= 0xFFFFFFFFL;
long delta = 0x9E3779B9;
delta &= 0xFFFFFFFFL;
// 迭代开始了, @_@
while (loop-- > 0) {
z -= ((y << 4) + c) ^ (y + sum) ^ ((y >>> 5) + d);
z &= 0xFFFFFFFFL;
y -= ((z << 4) + a) ^ (z + sum) ^ ((z >>> 5) + b);
y &= 0xFFFFFFFFL;
sum -= delta;
sum &= 0xFFFFFFFFL;
}
bas.reset();
writeInt((int) y);
writeInt((int) z);
return bas.toByteArray();
}
/**
* 写入一个整型到输出流,高字节优先
*/
private void writeInt(int t) {
bas.write(t >>> 24);
bas.write(t >>> 16);
bas.write(t >>> 8);
bas.write(t);
}
/**
* 解密
*
* @param in 密文
* @return 明文
*/
private byte[] decipher(byte[] in) {
return decipher(in, 0);
}
/**
* 加密8字节
*/
private void encrypt8Bytes() {
// 这部分完成我上面所说的 plain ^ preCrypt,注意这里判断了是不是第一个8字节块,如果是的话,那个prePlain就当作preCrypt用
for (pos = 0; pos < 8; pos++) {
if (header)
plain[pos] ^= prePlain[pos];
else
plain[pos] ^= out[preCrypt + pos];
}
// 这个完成我上面说的 f(plain ^ preCrypt)
byte[] crypted = encipher(plain);
// 这个没什么,就是拷贝一下,java不像c,所以我只好这么干,c就不用这一步了
System.arraycopy(crypted, 0, out, crypt, 8);
// 这个完成了 f(plain ^ preCrypt) ^ prePlain,ok,下面拷贝一下就行了
for (pos = 0; pos < 8; pos++)
out[crypt + pos] ^= prePlain[pos];
System.arraycopy(plain, 0, prePlain, 0, 8);
// 完成了加密,现在是调整crypt,preCrypt等等东西的时候了
preCrypt = crypt;
crypt += 8;
pos = 0;
header = false;
}
/**
* 解密8个字节
*
* @param in 密文字节数组
* @param offset 从何处开始解密
* @param len 密文的长度
* @return true表示解密成功
*/
private void decrypt8Bytes(byte[] in, int offset, int len) {
// 这里第一步就是判断后面还有没有数据,没有就返回,如果有,就执行 crypt ^ prePlain
for (pos = 0; pos < 8; pos++) {
if (contextStart + pos >= len)
return;
prePlain[pos] ^= in[offset + crypt + pos];
}
// 好,这里执行到了 d(crypt ^ prePlain)
prePlain = decipher(prePlain);
// 解密完成,最后一步好像没做?
// 这里最后一步放到decrypt里面去做了,因为解密的步骤有点不太一样
// 调整这些变量的值先
contextStart += 8;
crypt += 8;
pos = 0;
}
/**
* 这是个随机因子产生器,用来填充头部的,如果为了调试,可以用一个固定值
* 随机因子可以使相同的明文每次加密出来的密文都不一样
*
* @return 随机因子
*/
private int rand() {
return random.nextInt();
}
public static long getUnsignedInt(byte[] in, int offset, int len) {
long ret = 0L;
int end;
if (len > 8)
end = offset + 8;
else
end = offset + len;
for (int i = offset; i < end; i++) {
ret <<= 8;
ret |= in[i] & 0xff;
}
return ret & 0xffffffffL | ret >>> 32;
}
} | CrackerCat/unidbg-fetch-qsign | src/main/java/com/tencent/crypt/Crypt.java | 3,885 | // 字节输出流 | line_comment | zh-cn | package com.tencent.crypt;
import java.io.ByteArrayOutputStream;
import java.util.Random;
public class Crypt {
// 指向当前的明文块
private byte[] plain;
// 这指向前面一个明文块
private byte[] prePlain;
// 输出的密文或者明文
private byte[] out;
// 当前加密的密文位置和上一次加密的密文块位置,他们相差8
private int crypt, preCrypt;
// 当前处理的加密解密块的位置
private int pos;
// 填充数
private int padding;
// 密钥
private byte[] key;
// 用于加密时,表示当前是否是第一个8字节块,因为加密算法是反馈的
// 但是最开始的8个字节没有反馈可用,所有需要标明这种情况
private boolean header = true;
// 这个表示当前解密开始的位置,之所以要这么一个变量是为了避免当解密到最后时
// 后面已经没有数据,这时候就会出错,这个变量就是用来判断这种情况免得出错
private int contextStart;
// 随机数对象
private static final Random random = new Random();
// 字节 <SUF>
private final ByteArrayOutputStream bas;
/**
* 构造函数
*/
public Crypt() {
bas = new ByteArrayOutputStream(8);
}
/**
* 解密
*
* @param in 密文
* @param offset 密文开始的位置
* @param len 密文长度
* @param k 密钥
* @return 明文
*/
public byte[] decrypt(byte[] in, int offset, int len, byte[] k) {
// 检查密钥
if (k == null)
return null;
crypt = preCrypt = 0;
this.key = k;
int count;
byte[] m = new byte[offset + 8];
// 因为QQ消息加密之后至少是16字节,并且肯定是8的倍数,这里检查这种情况
if ((len % 8 != 0) || (len < 16)) return null;
// 得到消息的头部,关键是得到真正明文开始的位置,这个信息存在第一个字节里面,所以其用解密得到的第一个字节与7做与
prePlain = decipher(in, offset);
pos = prePlain[0] & 0x7;
// 得到真正明文的长度
count = len - pos - 10;
// 如果明文长度小于0,那肯定是出错了,比如传输错误之类的,返回
if (count < 0) return null;
// 这个是临时的preCrypt,和加密时第一个8字节块没有prePlain一样,解密时
// 第一个8字节块也没有preCrypt,所有这里建一个全0的
for (int i = offset; i < m.length; i++)
m[i] = 0;
// 通过了上面的代码,密文应该是没有问题了,我们分配输出缓冲区
out = new byte[count];
// 设置preCrypt的位置等于0,注意目前的preCrypt位置是指向m的,因为java没有指针,所以我们在后面要控制当前密文buf的引用
preCrypt = 0;
// 当前的密文位置,为什么是8不是0呢?注意前面我们已经解密了头部信息了,现在当然该8了
crypt = 8;
// 自然这个也是8
contextStart = 8;
// 加1,和加密算法是对应的
pos++;
// 开始跳过头部,如果在这个过程中满了8字节,则解密下一块
// 因为是解密下一块,所以我们有一个语句 m = in,下一块当然有preCrypt了,我们不再用m了
// 但是如果不满8,这说明了什么?说明了头8个字节的密文是包含了明文信息的,当然还是要用m把明文弄出来
// 所以,很显然,满了8的话,说明了头8个字节的密文除了一个长度信息有用之外,其他都是无用的填充
padding = 1;
while (padding <= 2) {
if (pos < 8) {
pos++;
padding++;
}
if (pos == 8) {
m = in;
decrypt8Bytes(in, offset, len);
}
}
// 这里是解密的重要阶段,这个时候头部的填充都已经跳过了,开始解密
// 注意如果上面一个while没有满8,这里第一个if里面用的就是原始的m,否则这个m就是in了
int i = 0;
while (count != 0) {
if (pos < 8) {
out[i] = (byte) (m[offset + preCrypt + pos] ^ prePlain[pos]);
i++;
count--;
pos++;
}
if (pos == 8) {
m = in;
preCrypt = crypt - 8;
decrypt8Bytes(in, offset, len);
}
}
// 最后的解密部分,上面一个while已经把明文都解出来了,就剩下尾部的填充了,应该全是0
// 所以这里有检查是否解密了之后是不是0,如果不是的话那肯定出错了,返回null
for (padding = 1; padding < 8; padding++) {
if (pos < 8) {
if ((m[offset + preCrypt + pos] ^ prePlain[pos]) != 0)
return null;
pos++;
}
if (pos == 8) {
m = in;
preCrypt = crypt;
decrypt8Bytes(in, offset, len);
}
}
return out;
}
public byte[] decrypt(byte[] in, byte[] k) {
return decrypt(in, 0, in.length, k);
}
public byte[] encrypt(byte[] in, int offset, int len, byte[] k) {
// 检查密钥
if (k == null)
return in;
plain = new byte[8];
prePlain = new byte[8];
padding = 0;
crypt = preCrypt = 0;
this.key = k;
header = true;
// 计算头部填充字节数
pos = (len + 0x0A) % 8;
if (pos != 0)
pos = 8 - pos;
// 计算输出的密文长度
out = new byte[len + pos + 10];
// 这里的操作把pos存到了plain的第一个字节里面
// 0xF8后面三位是空的,正好留给pos,因为pos是0到7的值,表示文本开始的字节位置
plain[0] = (byte) ((rand() & 0xF8) | pos);
// 这里用随机产生的数填充plain[1]到plain[pos]之间的内容
for (int i = 1; i <= pos; i++)
plain[i] = (byte) (rand() & 0xFF);
pos++;
// 这个就是prePlain,第一个8字节块当然没有prePlain,所以我们做一个全0的给第一个8字节块
for (int i = 0; i < 8; i++)
prePlain[i] = 0x0;
// 继续填充2个字节的随机数,这个过程中如果满了8字节就加密之
padding = 1;
while (padding <= 2) {
if (pos < 8) {
plain[pos++] = (byte) (rand() & 0xFF);
padding++;
}
if (pos == 8)
encrypt8Bytes();
}
// 头部填充完了,这里开始填真正的明文了,也是满了8字节就加密,一直到明文读完
int i = offset;
while (len > 0) {
if (pos < 8) {
plain[pos++] = in[i++];
len--;
}
if (pos == 8)
encrypt8Bytes();
}
// 最后填上0,以保证是8字节的倍数
padding = 1;
while (padding <= 7) {
if (pos < 8) {
plain[pos++] = 0x0;
padding++;
}
if (pos == 8)
encrypt8Bytes();
}
return out;
}
public byte[] encrypt(byte[] in, byte[] k) {
return encrypt(in, 0, in.length, k);
}
private byte[] encipher(byte[] in) {
// 迭代次数,16次
int loop = 0x10;
// 得到明文和密钥的各个部分,注意java没有无符号类型,所以为了表示一个无符号的整数
// 我们用了long,这个long的前32位是全0的,我们通过这种方式模拟无符号整数,后面用到的long也都是一样的
// 而且为了保证前32位为0,需要和0xFFFFFFFF做一下位与
long y = getUnsignedInt(in, 0, 4);
long z = getUnsignedInt(in, 4, 4);
long a = getUnsignedInt(key, 0, 4);
long b = getUnsignedInt(key, 4, 4);
long c = getUnsignedInt(key, 8, 4);
long d = getUnsignedInt(key, 12, 4);
// 这是算法的一些控制变量,为什么delta是0x9E3779B9呢?
// 这个数是TEA算法的delta,实际是就是(sqr(5) - 1) * 2^31 (根号5,减1,再乘2的31次方)
long sum = 0;
long delta = 0x9E3779B9;
delta &= 0xFFFFFFFFL;
// 开始迭代了,乱七八糟的,我也看不懂,反正和DES之类的差不多,都是这样倒来倒去
while (loop-- > 0) {
sum += delta;
sum &= 0xFFFFFFFFL;
y += ((z << 4) + a) ^ (z + sum) ^ ((z >>> 5) + b);
y &= 0xFFFFFFFFL;
z += ((y << 4) + c) ^ (y + sum) ^ ((y >>> 5) + d);
z &= 0xFFFFFFFFL;
}
// 最后,我们输出密文,因为我用的long,所以需要强制转换一下变成int
bas.reset();
writeInt((int) y);
writeInt((int) z);
return bas.toByteArray();
}
/**
* 解密从offset开始的8字节密文
*
* @param in 密文字节数组
* @param offset 密文开始位置
* @return 明文
*/
private byte[] decipher(byte[] in, int offset) {
// 迭代次数,16次
int loop = 0x10;
// 得到密文和密钥的各个部分,注意java没有无符号类型,所以为了表示一个无符号的整数
// 我们用了long,这个long的前32位是全0的,我们通过这种方式模拟无符号整数,后面用到的long也都是一样的
// 而且为了保证前32位为0,需要和0xFFFFFFFF做一下位与
long y = getUnsignedInt(in, offset, 4);
long z = getUnsignedInt(in, offset + 4, 4);
long a = getUnsignedInt(key, 0, 4);
long b = getUnsignedInt(key, 4, 4);
long c = getUnsignedInt(key, 8, 4);
long d = getUnsignedInt(key, 12, 4);
// 算法的一些控制变量,sum在这里也有数了,这个sum和迭代次数有关系
// 因为delta是这么多,所以sum如果是这么多的话,迭代的时候减减减,减16次,最后
// 得到0。反正这就是为了得到和加密时相反顺序的控制变量,这样才能解密呀~~
long sum = 0xE3779B90;
sum &= 0xFFFFFFFFL;
long delta = 0x9E3779B9;
delta &= 0xFFFFFFFFL;
// 迭代开始了, @_@
while (loop-- > 0) {
z -= ((y << 4) + c) ^ (y + sum) ^ ((y >>> 5) + d);
z &= 0xFFFFFFFFL;
y -= ((z << 4) + a) ^ (z + sum) ^ ((z >>> 5) + b);
y &= 0xFFFFFFFFL;
sum -= delta;
sum &= 0xFFFFFFFFL;
}
bas.reset();
writeInt((int) y);
writeInt((int) z);
return bas.toByteArray();
}
/**
* 写入一个整型到输出流,高字节优先
*/
private void writeInt(int t) {
bas.write(t >>> 24);
bas.write(t >>> 16);
bas.write(t >>> 8);
bas.write(t);
}
/**
* 解密
*
* @param in 密文
* @return 明文
*/
private byte[] decipher(byte[] in) {
return decipher(in, 0);
}
/**
* 加密8字节
*/
private void encrypt8Bytes() {
// 这部分完成我上面所说的 plain ^ preCrypt,注意这里判断了是不是第一个8字节块,如果是的话,那个prePlain就当作preCrypt用
for (pos = 0; pos < 8; pos++) {
if (header)
plain[pos] ^= prePlain[pos];
else
plain[pos] ^= out[preCrypt + pos];
}
// 这个完成我上面说的 f(plain ^ preCrypt)
byte[] crypted = encipher(plain);
// 这个没什么,就是拷贝一下,java不像c,所以我只好这么干,c就不用这一步了
System.arraycopy(crypted, 0, out, crypt, 8);
// 这个完成了 f(plain ^ preCrypt) ^ prePlain,ok,下面拷贝一下就行了
for (pos = 0; pos < 8; pos++)
out[crypt + pos] ^= prePlain[pos];
System.arraycopy(plain, 0, prePlain, 0, 8);
// 完成了加密,现在是调整crypt,preCrypt等等东西的时候了
preCrypt = crypt;
crypt += 8;
pos = 0;
header = false;
}
/**
* 解密8个字节
*
* @param in 密文字节数组
* @param offset 从何处开始解密
* @param len 密文的长度
* @return true表示解密成功
*/
private void decrypt8Bytes(byte[] in, int offset, int len) {
// 这里第一步就是判断后面还有没有数据,没有就返回,如果有,就执行 crypt ^ prePlain
for (pos = 0; pos < 8; pos++) {
if (contextStart + pos >= len)
return;
prePlain[pos] ^= in[offset + crypt + pos];
}
// 好,这里执行到了 d(crypt ^ prePlain)
prePlain = decipher(prePlain);
// 解密完成,最后一步好像没做?
// 这里最后一步放到decrypt里面去做了,因为解密的步骤有点不太一样
// 调整这些变量的值先
contextStart += 8;
crypt += 8;
pos = 0;
}
/**
* 这是个随机因子产生器,用来填充头部的,如果为了调试,可以用一个固定值
* 随机因子可以使相同的明文每次加密出来的密文都不一样
*
* @return 随机因子
*/
private int rand() {
return random.nextInt();
}
public static long getUnsignedInt(byte[] in, int offset, int len) {
long ret = 0L;
int end;
if (len > 8)
end = offset + 8;
else
end = offset + len;
for (int i = offset; i < end; i++) {
ret <<= 8;
ret |= in[i] & 0xff;
}
return ret & 0xffffffffL | ret >>> 32;
}
} | 1 | 8 | 1 |
2668_15 | package com.lingjuan.app.fragment.later;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.lingjuan.app.R;
import com.lingjuan.app.activity.CategoricalActivity;
import com.lingjuan.app.activity.MainActivity;
import com.lingjuan.app.activity.PurchaseActivity;
import com.lingjuan.app.activity.SearchActivity;
import com.lingjuan.app.adapter.LatesAdapter;
import com.lingjuan.app.adapter.YouPinAdapter;
import com.lingjuan.app.api.Iben;
import com.lingjuan.app.base.BaseFrament;
import com.lingjuan.app.base.ExampleApplication;
import com.lingjuan.app.uitls.DialogUtil;
import com.lingjuan.app.uitls.HttpMethods;
import com.lingjuan.app.uitls.SharedPreferenceUtil;
import com.lingjuan.app.uitls.ToastUtils;
import com.lingjuan.app.witde.NetworkImageHolderView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;
/**
* Created by sks on 2017/8/19.
* time 2017年8月19日18:50:10
* titile 推举模块
*/
public class LatestFragment extends BaseFrament implements View.OnClickListener {
private PullToRefreshListView mPullRefreshGridView;
private ListView mGridView;
private int qishi;
private View Heaner;
private LinearLayout buju;
private ArrayList<Map<String,Object>> mapArrayList;
private ArrayList<Map<String,Object>> DanArrayList;
private YouPinAdapter latesAdapter;
private ConvenientBanner convenientBanner;
private int paths = 1;
private int [] ints = {R.mipmap.ic_page_indicator,R.mipmap.ic_page_indicator_focused};
private String pathUrl ;
private CircleImageView tu1,tu2,tu3,tu4,tu5,tu6,tu7,tu8,tu9,tu10;
private ProgressDialog dialogs;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
dialogs.setProgress(msg.what);
super.handleMessage(msg);
}
};
private KProgressHUD hud;
private AlertDialog adDialog;
/**
* Fragment传值
*
* @param type
* @return
*/
public static LatestFragment newIntes(int type) {
LatestFragment df = new LatestFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", type);
df.setArguments(bundle);
return df;
}
@Override
protected void init(View view) {
dialogs = new ProgressDialog(getActivity());
buju = (LinearLayout) view.findViewById(R.id.buju);
Heaner = LayoutInflater.from(getActivity()).inflate(R.layout.listview_addhoe,null);
mPullRefreshGridView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
convenientBanner = (ConvenientBanner) Heaner.findViewById(R.id.iamges);
mGridView.addHeaderView(Heaner);
addViewinit(Heaner);
mPullRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//设置下拉时显示的日期和时间
String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// 更新显示的label
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mPullRefreshGridView.onRefreshComplete();
Toast.makeText(ExampleApplication.context, "已经到底了", Toast.LENGTH_SHORT).show();
}
},6000);
}
});
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//设置下拉时显示的日期和时间
String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// 更新显示的label
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
paths = paths+1;
getErCiRequestdata(paths);
}
});
List<String> urls = new ArrayList<>();
urls.add("https://img.alicdn.com/imgextra/i4/2508158775/TB2jD0adosIL1JjSZPiXXXKmpXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i1/2508158775/TB2r6aaXrKFJuJjSszgXXXVnXXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i3/2508158775/TB2BmewdEEIL1JjSZFFXXc5kVXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i2/2508158775/TB2BDsXchsIL1JjSZFqXXceCpXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i3/2508158775/TB2z2RgabsTMeJjSszgXXacpFXa_!!2508158775.jpg");
convenientBanner = (ConvenientBanner) view.findViewById(R.id.iamges);
convenientBanner.setPointViewVisible(true);
convenientBanner.startTurning(7000);
convenientBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
convenientBanner.setPageIndicator(ints);
//网络地址
//网络加载例子
if(Iben.mLunBo != null){
convenientBanner.setPages(new CBViewHolderCreator() {
@Override
public Object createHolder() {
return new NetworkImageHolderView();
}
},Iben.mLunBo);
}else {
convenientBanner.setPages(new CBViewHolderCreator() {
@Override
public Object createHolder() {
return new NetworkImageHolderView();
}
},urls);
}
//点击事件
convenientBanner.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
//跳转商品
if(DanArrayList != null){
DanArrayList.clear();
}
getDanPinSouSUo(position);
}
});
if(Iben.mapArrayList != null){
//加载数据
mapArrayList = Iben.mapArrayList;
buju.setVisibility(View.GONE);
latesAdapter = new YouPinAdapter(mapArrayList,getActivity());
mGridView.setAdapter(latesAdapter);
Iben.mapArrayList = null;
System.gc();
}else {
getRequestdata();
}
//获取
StartGengXin();
//获取PID
//getYaoqingM();
//设置邀请码
String pid = Iben.YURL = (String) SharedPreferenceUtil.get(getActivity(),"name","0");
if(pid.equals("0")){
Diods();
}else {
getYaoqingM(pid);
}
/**
* 跳转
*/
/**
* 跳转
*/
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), PurchaseActivity.class);
intent.putExtra("list",mapArrayList);
intent.putExtra("posd", position);
intent.putExtra("type", 2);
startActivity(intent);
}
});
}
/**
* 绑定布局
* @return
*/
@Override
protected int getLayout() {
return R.layout.framgnet_shouye;
}
/**
* 加载更多
* @param path
*/
private void getErCiRequestdata(int path) {
HttpMethods.BASE_URL = "http://openapi.qingtaoke.com/";
HttpMethods.getInstance().getJiuJIud(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
// Toast.makeText(getActivity(), "请求失败,请稍后尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
buju.setVisibility(View.GONE);
// Toast.makeText(getActivity(), "==="+s, Toast.LENGTH_SHORT).show();
//mapArrayList = getArrJson(s);
mapArrayList.addAll(getArrJson(s));
latesAdapter.setMapArrayList(mapArrayList);
latesAdapter.notifyDataSetChanged();
mPullRefreshGridView.onRefreshComplete();
//Toast.makeText(getActivity(), "13到底了", Toast.LENGTH_SHORT).show();
}
}, path,0);
}
/**
* 第一次请求网络数据
*/
private void getRequestdata() {
hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
HttpMethods.BASE_URL = "http://openapi.qingtaoke.com/";
HttpMethods.getInstance().getJiuJIud(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
hud.dismiss();
//Toast.makeText(getActivity(), "请求失败,请稍后尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
buju.setVisibility(View.GONE);
hud.dismiss();
// Toast.makeText(getActivity(), "==="+s, Toast.LENGTH_SHORT).show();
mapArrayList = getArrJson(s);
latesAdapter = new YouPinAdapter(mapArrayList, getActivity());
mGridView.setAdapter(latesAdapter);
}
}, 1,0);
}
/**
* 解析json
* @param string 要解析的字符串
* @return
*/
private ArrayList<Map<String, Object>> getArrJson(String string) {
ArrayList<Map<String, Object>> List = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(string);
JSONObject jsonArray = jsonObject.getJSONObject("data");
JSONArray listjsonarrya = jsonArray.getJSONArray("list");
for (int i = 0; i < listjsonarrya.length(); i++) {
JSONObject jsonObject1 = listjsonarrya.getJSONObject(i);
Map<String, Object> map = new HashMap<>();
map.put("goods_id", jsonObject1.getString("goods_id"));//ID
map.put("goods_pic", jsonObject1.getString("goods_pic"));//商品名字
map.put("goods_title", jsonObject1.getString("goods_title"));//商品ID
map.put("goods_short_title", jsonObject1.getString("goods_short_title"));//分类ID
map.put("goods_cat", jsonObject1.getString("goods_cat"));//分类名字
map.put("goods_price", jsonObject1.getDouble("goods_price"));//商品URL
map.put("goods_sales", jsonObject1.getString("goods_sales"));//商品图片
map.put("goods_introduce", jsonObject1.getString("goods_introduce"));//在线售价
map.put("seller_id", jsonObject1.getString("seller_id"));//劵后售价
map.put("coupon_id", jsonObject1.getString("coupon_id"));//优惠券价格
map.put("coupon_price", jsonObject1.getDouble("coupon_price"));//月销量
List.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return List;
}
/**
* 获取版本信息
*/
private void StartGengXin(){
HttpMethods.BASE_URL = "http://www.aiboyy.pw/";
HttpMethods.getInstance().getGengXin(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Toast.makeText(ExampleApplication.context, "服务器发送错误!,请联系管理员", Toast.LENGTH_SHORT).show();
//getActivity().finish();
}
@Override
public void onNext(String s) {
try {
//qidong
getLists(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 解析JSON
* @param response
* @return
* @throws Exception
*/
public void getLists(String response) throws Exception {
try {
JSONArray json = new JSONArray(response);;
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String banben = jsonObject.getString("banebn");
String gengxin = jsonObject.getString("gengxin");
final String url = jsonObject.getString("url");
if(!getVersionName().equals(banben)){
Diods(gengxin,url);
/* DialogUtil.showMsgDialog(getActivity(), gengxin, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//ad.dismiss();
//下载更新
dialogs.setCanceledOnTouchOutside(false);
dialogs.setTitle("正在下载");
dialogs.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialogs.setCancelable(false);
dialogs.show();
new Thread(new Runnable() {
@Override
public void run() {
getURL(url);
}
}).start();
}
});*/
}else {
Toast.makeText(getActivity(), "当前版本为最新版本", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
/**
* 获取版本号
* @return
*/
private String getVersionName() {
// 获取packagemanager的实例
PackageManager packageManager = getActivity().getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(getActivity().getPackageName(),0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = packInfo.versionName;
return version;
}
/**
* 启动应用安装。
*/
private void setupApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
//"file://"+文件路径。
Uri uri = Uri.parse("file://"+ pathUrl);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 启动更新
* @param GengXin
*/
private void getURL(String GengXin){
try {
//构建URL地址
URL url = new URL(GengXin);
try {
//打开打开打开
HttpURLConnection hcont = (HttpURLConnection) url.openConnection();
//建立实际链接
hcont.connect();
//获取输入流内容
InputStream is = hcont.getInputStream();
//获取文件长度
int ddddd =hcont.getContentLength();
//为进度条赋值
dialogs.setMax(ddddd);
//手机存储地址
pathUrl = getActivity().getExternalCacheDir().getPath()+"/lingjuan.apk";
//写入文件
OutputStream os = new FileOutputStream(pathUrl);
int length;
int lengtsh = 0;
byte [] bytes = new byte[1024];
while ((length = is.read(bytes))!= -1){
os.write(bytes,0,length);
//获取当前进度值
lengtsh+=length;
//把值传给handler
handler.sendEmptyMessage(lengtsh);
}
//关闭流
is.close();
os.close();
os.flush();
//dialogs.dismiss();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT).show();
setupApk();
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* 弹出布局
* @param yirme
*/
private void Diods(String name, final String dizhi){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.AlertDialogStyle);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.custom_dialog_two_layout, null);
TextView bt = (TextView) view.findViewById(R.id.tv_msg);
Button but_id = (Button) view.findViewById(R.id.btn_update);
bt.setText(name);
builder.setView(view);
final AlertDialog ad = builder.create();
ad.show();
ad.setCanceledOnTouchOutside(false);
ad.setCancelable(false);
//取消更新
//确定更新
but_id.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ad.dismiss();
dialogs.setCanceledOnTouchOutside(false);
dialogs.setTitle("正在下载");
dialogs.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialogs.setCancelable(false);
dialogs.show();
new Thread(new Runnable() {
@Override
public void run() {
getURL(dizhi);
}
}).start();
}
});
}
/**
* 初始化图
* @param view
*/
private void addViewinit(View view){
tu1 = (CircleImageView) view.findViewById(R.id.tubiao1);
tu2 = (CircleImageView) view.findViewById(R.id.tubiao2);
tu3 = (CircleImageView) view.findViewById(R.id.tubiao3);
tu4 = (CircleImageView) view.findViewById(R.id.tubiao4);
tu5 = (CircleImageView) view.findViewById(R.id.tubiao5);
tu6 = (CircleImageView) view.findViewById(R.id.tubiao6);
tu7 = (CircleImageView) view.findViewById(R.id.tubiao7);
tu8 = (CircleImageView) view.findViewById(R.id.tubiao8);
tu9 = (CircleImageView) view.findViewById(R.id.tubiao9);
tu10 = (CircleImageView) view.findViewById(R.id.tubiao10);
tu1.setOnClickListener(this);
tu2.setOnClickListener(this);
tu3.setOnClickListener(this);
tu4.setOnClickListener(this);
tu5.setOnClickListener(this);
tu6.setOnClickListener(this);
tu7.setOnClickListener(this);
tu8.setOnClickListener(this);
tu9.setOnClickListener(this);
tu10.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tubiao1:
IntesnStrac(12);
break;
case R.id.tubiao2:
IntesnStrac(10);
break;
case R.id.tubiao3:
IntesnStrac(11);
break;
case R.id.tubiao4:
IntesnStrac(8);
break;
case R.id.tubiao5:
IntesnStrac(4);
break;
case R.id.tubiao6:
IntesnStrac(3);
break;
case R.id.tubiao7:
IntesnStrac(5);
break;
case R.id.tubiao8:
IntesnStrac(6);
break;
case R.id.tubiao9:
IntesnStrac(7);
break;
case R.id.tubiao10:
IntesnStrac(2);
break;
}
}
/**
* 跳转分类Activity
*/
private void IntesnStrac(int type){
Intent intent = new Intent(getActivity(), CategoricalActivity.class);
intent.putExtra("type",type);
getActivity().startActivity(intent);
}
/**
* 第一次请求网络数据
*/
private void getDanPinSouSUo(int position) {
hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
HttpMethods.BASE_URL = "http://api.tkjidi.com/";
HttpMethods.getInstance().getDanGe(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
hud.dismiss();
Toast.makeText(getActivity(), "请求失败,请稍后尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
buju.setVisibility(View.GONE);
hud.dismiss();
DanArrayList = getDanList(s);
//判定商品数据不为空
if(DanArrayList.get(0).size() != 1){
Intent intent = new Intent(getActivity(), PurchaseActivity.class);
intent.putExtra("list",DanArrayList);
intent.putExtra("posd", 0);
intent.putExtra("type", 5);
startActivity(intent);
}else {
ToastUtils.showToastInCenter(getActivity(),1,"暂时没有这个商品",Toast.LENGTH_SHORT);
}
}
},Iben.mLunId.get(position));
}
/**
* 解析轮播图的商品
* @param json
* @return
*/
private ArrayList<Map<String,Object>> getDanList(String json){
ArrayList<Map<String,Object>> DanArrayListds = null;
try {
DanArrayListds = new ArrayList<>();
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
Map<String,Object> map = new HashMap<>();
String quan_id2 = jsonObject1.getString("quan_id");
if(!quan_id2.equals("")){
String goods_id = jsonObject1.getString("goods_id");
String price = jsonObject1.getString("price");
String price_after_coupons = jsonObject1.getString("price_after_coupons");
String price_coupons = jsonObject1.getString("price_coupons");
String pic = jsonObject1.getString("pic");
String quan_guid_content = jsonObject1.getString("quan_guid_content");
String quan_id = jsonObject1.getString("quan_id");
String sales = jsonObject1.getString("sales");
String goods_name = jsonObject1.getString("goods_name");
map.put("goods_id",goods_id);
map.put("price",price);
map.put("sales",sales);
map.put("price_after_coupons",price_after_coupons);
map.put("price_coupons",price_coupons);
map.put("pic",pic);
map.put("quan_guid_content",quan_guid_content);
map.put("quan_id",quan_id);
map.put("goods_name",goods_name);
DanArrayListds.add(map);
}else {
map.put("21313","为空");
DanArrayListds.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return DanArrayListds;
}
/**
* PID的获取
*/
private void getYaoqingM(final String name, final AlertDialog alertDialog) {
hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
HttpMethods.BASE_URL = "http://www.aiboyy.pw/";
HttpMethods.getInstance().getPid(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
alertDialog.dismiss();
hud.dismiss();
Iben.YURL = (String) SharedPreferenceUtil.get(getActivity(),"pid","0");
Iben.QQ = (String) SharedPreferenceUtil.get(getActivity(),"qq","123");
//SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
}
@Override
public void onNext(String s) {
hud.dismiss();
try {
JSONArray jsonObject2 = new JSONArray(s);
JSONObject jsonObject = jsonObject2.getJSONObject(0);
if(!jsonObject.getString("name").equals("110") && !jsonObject.getString("cate_id").equals("110")){
alertDialog.dismiss();
Iben.YURL = jsonObject.getString("name");
Iben.QQ = jsonObject.getString("cate_id");
SharedPreferenceUtil.put(getActivity(),"pid",Iben.YURL);
SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
SharedPreferenceUtil.put(getActivity(),"name",name);
System.out.println("=======我获取到的PID是:"+Iben.YURL+",获取到的QQ是:"+Iben.QQ);
ToastUtils.showToastInCenter(getActivity(),2,"当日数据已更新",Toast.LENGTH_SHORT);
}else {
// getActivity().finish();
ToastUtils.showToastInCenter(getActivity(),1,"专属码错误请重新输入",Toast.LENGTH_SHORT);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},name);
}
/**
* PID的获取
*/
private void getYaoqingM(String name) {
/* hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();*/
HttpMethods.BASE_URL = "http://www.aiboyy.pw/";
HttpMethods.getInstance().getPid(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
// hud.dismiss();
Iben.YURL = (String) SharedPreferenceUtil.get(getActivity(),"pid","0");
Iben.QQ = (String) SharedPreferenceUtil.get(getActivity(),"qq","123");
//SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
}
@Override
public void onNext(String s) {
// hud.dismiss();
try {
JSONArray jsonObject2 = new JSONArray(s);
JSONObject jsonObject = jsonObject2.getJSONObject(0);
if(!jsonObject.getString("name").equals("110") && !jsonObject.getString("cate_id").equals("110")){
Iben.YURL = jsonObject.getString("name");
Iben.QQ = jsonObject.getString("cate_id");
SharedPreferenceUtil.put(getActivity(),"pid",Iben.YURL);
SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
System.out.println("=======我获取到的PID是:"+Iben.YURL+",获取到的QQ是:"+Iben.QQ);
ToastUtils.showToastInCenter(getActivity(),2,"当日数据已更新",Toast.LENGTH_SHORT);
}else {
// getActivity().finish();
ToastUtils.showToastInCenter(getActivity(),1,"请重新输入",Toast.LENGTH_SHORT);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},name);
}
/**
* 弹出布局
*/
private void Diods(){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(false);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_share,null);
Button bt = (Button) view.findViewById(R.id.dialog_btn_pay);
final EditText editName = (EditText) view.findViewById(R.id.et_registerPhone);
builder.setView(view);
adDialog = builder.create();
adDialog.show();
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Name = editName.getText().toString();
if(!Name.equals("") && Name.trim().length() != 0 ){
getYaoqingM(Name,adDialog);
}else {
Toast.makeText(getActivity(), "请输入内容在点击,谢谢", Toast.LENGTH_SHORT).show();
}
}
});
}
} | CrackgmKey/lingJuan | lingjuaner/src/main/java/com/lingjuan/app/fragment/later/LatestFragment.java | 7,395 | //加载数据 | line_comment | zh-cn | package com.lingjuan.app.fragment.later;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.lingjuan.app.R;
import com.lingjuan.app.activity.CategoricalActivity;
import com.lingjuan.app.activity.MainActivity;
import com.lingjuan.app.activity.PurchaseActivity;
import com.lingjuan.app.activity.SearchActivity;
import com.lingjuan.app.adapter.LatesAdapter;
import com.lingjuan.app.adapter.YouPinAdapter;
import com.lingjuan.app.api.Iben;
import com.lingjuan.app.base.BaseFrament;
import com.lingjuan.app.base.ExampleApplication;
import com.lingjuan.app.uitls.DialogUtil;
import com.lingjuan.app.uitls.HttpMethods;
import com.lingjuan.app.uitls.SharedPreferenceUtil;
import com.lingjuan.app.uitls.ToastUtils;
import com.lingjuan.app.witde.NetworkImageHolderView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;
/**
* Created by sks on 2017/8/19.
* time 2017年8月19日18:50:10
* titile 推举模块
*/
public class LatestFragment extends BaseFrament implements View.OnClickListener {
private PullToRefreshListView mPullRefreshGridView;
private ListView mGridView;
private int qishi;
private View Heaner;
private LinearLayout buju;
private ArrayList<Map<String,Object>> mapArrayList;
private ArrayList<Map<String,Object>> DanArrayList;
private YouPinAdapter latesAdapter;
private ConvenientBanner convenientBanner;
private int paths = 1;
private int [] ints = {R.mipmap.ic_page_indicator,R.mipmap.ic_page_indicator_focused};
private String pathUrl ;
private CircleImageView tu1,tu2,tu3,tu4,tu5,tu6,tu7,tu8,tu9,tu10;
private ProgressDialog dialogs;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
dialogs.setProgress(msg.what);
super.handleMessage(msg);
}
};
private KProgressHUD hud;
private AlertDialog adDialog;
/**
* Fragment传值
*
* @param type
* @return
*/
public static LatestFragment newIntes(int type) {
LatestFragment df = new LatestFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", type);
df.setArguments(bundle);
return df;
}
@Override
protected void init(View view) {
dialogs = new ProgressDialog(getActivity());
buju = (LinearLayout) view.findViewById(R.id.buju);
Heaner = LayoutInflater.from(getActivity()).inflate(R.layout.listview_addhoe,null);
mPullRefreshGridView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
convenientBanner = (ConvenientBanner) Heaner.findViewById(R.id.iamges);
mGridView.addHeaderView(Heaner);
addViewinit(Heaner);
mPullRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//设置下拉时显示的日期和时间
String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// 更新显示的label
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mPullRefreshGridView.onRefreshComplete();
Toast.makeText(ExampleApplication.context, "已经到底了", Toast.LENGTH_SHORT).show();
}
},6000);
}
});
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//设置下拉时显示的日期和时间
String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// 更新显示的label
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
paths = paths+1;
getErCiRequestdata(paths);
}
});
List<String> urls = new ArrayList<>();
urls.add("https://img.alicdn.com/imgextra/i4/2508158775/TB2jD0adosIL1JjSZPiXXXKmpXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i1/2508158775/TB2r6aaXrKFJuJjSszgXXXVnXXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i3/2508158775/TB2BmewdEEIL1JjSZFFXXc5kVXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i2/2508158775/TB2BDsXchsIL1JjSZFqXXceCpXa_!!2508158775.jpg");
urls.add("https://img.alicdn.com/imgextra/i3/2508158775/TB2z2RgabsTMeJjSszgXXacpFXa_!!2508158775.jpg");
convenientBanner = (ConvenientBanner) view.findViewById(R.id.iamges);
convenientBanner.setPointViewVisible(true);
convenientBanner.startTurning(7000);
convenientBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
convenientBanner.setPageIndicator(ints);
//网络地址
//网络加载例子
if(Iben.mLunBo != null){
convenientBanner.setPages(new CBViewHolderCreator() {
@Override
public Object createHolder() {
return new NetworkImageHolderView();
}
},Iben.mLunBo);
}else {
convenientBanner.setPages(new CBViewHolderCreator() {
@Override
public Object createHolder() {
return new NetworkImageHolderView();
}
},urls);
}
//点击事件
convenientBanner.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
//跳转商品
if(DanArrayList != null){
DanArrayList.clear();
}
getDanPinSouSUo(position);
}
});
if(Iben.mapArrayList != null){
//加载 <SUF>
mapArrayList = Iben.mapArrayList;
buju.setVisibility(View.GONE);
latesAdapter = new YouPinAdapter(mapArrayList,getActivity());
mGridView.setAdapter(latesAdapter);
Iben.mapArrayList = null;
System.gc();
}else {
getRequestdata();
}
//获取
StartGengXin();
//获取PID
//getYaoqingM();
//设置邀请码
String pid = Iben.YURL = (String) SharedPreferenceUtil.get(getActivity(),"name","0");
if(pid.equals("0")){
Diods();
}else {
getYaoqingM(pid);
}
/**
* 跳转
*/
/**
* 跳转
*/
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), PurchaseActivity.class);
intent.putExtra("list",mapArrayList);
intent.putExtra("posd", position);
intent.putExtra("type", 2);
startActivity(intent);
}
});
}
/**
* 绑定布局
* @return
*/
@Override
protected int getLayout() {
return R.layout.framgnet_shouye;
}
/**
* 加载更多
* @param path
*/
private void getErCiRequestdata(int path) {
HttpMethods.BASE_URL = "http://openapi.qingtaoke.com/";
HttpMethods.getInstance().getJiuJIud(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
// Toast.makeText(getActivity(), "请求失败,请稍后尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
buju.setVisibility(View.GONE);
// Toast.makeText(getActivity(), "==="+s, Toast.LENGTH_SHORT).show();
//mapArrayList = getArrJson(s);
mapArrayList.addAll(getArrJson(s));
latesAdapter.setMapArrayList(mapArrayList);
latesAdapter.notifyDataSetChanged();
mPullRefreshGridView.onRefreshComplete();
//Toast.makeText(getActivity(), "13到底了", Toast.LENGTH_SHORT).show();
}
}, path,0);
}
/**
* 第一次请求网络数据
*/
private void getRequestdata() {
hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
HttpMethods.BASE_URL = "http://openapi.qingtaoke.com/";
HttpMethods.getInstance().getJiuJIud(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
hud.dismiss();
//Toast.makeText(getActivity(), "请求失败,请稍后尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
buju.setVisibility(View.GONE);
hud.dismiss();
// Toast.makeText(getActivity(), "==="+s, Toast.LENGTH_SHORT).show();
mapArrayList = getArrJson(s);
latesAdapter = new YouPinAdapter(mapArrayList, getActivity());
mGridView.setAdapter(latesAdapter);
}
}, 1,0);
}
/**
* 解析json
* @param string 要解析的字符串
* @return
*/
private ArrayList<Map<String, Object>> getArrJson(String string) {
ArrayList<Map<String, Object>> List = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(string);
JSONObject jsonArray = jsonObject.getJSONObject("data");
JSONArray listjsonarrya = jsonArray.getJSONArray("list");
for (int i = 0; i < listjsonarrya.length(); i++) {
JSONObject jsonObject1 = listjsonarrya.getJSONObject(i);
Map<String, Object> map = new HashMap<>();
map.put("goods_id", jsonObject1.getString("goods_id"));//ID
map.put("goods_pic", jsonObject1.getString("goods_pic"));//商品名字
map.put("goods_title", jsonObject1.getString("goods_title"));//商品ID
map.put("goods_short_title", jsonObject1.getString("goods_short_title"));//分类ID
map.put("goods_cat", jsonObject1.getString("goods_cat"));//分类名字
map.put("goods_price", jsonObject1.getDouble("goods_price"));//商品URL
map.put("goods_sales", jsonObject1.getString("goods_sales"));//商品图片
map.put("goods_introduce", jsonObject1.getString("goods_introduce"));//在线售价
map.put("seller_id", jsonObject1.getString("seller_id"));//劵后售价
map.put("coupon_id", jsonObject1.getString("coupon_id"));//优惠券价格
map.put("coupon_price", jsonObject1.getDouble("coupon_price"));//月销量
List.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return List;
}
/**
* 获取版本信息
*/
private void StartGengXin(){
HttpMethods.BASE_URL = "http://www.aiboyy.pw/";
HttpMethods.getInstance().getGengXin(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Toast.makeText(ExampleApplication.context, "服务器发送错误!,请联系管理员", Toast.LENGTH_SHORT).show();
//getActivity().finish();
}
@Override
public void onNext(String s) {
try {
//qidong
getLists(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 解析JSON
* @param response
* @return
* @throws Exception
*/
public void getLists(String response) throws Exception {
try {
JSONArray json = new JSONArray(response);;
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String banben = jsonObject.getString("banebn");
String gengxin = jsonObject.getString("gengxin");
final String url = jsonObject.getString("url");
if(!getVersionName().equals(banben)){
Diods(gengxin,url);
/* DialogUtil.showMsgDialog(getActivity(), gengxin, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//ad.dismiss();
//下载更新
dialogs.setCanceledOnTouchOutside(false);
dialogs.setTitle("正在下载");
dialogs.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialogs.setCancelable(false);
dialogs.show();
new Thread(new Runnable() {
@Override
public void run() {
getURL(url);
}
}).start();
}
});*/
}else {
Toast.makeText(getActivity(), "当前版本为最新版本", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
/**
* 获取版本号
* @return
*/
private String getVersionName() {
// 获取packagemanager的实例
PackageManager packageManager = getActivity().getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(getActivity().getPackageName(),0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = packInfo.versionName;
return version;
}
/**
* 启动应用安装。
*/
private void setupApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
//"file://"+文件路径。
Uri uri = Uri.parse("file://"+ pathUrl);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 启动更新
* @param GengXin
*/
private void getURL(String GengXin){
try {
//构建URL地址
URL url = new URL(GengXin);
try {
//打开打开打开
HttpURLConnection hcont = (HttpURLConnection) url.openConnection();
//建立实际链接
hcont.connect();
//获取输入流内容
InputStream is = hcont.getInputStream();
//获取文件长度
int ddddd =hcont.getContentLength();
//为进度条赋值
dialogs.setMax(ddddd);
//手机存储地址
pathUrl = getActivity().getExternalCacheDir().getPath()+"/lingjuan.apk";
//写入文件
OutputStream os = new FileOutputStream(pathUrl);
int length;
int lengtsh = 0;
byte [] bytes = new byte[1024];
while ((length = is.read(bytes))!= -1){
os.write(bytes,0,length);
//获取当前进度值
lengtsh+=length;
//把值传给handler
handler.sendEmptyMessage(lengtsh);
}
//关闭流
is.close();
os.close();
os.flush();
//dialogs.dismiss();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT).show();
setupApk();
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* 弹出布局
* @param yirme
*/
private void Diods(String name, final String dizhi){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.AlertDialogStyle);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.custom_dialog_two_layout, null);
TextView bt = (TextView) view.findViewById(R.id.tv_msg);
Button but_id = (Button) view.findViewById(R.id.btn_update);
bt.setText(name);
builder.setView(view);
final AlertDialog ad = builder.create();
ad.show();
ad.setCanceledOnTouchOutside(false);
ad.setCancelable(false);
//取消更新
//确定更新
but_id.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ad.dismiss();
dialogs.setCanceledOnTouchOutside(false);
dialogs.setTitle("正在下载");
dialogs.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialogs.setCancelable(false);
dialogs.show();
new Thread(new Runnable() {
@Override
public void run() {
getURL(dizhi);
}
}).start();
}
});
}
/**
* 初始化图
* @param view
*/
private void addViewinit(View view){
tu1 = (CircleImageView) view.findViewById(R.id.tubiao1);
tu2 = (CircleImageView) view.findViewById(R.id.tubiao2);
tu3 = (CircleImageView) view.findViewById(R.id.tubiao3);
tu4 = (CircleImageView) view.findViewById(R.id.tubiao4);
tu5 = (CircleImageView) view.findViewById(R.id.tubiao5);
tu6 = (CircleImageView) view.findViewById(R.id.tubiao6);
tu7 = (CircleImageView) view.findViewById(R.id.tubiao7);
tu8 = (CircleImageView) view.findViewById(R.id.tubiao8);
tu9 = (CircleImageView) view.findViewById(R.id.tubiao9);
tu10 = (CircleImageView) view.findViewById(R.id.tubiao10);
tu1.setOnClickListener(this);
tu2.setOnClickListener(this);
tu3.setOnClickListener(this);
tu4.setOnClickListener(this);
tu5.setOnClickListener(this);
tu6.setOnClickListener(this);
tu7.setOnClickListener(this);
tu8.setOnClickListener(this);
tu9.setOnClickListener(this);
tu10.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tubiao1:
IntesnStrac(12);
break;
case R.id.tubiao2:
IntesnStrac(10);
break;
case R.id.tubiao3:
IntesnStrac(11);
break;
case R.id.tubiao4:
IntesnStrac(8);
break;
case R.id.tubiao5:
IntesnStrac(4);
break;
case R.id.tubiao6:
IntesnStrac(3);
break;
case R.id.tubiao7:
IntesnStrac(5);
break;
case R.id.tubiao8:
IntesnStrac(6);
break;
case R.id.tubiao9:
IntesnStrac(7);
break;
case R.id.tubiao10:
IntesnStrac(2);
break;
}
}
/**
* 跳转分类Activity
*/
private void IntesnStrac(int type){
Intent intent = new Intent(getActivity(), CategoricalActivity.class);
intent.putExtra("type",type);
getActivity().startActivity(intent);
}
/**
* 第一次请求网络数据
*/
private void getDanPinSouSUo(int position) {
hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
HttpMethods.BASE_URL = "http://api.tkjidi.com/";
HttpMethods.getInstance().getDanGe(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
hud.dismiss();
Toast.makeText(getActivity(), "请求失败,请稍后尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
buju.setVisibility(View.GONE);
hud.dismiss();
DanArrayList = getDanList(s);
//判定商品数据不为空
if(DanArrayList.get(0).size() != 1){
Intent intent = new Intent(getActivity(), PurchaseActivity.class);
intent.putExtra("list",DanArrayList);
intent.putExtra("posd", 0);
intent.putExtra("type", 5);
startActivity(intent);
}else {
ToastUtils.showToastInCenter(getActivity(),1,"暂时没有这个商品",Toast.LENGTH_SHORT);
}
}
},Iben.mLunId.get(position));
}
/**
* 解析轮播图的商品
* @param json
* @return
*/
private ArrayList<Map<String,Object>> getDanList(String json){
ArrayList<Map<String,Object>> DanArrayListds = null;
try {
DanArrayListds = new ArrayList<>();
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
Map<String,Object> map = new HashMap<>();
String quan_id2 = jsonObject1.getString("quan_id");
if(!quan_id2.equals("")){
String goods_id = jsonObject1.getString("goods_id");
String price = jsonObject1.getString("price");
String price_after_coupons = jsonObject1.getString("price_after_coupons");
String price_coupons = jsonObject1.getString("price_coupons");
String pic = jsonObject1.getString("pic");
String quan_guid_content = jsonObject1.getString("quan_guid_content");
String quan_id = jsonObject1.getString("quan_id");
String sales = jsonObject1.getString("sales");
String goods_name = jsonObject1.getString("goods_name");
map.put("goods_id",goods_id);
map.put("price",price);
map.put("sales",sales);
map.put("price_after_coupons",price_after_coupons);
map.put("price_coupons",price_coupons);
map.put("pic",pic);
map.put("quan_guid_content",quan_guid_content);
map.put("quan_id",quan_id);
map.put("goods_name",goods_name);
DanArrayListds.add(map);
}else {
map.put("21313","为空");
DanArrayListds.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return DanArrayListds;
}
/**
* PID的获取
*/
private void getYaoqingM(final String name, final AlertDialog alertDialog) {
hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
HttpMethods.BASE_URL = "http://www.aiboyy.pw/";
HttpMethods.getInstance().getPid(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
alertDialog.dismiss();
hud.dismiss();
Iben.YURL = (String) SharedPreferenceUtil.get(getActivity(),"pid","0");
Iben.QQ = (String) SharedPreferenceUtil.get(getActivity(),"qq","123");
//SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
}
@Override
public void onNext(String s) {
hud.dismiss();
try {
JSONArray jsonObject2 = new JSONArray(s);
JSONObject jsonObject = jsonObject2.getJSONObject(0);
if(!jsonObject.getString("name").equals("110") && !jsonObject.getString("cate_id").equals("110")){
alertDialog.dismiss();
Iben.YURL = jsonObject.getString("name");
Iben.QQ = jsonObject.getString("cate_id");
SharedPreferenceUtil.put(getActivity(),"pid",Iben.YURL);
SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
SharedPreferenceUtil.put(getActivity(),"name",name);
System.out.println("=======我获取到的PID是:"+Iben.YURL+",获取到的QQ是:"+Iben.QQ);
ToastUtils.showToastInCenter(getActivity(),2,"当日数据已更新",Toast.LENGTH_SHORT);
}else {
// getActivity().finish();
ToastUtils.showToastInCenter(getActivity(),1,"专属码错误请重新输入",Toast.LENGTH_SHORT);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},name);
}
/**
* PID的获取
*/
private void getYaoqingM(String name) {
/* hud = KProgressHUD.create(getActivity())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("疯狂加载中")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();*/
HttpMethods.BASE_URL = "http://www.aiboyy.pw/";
HttpMethods.getInstance().getPid(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
// hud.dismiss();
Iben.YURL = (String) SharedPreferenceUtil.get(getActivity(),"pid","0");
Iben.QQ = (String) SharedPreferenceUtil.get(getActivity(),"qq","123");
//SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
}
@Override
public void onNext(String s) {
// hud.dismiss();
try {
JSONArray jsonObject2 = new JSONArray(s);
JSONObject jsonObject = jsonObject2.getJSONObject(0);
if(!jsonObject.getString("name").equals("110") && !jsonObject.getString("cate_id").equals("110")){
Iben.YURL = jsonObject.getString("name");
Iben.QQ = jsonObject.getString("cate_id");
SharedPreferenceUtil.put(getActivity(),"pid",Iben.YURL);
SharedPreferenceUtil.put(getActivity(),"qq",Iben.QQ);
System.out.println("=======我获取到的PID是:"+Iben.YURL+",获取到的QQ是:"+Iben.QQ);
ToastUtils.showToastInCenter(getActivity(),2,"当日数据已更新",Toast.LENGTH_SHORT);
}else {
// getActivity().finish();
ToastUtils.showToastInCenter(getActivity(),1,"请重新输入",Toast.LENGTH_SHORT);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},name);
}
/**
* 弹出布局
*/
private void Diods(){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(false);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_share,null);
Button bt = (Button) view.findViewById(R.id.dialog_btn_pay);
final EditText editName = (EditText) view.findViewById(R.id.et_registerPhone);
builder.setView(view);
adDialog = builder.create();
adDialog.show();
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Name = editName.getText().toString();
if(!Name.equals("") && Name.trim().length() != 0 ){
getYaoqingM(Name,adDialog);
}else {
Toast.makeText(getActivity(), "请输入内容在点击,谢谢", Toast.LENGTH_SHORT).show();
}
}
});
}
} | 1 | 6 | 1 |
29822_3 | package com.ab.http;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* © 2012 amsoft.cn
* 名称:EasyX509TrustManager.java
* 描述:SSL自签名的实现类
*
* @author 还如一梦中
* @version v1.0
* @date:2013-11-13 上午9:00:52
*/
public class EasyX509TrustManager implements X509TrustManager {
private X509TrustManager standardTrustManager = null;
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager(KeyStore keystore)
throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* 执行客户端的安全策略
*/
@Override
public void checkClientTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
standardTrustManager.checkClientTrusted(certificates, authType);
}
/**
* 执行服务器的安全策略
* 检查签名、信任链中证书的有效日期和CRLs
* 清除因证书过期出现的问题
*/
@Override
public void checkServerTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
// Clean up the certificates chain and build a new one.
// Theoretically, we shouldn't have to do this, but various web servers
// in practice are mis-configured to have out-of-order certificates or
// expired self-issued root certificate.
// int chainLength = certificates.length;
if (certificates.length > 1) {
// 1. we clean the received certificates chain.
// We start from the end-entity certificate, tracing down by
// matching
// the "issuer" field and "subject" field until we can't continue.
// This helps when the certificates are out of order or
// some certificates are not related to the site.
int currIndex;
for (currIndex = 0; currIndex < certificates.length; ++currIndex) {
boolean foundNext = false;
for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) {
if (certificates[currIndex].getIssuerDN().equals(
certificates[nextIndex].getSubjectDN())) {
foundNext = true;
// Exchange certificates so that 0 through currIndex + 1
// are in proper order
if (nextIndex != currIndex + 1) {
X509Certificate tempCertificate = certificates[nextIndex];
certificates[nextIndex] = certificates[currIndex + 1];
certificates[currIndex + 1] = tempCertificate;
}
break;
}
}
if (!foundNext)
break;
}
// 2. we exam if the last traced certificate is self issued and it
// is expired.
// If so, we drop it and pass the rest to checkServerTrusted(),
// hoping we might
// have a similar but unexpired trusted root.
int chainLength = currIndex + 1;
X509Certificate lastCertificate = certificates[chainLength - 1];
Date now = new Date();
if (lastCertificate.getSubjectDN().equals(
lastCertificate.getIssuerDN())
&& now.after(lastCertificate.getNotAfter())) {
--chainLength;
}
}
// standardTrustManager.checkServerTrusted(certificates, authType);
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return this.standardTrustManager.getAcceptedIssuers();
}
} | CraftsmenTech/AndBase | AndBase/src/com/ab/http/EasyX509TrustManager.java | 1,096 | /**
* 执行服务器的安全策略
* 检查签名、信任链中证书的有效日期和CRLs
* 清除因证书过期出现的问题
*/ | block_comment | zh-cn | package com.ab.http;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* © 2012 amsoft.cn
* 名称:EasyX509TrustManager.java
* 描述:SSL自签名的实现类
*
* @author 还如一梦中
* @version v1.0
* @date:2013-11-13 上午9:00:52
*/
public class EasyX509TrustManager implements X509TrustManager {
private X509TrustManager standardTrustManager = null;
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager(KeyStore keystore)
throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* 执行客户端的安全策略
*/
@Override
public void checkClientTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
standardTrustManager.checkClientTrusted(certificates, authType);
}
/**
* 执行服 <SUF>*/
@Override
public void checkServerTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
// Clean up the certificates chain and build a new one.
// Theoretically, we shouldn't have to do this, but various web servers
// in practice are mis-configured to have out-of-order certificates or
// expired self-issued root certificate.
// int chainLength = certificates.length;
if (certificates.length > 1) {
// 1. we clean the received certificates chain.
// We start from the end-entity certificate, tracing down by
// matching
// the "issuer" field and "subject" field until we can't continue.
// This helps when the certificates are out of order or
// some certificates are not related to the site.
int currIndex;
for (currIndex = 0; currIndex < certificates.length; ++currIndex) {
boolean foundNext = false;
for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) {
if (certificates[currIndex].getIssuerDN().equals(
certificates[nextIndex].getSubjectDN())) {
foundNext = true;
// Exchange certificates so that 0 through currIndex + 1
// are in proper order
if (nextIndex != currIndex + 1) {
X509Certificate tempCertificate = certificates[nextIndex];
certificates[nextIndex] = certificates[currIndex + 1];
certificates[currIndex + 1] = tempCertificate;
}
break;
}
}
if (!foundNext)
break;
}
// 2. we exam if the last traced certificate is self issued and it
// is expired.
// If so, we drop it and pass the rest to checkServerTrusted(),
// hoping we might
// have a similar but unexpired trusted root.
int chainLength = currIndex + 1;
X509Certificate lastCertificate = certificates[chainLength - 1];
Date now = new Date();
if (lastCertificate.getSubjectDN().equals(
lastCertificate.getIssuerDN())
&& now.after(lastCertificate.getNotAfter())) {
--chainLength;
}
}
// standardTrustManager.checkServerTrusted(certificates, authType);
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return this.standardTrustManager.getAcceptedIssuers();
}
} | 1 | 66 | 1 |
42246_2 | package com.orong.activity;
import org.json.JSONException;
import org.json.JSONObject;
import com.orong.Constant;
import com.orong.R;
import com.orong.entity.HttpDatas;
import com.orong.utils.net.NetUtils;
import com.orong.utils.net.HttpAsyncTask.TaskCallBack;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TelUsActivity extends BaseActivity {
private TextView tvTelephone;// 客服电话
private ImageView ivCallService;// 呼叫客服
private EditText etOpinion;// 意见信息
private Button btSubmit;// 确认提交
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tel_us);
initivReabck(this);
setTitle(this, R.string.aboutus);
tvTelephone = (TextView) this.findViewById(R.id.tv_telephone);
ivCallService = (ImageView) this.findViewById(R.id.iv_call_service);
ivCallService.setOnClickListener(this);
etOpinion = (EditText) this.findViewById(R.id.et_opinion);
etOpinion.addTextChangedListener(new SuggestTextWatcher());
btSubmit = (Button) this.findViewById(R.id.bt_submit);
btSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_call_service:
callPhone();
break;
case R.id.bt_submit:
submintOpinion();
break;
default:
super.onClick(v);
break;
}
}
/**
* 启动打电话功能
*/
private void callPhone() {
String phone = tvTelephone.getText().toString();
Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone));
startActivity(intent);
}
private void submintOpinion() {
String opinion = etOpinion.getText().toString().trim();
if ("".equals(opinion)) {
Toast.makeText(this, "意见不能为空", 0).show();
return;
}
if (opinion.length() < 5) {
Toast.makeText(this, getString(R.string.text_less_than_5), 0).show();
return;
}
if (opinion.length() > 100) {
Toast.makeText(this, getString(R.string.text_more_than_100), 0).show();
return;
}
HttpDatas datas = new HttpDatas(Constant.USERAPI);
datas.putParam("method", "ContactUs");
datas.putParam("reason", opinion);
NetUtils.sendRequest(datas, this, getString(R.string.uploading_message), new TaskCallBack() {
@Override
public int excueHttpResponse(String respondsStr) {
int code = 0;
try {
JSONObject jsonObject = new JSONObject(respondsStr);
code = jsonObject.getInt("code");
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
@Override
public void beforeTask() {
}
@Override
public void afterTask(int result) {
switch (result) {
case Constant.RESPONSE_OK:
Toast.makeText(getApplicationContext(), getString(R.string.thanks_for_opinion), 0).show();
break;
case 3009:
Toast.makeText(getApplicationContext(), getString(R.string.was_resummit), 0).show();
break;
default:
showResulttoast(result, TelUsActivity.this);
break;
}
}
});
}
class SuggestTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int length = s.length();
if (length > 100) {
s.delete(length - 1, length);
length--;
Toast.makeText(getApplicationContext(), "字数超限", 0).show();
return;
}
}
}
}
| CraftsmenTech/jurongwang | src/com/orong/activity/TelUsActivity.java | 1,211 | // 意见信息
| line_comment | zh-cn | package com.orong.activity;
import org.json.JSONException;
import org.json.JSONObject;
import com.orong.Constant;
import com.orong.R;
import com.orong.entity.HttpDatas;
import com.orong.utils.net.NetUtils;
import com.orong.utils.net.HttpAsyncTask.TaskCallBack;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TelUsActivity extends BaseActivity {
private TextView tvTelephone;// 客服电话
private ImageView ivCallService;// 呼叫客服
private EditText etOpinion;// 意见 <SUF>
private Button btSubmit;// 确认提交
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tel_us);
initivReabck(this);
setTitle(this, R.string.aboutus);
tvTelephone = (TextView) this.findViewById(R.id.tv_telephone);
ivCallService = (ImageView) this.findViewById(R.id.iv_call_service);
ivCallService.setOnClickListener(this);
etOpinion = (EditText) this.findViewById(R.id.et_opinion);
etOpinion.addTextChangedListener(new SuggestTextWatcher());
btSubmit = (Button) this.findViewById(R.id.bt_submit);
btSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_call_service:
callPhone();
break;
case R.id.bt_submit:
submintOpinion();
break;
default:
super.onClick(v);
break;
}
}
/**
* 启动打电话功能
*/
private void callPhone() {
String phone = tvTelephone.getText().toString();
Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone));
startActivity(intent);
}
private void submintOpinion() {
String opinion = etOpinion.getText().toString().trim();
if ("".equals(opinion)) {
Toast.makeText(this, "意见不能为空", 0).show();
return;
}
if (opinion.length() < 5) {
Toast.makeText(this, getString(R.string.text_less_than_5), 0).show();
return;
}
if (opinion.length() > 100) {
Toast.makeText(this, getString(R.string.text_more_than_100), 0).show();
return;
}
HttpDatas datas = new HttpDatas(Constant.USERAPI);
datas.putParam("method", "ContactUs");
datas.putParam("reason", opinion);
NetUtils.sendRequest(datas, this, getString(R.string.uploading_message), new TaskCallBack() {
@Override
public int excueHttpResponse(String respondsStr) {
int code = 0;
try {
JSONObject jsonObject = new JSONObject(respondsStr);
code = jsonObject.getInt("code");
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
@Override
public void beforeTask() {
}
@Override
public void afterTask(int result) {
switch (result) {
case Constant.RESPONSE_OK:
Toast.makeText(getApplicationContext(), getString(R.string.thanks_for_opinion), 0).show();
break;
case 3009:
Toast.makeText(getApplicationContext(), getString(R.string.was_resummit), 0).show();
break;
default:
showResulttoast(result, TelUsActivity.this);
break;
}
}
});
}
class SuggestTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int length = s.length();
if (length > 100) {
s.delete(length - 1, length);
length--;
Toast.makeText(getApplicationContext(), "字数超限", 0).show();
return;
}
}
}
}
| 1 | 8 | 1 |
34722_11 | package ai.zhuanzhi.dl4j.rbm4j;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.transforms.Transforms;
/**
* @author hu
* 该教程由专知(www.zhuanzhi.ai)提供
*/
public class RBM {
protected INDArray w, b, a;
public RBM(int vDim, int hDim){
w = Nd4j.rand(vDim, hDim);
b = Nd4j.rand(new int[]{hDim});
a = Nd4j.rand(new int[]{vDim});
}
//输入可见层v,输出隐藏层为1的概率p(h|v)
protected INDArray computeHProbs(INDArray vSamples){
INDArray hProbs = vSamples.mmul(w).addRowVector(b);
hProbs = Transforms.sigmoid(hProbs);
return hProbs;
}
//输入隐藏层h,输出可见层为1的概率p(v|h)
protected INDArray computeVProbs(INDArray hSamples){
INDArray vProbs = hSamples.mmul(w.transpose()).addRowVector(a);
vProbs = Transforms.sigmoid(vProbs);
return vProbs;
}
//输入可见层,输出RBM重构的结果
public INDArray reconstruct(INDArray vSamples){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
return negVSamples;
}
public double fit(INDArray vSamples, double learningRate){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
INDArray negHProbs = computeHProbs(negVSamples);
INDArray mseTempMatrix = negVSamples.sub(vSamples);
double loss = mseTempMatrix.mul(mseTempMatrix).div(2).mean(0,1).getDouble(0,0);
//正梯度
INDArray posGrad = vSamples.transpose().mmul(hProbs);
//负梯度
INDArray negGrad = negVSamples.transpose().mmul(negHProbs);
//输入样本数量
int numSamples = vSamples.shape()[0];
//计算并更新参数
INDArray dw = posGrad.sub(negGrad).mul(learningRate/numSamples);
INDArray db = hProbs.mean(0).sub(negHProbs.mean(0)).mul(learningRate);
INDArray da = vSamples.mean(0).sub(negVSamples.mean(0)).mul(learningRate);
w.addi(dw);
b.addi(db);
a.addi(da);
return loss;
}
//伯努利采样
protected INDArray bernoulliSample(INDArray probs){
INDArray randArray = Nd4j.rand(probs.shape());
INDArray samples = probs.gt(randArray);
return samples;
}
public static void main(String[] args) {
//手工设置一组数据
double[][] rawVSamples = new double[][]{
{1,1,1,1,0,0,0,0},
{1,1,1,1,0,0,0,0},
{0,0,1,1,1,1,0,0},
{0,0,1,1,1,1,0,0},
{0,0,0,0,1,1,1,1},
{0,0,0,0,1,1,1,1}
};
INDArray vSamples = Nd4j.create(rawVSamples);
//设置RBM(隐藏层大小为2)
RBM rbm = new RBM(vSamples.shape()[1],2);
//训练
for(int i=0;i<20000;i++){
double loss = rbm.fit(vSamples,5e-3);
if(i % 1000 == 0){
System.out.println("batch:"+i+"\tloss:" + loss);
}
}
//显示重构结果
System.out.println("reconstruction:");
System.out.println(rbm.reconstruct(vSamples));
//显示对应的隐藏层激活值(学习到的特征)
System.out.println("features:");
System.out.println(rbm.computeHProbs(vSamples));
}
}
| CrawlScript/RBM4j | src/main/java/ai/zhuanzhi/dl4j/rbm4j/RBM.java | 1,123 | //显示重构结果 | line_comment | zh-cn | package ai.zhuanzhi.dl4j.rbm4j;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.transforms.Transforms;
/**
* @author hu
* 该教程由专知(www.zhuanzhi.ai)提供
*/
public class RBM {
protected INDArray w, b, a;
public RBM(int vDim, int hDim){
w = Nd4j.rand(vDim, hDim);
b = Nd4j.rand(new int[]{hDim});
a = Nd4j.rand(new int[]{vDim});
}
//输入可见层v,输出隐藏层为1的概率p(h|v)
protected INDArray computeHProbs(INDArray vSamples){
INDArray hProbs = vSamples.mmul(w).addRowVector(b);
hProbs = Transforms.sigmoid(hProbs);
return hProbs;
}
//输入隐藏层h,输出可见层为1的概率p(v|h)
protected INDArray computeVProbs(INDArray hSamples){
INDArray vProbs = hSamples.mmul(w.transpose()).addRowVector(a);
vProbs = Transforms.sigmoid(vProbs);
return vProbs;
}
//输入可见层,输出RBM重构的结果
public INDArray reconstruct(INDArray vSamples){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
return negVSamples;
}
public double fit(INDArray vSamples, double learningRate){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
INDArray negHProbs = computeHProbs(negVSamples);
INDArray mseTempMatrix = negVSamples.sub(vSamples);
double loss = mseTempMatrix.mul(mseTempMatrix).div(2).mean(0,1).getDouble(0,0);
//正梯度
INDArray posGrad = vSamples.transpose().mmul(hProbs);
//负梯度
INDArray negGrad = negVSamples.transpose().mmul(negHProbs);
//输入样本数量
int numSamples = vSamples.shape()[0];
//计算并更新参数
INDArray dw = posGrad.sub(negGrad).mul(learningRate/numSamples);
INDArray db = hProbs.mean(0).sub(negHProbs.mean(0)).mul(learningRate);
INDArray da = vSamples.mean(0).sub(negVSamples.mean(0)).mul(learningRate);
w.addi(dw);
b.addi(db);
a.addi(da);
return loss;
}
//伯努利采样
protected INDArray bernoulliSample(INDArray probs){
INDArray randArray = Nd4j.rand(probs.shape());
INDArray samples = probs.gt(randArray);
return samples;
}
public static void main(String[] args) {
//手工设置一组数据
double[][] rawVSamples = new double[][]{
{1,1,1,1,0,0,0,0},
{1,1,1,1,0,0,0,0},
{0,0,1,1,1,1,0,0},
{0,0,1,1,1,1,0,0},
{0,0,0,0,1,1,1,1},
{0,0,0,0,1,1,1,1}
};
INDArray vSamples = Nd4j.create(rawVSamples);
//设置RBM(隐藏层大小为2)
RBM rbm = new RBM(vSamples.shape()[1],2);
//训练
for(int i=0;i<20000;i++){
double loss = rbm.fit(vSamples,5e-3);
if(i % 1000 == 0){
System.out.println("batch:"+i+"\tloss:" + loss);
}
}
//显示 <SUF>
System.out.println("reconstruction:");
System.out.println(rbm.reconstruct(vSamples));
//显示对应的隐藏层激活值(学习到的特征)
System.out.println("features:");
System.out.println(rbm.computeHProbs(vSamples));
}
}
| 1 | 8 | 1 |
12926_9 | /*
* Copyright (C) 2015 hu
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package cn.edu.hfut.dmic.webcollector.example;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatum;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatums;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.plugin.ram.RamCrawler;
/**
* WebCollector 2.x版本的tutorial(2.20以上)
* 2.x版本特性:
* 1)自定义遍历策略,可完成更为复杂的遍历业务,例如分页、AJAX
* 2)可以为每个URL设置附加信息(MetaData),利用附加信息可以完成很多复杂业务,例如深度获取、锚文本获取、引用页面获取、POST参数传递、增量更新等。
* 3)使用插件机制,WebCollector内置两套插件。
* 4)内置一套基于内存的插件(RamCrawler),不依赖文件系统或数据库,适合一次性爬取,例如实时爬取搜索引擎。
* 5)内置一套基于Berkeley DB(BreadthCrawler)的插件:适合处理长期和大量级的任务,并具有断点爬取功能,不会因为宕机、关闭导致数据丢失。
* 6)集成selenium,可以对javascript生成信息进行抽取
* 7)可轻松自定义http请求,并内置多代理随机切换功能。 可通过定义http请求实现模拟登录。
* 8)使用slf4j作为日志门面,可对接多种日志
*
* 可在cn.edu.hfut.dmic.webcollector.example包中找到例子(Demo)
*
* @author hu
*/
public class DemoMetaCrawler extends RamCrawler {
/*
实际使用时建议按照DemoTypeCrawler的方式操作,该教程目的为阐述meta的原理
可以往next中添加希望后续爬取的任务,任务可以是URL或者CrawlDatum
爬虫不会重复爬取任务,从2.20版之后,爬虫根据CrawlDatum的key去重,而不是URL
因此如果希望重复爬取某个URL,只要将CrawlDatum的key设置为一个历史中不存在的值即可
例如增量爬取,可以使用 爬取时间+URL作为key。
新版本中,可以直接通过 page.select(css选择器)方法来抽取网页中的信息,等价于
page.getDoc().select(css选择器)方法,page.getDoc()获取到的是Jsoup中的
Document对象,细节请参考Jsoup教程
该Demo爬虫需要应对豆瓣图书的三种页面:
1)标签页(taglist,包含图书列表页的入口链接)
2)列表页(booklist,包含图书详情页的入口链接)
3)图书详情页(content)
*/
@Override
public void visit(Page page, CrawlDatums next) {
String type=page.meta("type");
//如果是列表页,抽取内容页链接,放入后续任务中
if(type.equals("taglist")){
//可以确定抽取到的链接都指向内容页
//因此为这些链接添加附加信息(meta):type=content
next.addAndReturn(page.links("table.tagCol td>a")).meta("type", "booklist");
}else if(type.equals("booklist")){
next.addAndReturn(page.links("div.info>h2>a")).meta("type", "content");
}else if(type.equals("content")){
//处理内容页,抽取书名和豆瓣评分
String title=page.select("h1>span").first().text();
String score=page.select("strong.ll.rating_num").first().text();
System.out.println("title:"+title+"\tscore:"+score);
}
}
public static void main(String[] args) throws Exception {
DemoMetaCrawler crawler = new DemoMetaCrawler();
//meta是CrawlDatum的附加信息,爬虫内核并不使用meta信息
//在解析页面时,往往需要知道当前页面的类型(例如是列表页还是内容页)或一些附加信息(例如页号)
//然而根据当前页面的信息(内容和URL)并不一定能够轻易得到这些信息
//例如当在解析页面 https://book.douban.com/tag/ 时,需要知道该页是目录页还是内容页
//虽然用正则可以解决这个问题,但是较为麻烦
//当我们将一个新链接(CrawlDatum)提交给爬虫时,链接指向页面的类型有时是确定的(例如在很多任务中,种子页面就是列表页)
//如果在提交CrawlDatum时,直接将链接的类型信息(type)存放到meta中,那么在解析页面时,
//只需取出链接(CrawlDatum)中的类型信息(type)即可知道当前页面类型
CrawlDatum seed=new CrawlDatum("https://book.douban.com/tag/").meta("type", "taglist");
crawler.addSeed(seed);
/*可以设置每个线程visit的间隔,这里是毫秒*/
//crawler.setVisitInterval(1000);
/*可以设置http请求重试的间隔,这里是毫秒*/
//crawler.setRetryInterval(1000);
crawler.setThreads(30);
crawler.start(3);
}
} | CrawlScript/WebCollector | src/main/java/cn/edu/hfut/dmic/webcollector/example/DemoMetaCrawler.java | 1,513 | //然而根据当前页面的信息(内容和URL)并不一定能够轻易得到这些信息 | line_comment | zh-cn | /*
* Copyright (C) 2015 hu
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package cn.edu.hfut.dmic.webcollector.example;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatum;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatums;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.plugin.ram.RamCrawler;
/**
* WebCollector 2.x版本的tutorial(2.20以上)
* 2.x版本特性:
* 1)自定义遍历策略,可完成更为复杂的遍历业务,例如分页、AJAX
* 2)可以为每个URL设置附加信息(MetaData),利用附加信息可以完成很多复杂业务,例如深度获取、锚文本获取、引用页面获取、POST参数传递、增量更新等。
* 3)使用插件机制,WebCollector内置两套插件。
* 4)内置一套基于内存的插件(RamCrawler),不依赖文件系统或数据库,适合一次性爬取,例如实时爬取搜索引擎。
* 5)内置一套基于Berkeley DB(BreadthCrawler)的插件:适合处理长期和大量级的任务,并具有断点爬取功能,不会因为宕机、关闭导致数据丢失。
* 6)集成selenium,可以对javascript生成信息进行抽取
* 7)可轻松自定义http请求,并内置多代理随机切换功能。 可通过定义http请求实现模拟登录。
* 8)使用slf4j作为日志门面,可对接多种日志
*
* 可在cn.edu.hfut.dmic.webcollector.example包中找到例子(Demo)
*
* @author hu
*/
public class DemoMetaCrawler extends RamCrawler {
/*
实际使用时建议按照DemoTypeCrawler的方式操作,该教程目的为阐述meta的原理
可以往next中添加希望后续爬取的任务,任务可以是URL或者CrawlDatum
爬虫不会重复爬取任务,从2.20版之后,爬虫根据CrawlDatum的key去重,而不是URL
因此如果希望重复爬取某个URL,只要将CrawlDatum的key设置为一个历史中不存在的值即可
例如增量爬取,可以使用 爬取时间+URL作为key。
新版本中,可以直接通过 page.select(css选择器)方法来抽取网页中的信息,等价于
page.getDoc().select(css选择器)方法,page.getDoc()获取到的是Jsoup中的
Document对象,细节请参考Jsoup教程
该Demo爬虫需要应对豆瓣图书的三种页面:
1)标签页(taglist,包含图书列表页的入口链接)
2)列表页(booklist,包含图书详情页的入口链接)
3)图书详情页(content)
*/
@Override
public void visit(Page page, CrawlDatums next) {
String type=page.meta("type");
//如果是列表页,抽取内容页链接,放入后续任务中
if(type.equals("taglist")){
//可以确定抽取到的链接都指向内容页
//因此为这些链接添加附加信息(meta):type=content
next.addAndReturn(page.links("table.tagCol td>a")).meta("type", "booklist");
}else if(type.equals("booklist")){
next.addAndReturn(page.links("div.info>h2>a")).meta("type", "content");
}else if(type.equals("content")){
//处理内容页,抽取书名和豆瓣评分
String title=page.select("h1>span").first().text();
String score=page.select("strong.ll.rating_num").first().text();
System.out.println("title:"+title+"\tscore:"+score);
}
}
public static void main(String[] args) throws Exception {
DemoMetaCrawler crawler = new DemoMetaCrawler();
//meta是CrawlDatum的附加信息,爬虫内核并不使用meta信息
//在解析页面时,往往需要知道当前页面的类型(例如是列表页还是内容页)或一些附加信息(例如页号)
//然而 <SUF>
//例如当在解析页面 https://book.douban.com/tag/ 时,需要知道该页是目录页还是内容页
//虽然用正则可以解决这个问题,但是较为麻烦
//当我们将一个新链接(CrawlDatum)提交给爬虫时,链接指向页面的类型有时是确定的(例如在很多任务中,种子页面就是列表页)
//如果在提交CrawlDatum时,直接将链接的类型信息(type)存放到meta中,那么在解析页面时,
//只需取出链接(CrawlDatum)中的类型信息(type)即可知道当前页面类型
CrawlDatum seed=new CrawlDatum("https://book.douban.com/tag/").meta("type", "taglist");
crawler.addSeed(seed);
/*可以设置每个线程visit的间隔,这里是毫秒*/
//crawler.setVisitInterval(1000);
/*可以设置http请求重试的间隔,这里是毫秒*/
//crawler.setRetryInterval(1000);
crawler.setThreads(30);
crawler.start(3);
}
} | 0 | 35 | 0 |
60032_8 | package com.ynyes.lyz.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 调色包实体类
*
* @author dengxiao
*/
@Entity
public class TdColorPackage {
// id
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// 调色包名称
@Column
private String name;
// 调色包编号
@Column
private String number;
// 调色包图片
@Column
private String imageUri;
// 库存
@Column
private Long inventory;
// 当前销售价格
@Column(scale = 2)
private Double salePrice;
// 当前进货价格
@Column(scale = 2)
private Double stockPrice;
// 购买数量
@Column
private Long quantity;
//总价
@Column
private Double totalPrice;
// 归属: 1 华润商品 2 乐意装商品
@Column
private Long belongTo;
// 排序号
@Column
private Double sortId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
public Long getInventory() {
return inventory;
}
public void setInventory(Long inventory) {
this.inventory = inventory;
}
public Double getSalePrice() {
return salePrice;
}
public void setSalePrice(Double salePrice) {
this.salePrice = salePrice;
}
public Double getStockPrice() {
return stockPrice;
}
public void setStockPrice(Double stockPrice) {
this.stockPrice = stockPrice;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Long getBelongTo() {
return belongTo;
}
public void setBelongTo(Long belongTo) {
this.belongTo = belongTo;
}
public Double getSortId() {
return sortId;
}
public void setSortId(Double sortId) {
this.sortId = sortId;
}
}
| CrazyApeDX/leyizhuang2.0-manager | src/main/java/com/ynyes/lyz/entity/TdColorPackage.java | 768 | // 排序号 | line_comment | zh-cn | package com.ynyes.lyz.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 调色包实体类
*
* @author dengxiao
*/
@Entity
public class TdColorPackage {
// id
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// 调色包名称
@Column
private String name;
// 调色包编号
@Column
private String number;
// 调色包图片
@Column
private String imageUri;
// 库存
@Column
private Long inventory;
// 当前销售价格
@Column(scale = 2)
private Double salePrice;
// 当前进货价格
@Column(scale = 2)
private Double stockPrice;
// 购买数量
@Column
private Long quantity;
//总价
@Column
private Double totalPrice;
// 归属: 1 华润商品 2 乐意装商品
@Column
private Long belongTo;
// 排序 <SUF>
@Column
private Double sortId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
public Long getInventory() {
return inventory;
}
public void setInventory(Long inventory) {
this.inventory = inventory;
}
public Double getSalePrice() {
return salePrice;
}
public void setSalePrice(Double salePrice) {
this.salePrice = salePrice;
}
public Double getStockPrice() {
return stockPrice;
}
public void setStockPrice(Double stockPrice) {
this.stockPrice = stockPrice;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Long getBelongTo() {
return belongTo;
}
public void setBelongTo(Long belongTo) {
this.belongTo = belongTo;
}
public Double getSortId() {
return sortId;
}
public void setSortId(Double sortId) {
this.sortId = sortId;
}
}
| 1 | 6 | 1 |
7780_3 | package basic.thread.state;
/**
* @description:
* @author: Feirouz
* @date: 2023-06-06 19:57
*/
public class DaemonTest {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); // 默认是false表示是用户线程,正常的线程都是用户线程
thread.start(); //上帝守护线程启动
new Thread(you).start(); // 你 用户线程启动
}
}
// 上帝
class God implements Runnable{
@Override
public void run() {
while (true) {
System.out.println("上帝保佑着你");
}
}
}
// 你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("=========再见世界===========");
}
} | CrazyFeirouz/CodeLife_Java | source/basic/thread/state/DaemonTest.java | 270 | // 你 用户线程启动 | line_comment | zh-cn | package basic.thread.state;
/**
* @description:
* @author: Feirouz
* @date: 2023-06-06 19:57
*/
public class DaemonTest {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); // 默认是false表示是用户线程,正常的线程都是用户线程
thread.start(); //上帝守护线程启动
new Thread(you).start(); // 你 <SUF>
}
}
// 上帝
class God implements Runnable{
@Override
public void run() {
while (true) {
System.out.println("上帝保佑着你");
}
}
}
// 你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("=========再见世界===========");
}
} | 0 | 11 | 0 |
58107_9 | package com.deep007.goniub.util;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Strings {
public static int alphabetNumber(String str) {
int chineseNumber = chineseNumber(str);
return str.length() - chineseNumber;
}
/**
* @param str 字符串
* @return 中文字的个数
*/
public static int chineseNumber(String str) {
int chineseNumber = 0;
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(str);
while (matcher.find()) {
chineseNumber += matcher.group().length();
}
return chineseNumber;
}
public static boolean hasChineseNumber(String str) {
return Pattern.compile("[零一二三四五六七八九十壹贰叁肆伍陆柒捌玖]").matcher(str).find();
}
public static boolean statrWithAlphabet(String text) {
if (text == null || text.isEmpty()) {
return false;
}
String first = text.substring(0, 1);
return Pattern.compile("[0-9a-zA-Z]+").matcher(first).find();
}
public static boolean endsWithAlphabet(String text) {
if (text == null || text.isEmpty()) {
return false;
}
String end = text.substring(text.length() - 1, text.length());
return Pattern.compile("[0-9a-zA-Z]+").matcher(end).find();
}
public static boolean hasAlphabet(String text) {
return Pattern.compile("[0-9a-zA-Z]+").matcher(text).find();
}
public static boolean hasSymbol(String text) {
return Pattern.compile("\\pP").matcher(text).find();
}
public static boolean isAlphabet(String text) {
return text.matches("^[0-9a-zA-Z]+$");
}
/**
* @param str 字符串
* @return unicode转中文
*/
public static String unicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
public static String getDomain(String urlOrDomain) {
String domain = null;
if (urlOrDomain.trim().startsWith("http") || urlOrDomain.contains("/")) {
java.net.URL url;
try {
url = new java.net.URL(urlOrDomain);
domain = url.getHost().toLowerCase();// 获取主机名
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
} else {
domain = urlOrDomain;
}
Matcher matcher = Pattern.compile("(\\w+.\\w+)$").matcher(domain);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
/**
* 两个大数相减,默认没有符号位,且都为正数
*
* @param a a
* @param b b
* @return 相似度
*/
public static String bigDigitalSub(String a, String b) {
// 翻转字符串并转化成数组
char[] aArray = new StringBuilder(a).reverse().toString().toCharArray();
char[] bArray = new StringBuilder(b).reverse().toString().toCharArray();
int aLength = aArray.length;
int bLength = bArray.length;
// 找到最大的位数,两个整数的差的位数小于等于两个整数中的最大位数
int maxLength = aLength > bLength ? aLength : bLength;
int[] result = new int[maxLength];
// 判断结果符号
char sign = '+';
if (aLength < bLength)
sign = '-';
else if (aLength == bLength) {
int i = maxLength - 1;
while (i > 0 && aArray[i] == bArray[i])
i--;
if (aArray[i] < bArray[i])
sign = '-';
}
// 开始计算结果集
for (int i = 0; i < maxLength; i++) {
int aInt = i < aLength ? aArray[i] - '0' : 0;
int bInt = i < bLength ? bArray[i] - '0' : 0;
if (sign == '-')
result[i] = bInt - aInt;
else
result[i] = aInt - bInt;
}
// 处理结果集,如果结果集中的某一位小于0,则向高位借位,然后将本位加10
for (int i = 0; i < maxLength - 1; i++) {
if (result[i] < 0) {
result[i + 1] -= 1;
result[i] += 10;
}
}
// 处理结果集,转化成真正结果
StringBuffer realResult = new StringBuffer();
if (sign == '-')
realResult.append('-');
boolean isBeginning = true;
for (int i = maxLength - 1; i >= 0; i--) {
if (result[i] == 0 && isBeginning)
continue;
else
isBeginning = false;
realResult.append(result[i]);
}
if (realResult.toString().equals(""))
realResult.append('0');
return realResult.toString();
}
/**
* 采用动态规划的方法解决
*
* @param source source
* @param target target
* @return 字符串相似度
*/
public static int editDistance(String source, String target) {
char[] sources = source.toCharArray();
char[] targets = target.toCharArray();
int sourceLen = sources.length;
int targetLen = targets.length;
int[][] d = new int[sourceLen + 1][targetLen + 1];
for (int i = 0; i <= sourceLen; i++) {
d[i][0] = i;
}
for (int i = 0; i <= targetLen; i++) {
d[0][i] = i;
}
for (int i = 1; i <= sourceLen; i++) {
for (int j = 1; j <= targetLen; j++) {
if (sources[i - 1] == targets[j - 1]) {
d[i][j] = d[i - 1][j - 1];
} else {
// 插入
int insert = d[i][j - 1] + 1;
// 删除
int delete = d[i - 1][j] + 1;
// 替换
int replace = d[i - 1][j - 1] + 1;
d[i][j] = Math.min(insert, delete) > Math.min(delete, replace) ? Math.min(delete, replace)
: Math.min(insert, delete);
}
}
}
return d[sourceLen][targetLen];
}
public static Date formatDate(String str, String format) {
if (format == null || format.isEmpty()) {
return null;
}
try {
return new SimpleDateFormat(format).parse(str);
} catch (ParseException e) {
}
return null;
}
public static String getMD5(String inStr) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bs = md5.digest(inStr.getBytes());
StringBuilder sb = new StringBuilder(40);
for (byte x : bs) {
if ((x & 0xff) >> 4 == 0) {
sb.append("0").append(Integer.toHexString(x & 0xff));
} else {
sb.append(Integer.toHexString(x & 0xff));
}
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return inStr;
}
}
public static boolean hasChinese(String str) {
return Pattern.compile("[\\u4e00-\\u9fa5]").matcher(str).find();
}
public static boolean isChinese(String str) {
return str.matches("[\\u4e00-\\u9fa5]+");
}
public static boolean hasNumber(String str) {
return Pattern.compile("\\d+").matcher(str).find();
}
public static boolean hasLetter(String str) {
return Pattern.compile("[a-zA-Z]+").matcher(str).find();
}
public static boolean hasNocrediteNumber(String text) {
// (2018)苏0205民初6040号
Pattern pattern = Pattern
.compile("[\\((][\\d]{4}[)\\)][\\u4e00-\\u9fa5]{1,3}[\\d]{4,5}[\\u4e00-\\u9fa5]{1,3}[\\d]{4,5}号");
return pattern.matcher(text).find();
}
public static String getPersonName(String name) throws Exception {
if (!isValidString(name)) {
throw new Exception("字符串无效:" + name);
}
if (name.contains("*")) {
throw new Exception("名字不能有*:" + name);
}
StringBuilder sb = new StringBuilder();
Matcher matcher = Pattern.compile("[\u4e00-\u9fa5a-zA-Z]").matcher(name);
while (matcher.find()) {
sb.append(matcher.group());
}
return sb.toString();
}
public static String filterNoNumber(String number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < number.length(); i++) {
if (number.charAt(i) == '*' || (number.charAt(i) >= '0' && number.charAt(i) <= '9')) {
sb.append(number.charAt(i));
}
}
return sb.toString();
}
public static String getNumber(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
return filterNoNumber(number);
}
public static String getCardIdNumber(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
Matcher matcher = Pattern.compile("\\d[\\d*a-zA-Z]{17}").matcher(number);
if (matcher.find()) {
return matcher.group(0);
}
throw new Exception("找不到身份证号:" + number);
}
public static String getTelephoneNumber(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
number = filterNoNumber(number);
if (number.startsWith("+86")) {
number = number.substring(3);
} else if (number.startsWith("86")) {
number = number.substring(2);
}
Matcher matcher = Pattern.compile("[\\d*\\-]{7,13}").matcher(number);
if (matcher.find()) {
number = matcher.group(0);
if (number.length() > 11) {
return number.substring(number.length() - 11);
}
return number;
}
throw new Exception("找不到手机号:" + number);
}
public static String getTelephoneNumberNoStar(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
number = filterNoNumber(number);
if (number.startsWith("+86")) {
number = number.substring(3);
} else if (number.startsWith("86")) {
number = number.substring(2);
}
Matcher matcher = Pattern.compile("[\\d]{7,11}").matcher(number);
if (matcher.find()) {
number = matcher.group(0);
if (number.length() > 11) {
return number.substring(number.length() - 11);
}
return number;
}
throw new Exception("找不到手机号:" + number);
}
public static String mergeText(String a, String b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
if (!isSameText(a, b)) {
return a;
}
String n = "";
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != '*') {
n += a.charAt(i);
} else if (b.length() > i) {
n += b.charAt(i);
}
}
return n;
}
public static boolean isSameText(String cardIdA, String cardIdB) {
if (cardIdA != null && cardIdB != null && cardIdA.length() == cardIdB.length()) {
for (int i = 0; i < cardIdA.length(); i++) {
if (cardIdA.charAt(i) == '*' || cardIdB.charAt(i) == '*') {
continue;
}
if (cardIdA.charAt(i) != cardIdB.charAt(i)) {
return false;
}
}
}
return true;
}
/**
* @param str str
* @return starts ends of array
*/
public static String[] extractDesensitizationInfo(String str) {
String[] result = new String[2];
if (!str.startsWith("*")) {
String temp = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != '*') {
temp += ch;
} else {
result[0] = temp;
break;
}
if (temp.length() >= 5) {
result[0] = temp;
break;
}
}
}
if (!str.endsWith("*")) {
String temp = "";
int i = str.length() - 1;
for (; i < str.length(); i--) {
char ch = str.charAt(i);
if (ch != '*') {
temp = ch + temp;
} else {
result[1] = temp;
break;
}
if (temp.length() >= 5) {
result[1] = temp;
break;
}
}
}
return result;
}
public static boolean isValidString(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
return !str.contains("正在加载..");
}
public static boolean isValidTelephone(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
Matcher matcher = Pattern.compile("[\u4e00-\u9fa5]").matcher(str);
return !matcher.find();
}
public static boolean isSamePrefix(String a, String b, int num) {
for (int i = 0; i < num; i++) {
if (a.charAt(i) != b.charAt(i)) {
return false;
}
}
return true;
}
/**
* 区县名字简易化
*
* @param district addr text
* @return simple name
*/
public static String district2SimpleText(String district) {
if (district.endsWith("市") || district.endsWith("区")) {
return district.substring(0, district.length() - 1);
}
return district;
}
/**
* 乡镇名字简易化
*
* @param village addr text
* @return simple name
*/
public static String village2SimpleText(String village) {
if (village.endsWith("镇") || village.endsWith("乡") || village.endsWith("村") || village.endsWith("组")) {
return village.substring(0, village.length() - 1);
}
if (village.endsWith("街道") || village.endsWith("集团") || village.endsWith("林场") || village.endsWith("大队")
|| village.endsWith("基地")) {
return village.substring(0, village.length() - 2);
}
return village;
}
/**
* 公司名字简易化
*
* @param companyName name
* @return simple name
*/
public static String companyName2SimpleText(String companyName) {
if (companyName.contains("有限公司")) {
companyName = companyName.substring(0, companyName.indexOf("有限公司") - 2);
}
if (companyName.contains("有限责任公司")) {
companyName = companyName.substring(0, companyName.indexOf("有限责任公司") - 2);
}
return companyName;
}
/**
* 去除括号里面的
*
* @param addressText addr text
* @return no symbol name
*/
public static String removeParenthesis(String addressText) {
int startIndex = addressText.indexOf("(");
int endIndex = addressText.indexOf(")");
while (endIndex > startIndex && startIndex > 0) {
addressText = addressText.substring(0, startIndex) + addressText.substring(endIndex + 1);
addressText.indexOf("(");
endIndex = addressText.indexOf(")");
}
startIndex = addressText.indexOf("(");
endIndex = addressText.indexOf(")");
while (endIndex > startIndex && startIndex > 0) {
addressText = addressText.substring(0, startIndex) + addressText.substring(endIndex + 1);
addressText.indexOf("(");
endIndex = addressText.indexOf(")");
}
addressText = addressText.replaceAll("\\(", "").replaceAll("\\)", "");
addressText = addressText.replaceAll("(", "").replaceAll(")", "");
return addressText;
}
}
| CreditTone/goniub | src/main/java/com/deep007/goniub/util/Strings.java | 4,686 | // 处理结果集,转化成真正结果 | line_comment | zh-cn | package com.deep007.goniub.util;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Strings {
public static int alphabetNumber(String str) {
int chineseNumber = chineseNumber(str);
return str.length() - chineseNumber;
}
/**
* @param str 字符串
* @return 中文字的个数
*/
public static int chineseNumber(String str) {
int chineseNumber = 0;
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(str);
while (matcher.find()) {
chineseNumber += matcher.group().length();
}
return chineseNumber;
}
public static boolean hasChineseNumber(String str) {
return Pattern.compile("[零一二三四五六七八九十壹贰叁肆伍陆柒捌玖]").matcher(str).find();
}
public static boolean statrWithAlphabet(String text) {
if (text == null || text.isEmpty()) {
return false;
}
String first = text.substring(0, 1);
return Pattern.compile("[0-9a-zA-Z]+").matcher(first).find();
}
public static boolean endsWithAlphabet(String text) {
if (text == null || text.isEmpty()) {
return false;
}
String end = text.substring(text.length() - 1, text.length());
return Pattern.compile("[0-9a-zA-Z]+").matcher(end).find();
}
public static boolean hasAlphabet(String text) {
return Pattern.compile("[0-9a-zA-Z]+").matcher(text).find();
}
public static boolean hasSymbol(String text) {
return Pattern.compile("\\pP").matcher(text).find();
}
public static boolean isAlphabet(String text) {
return text.matches("^[0-9a-zA-Z]+$");
}
/**
* @param str 字符串
* @return unicode转中文
*/
public static String unicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
public static String getDomain(String urlOrDomain) {
String domain = null;
if (urlOrDomain.trim().startsWith("http") || urlOrDomain.contains("/")) {
java.net.URL url;
try {
url = new java.net.URL(urlOrDomain);
domain = url.getHost().toLowerCase();// 获取主机名
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
} else {
domain = urlOrDomain;
}
Matcher matcher = Pattern.compile("(\\w+.\\w+)$").matcher(domain);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
/**
* 两个大数相减,默认没有符号位,且都为正数
*
* @param a a
* @param b b
* @return 相似度
*/
public static String bigDigitalSub(String a, String b) {
// 翻转字符串并转化成数组
char[] aArray = new StringBuilder(a).reverse().toString().toCharArray();
char[] bArray = new StringBuilder(b).reverse().toString().toCharArray();
int aLength = aArray.length;
int bLength = bArray.length;
// 找到最大的位数,两个整数的差的位数小于等于两个整数中的最大位数
int maxLength = aLength > bLength ? aLength : bLength;
int[] result = new int[maxLength];
// 判断结果符号
char sign = '+';
if (aLength < bLength)
sign = '-';
else if (aLength == bLength) {
int i = maxLength - 1;
while (i > 0 && aArray[i] == bArray[i])
i--;
if (aArray[i] < bArray[i])
sign = '-';
}
// 开始计算结果集
for (int i = 0; i < maxLength; i++) {
int aInt = i < aLength ? aArray[i] - '0' : 0;
int bInt = i < bLength ? bArray[i] - '0' : 0;
if (sign == '-')
result[i] = bInt - aInt;
else
result[i] = aInt - bInt;
}
// 处理结果集,如果结果集中的某一位小于0,则向高位借位,然后将本位加10
for (int i = 0; i < maxLength - 1; i++) {
if (result[i] < 0) {
result[i + 1] -= 1;
result[i] += 10;
}
}
// 处理 <SUF>
StringBuffer realResult = new StringBuffer();
if (sign == '-')
realResult.append('-');
boolean isBeginning = true;
for (int i = maxLength - 1; i >= 0; i--) {
if (result[i] == 0 && isBeginning)
continue;
else
isBeginning = false;
realResult.append(result[i]);
}
if (realResult.toString().equals(""))
realResult.append('0');
return realResult.toString();
}
/**
* 采用动态规划的方法解决
*
* @param source source
* @param target target
* @return 字符串相似度
*/
public static int editDistance(String source, String target) {
char[] sources = source.toCharArray();
char[] targets = target.toCharArray();
int sourceLen = sources.length;
int targetLen = targets.length;
int[][] d = new int[sourceLen + 1][targetLen + 1];
for (int i = 0; i <= sourceLen; i++) {
d[i][0] = i;
}
for (int i = 0; i <= targetLen; i++) {
d[0][i] = i;
}
for (int i = 1; i <= sourceLen; i++) {
for (int j = 1; j <= targetLen; j++) {
if (sources[i - 1] == targets[j - 1]) {
d[i][j] = d[i - 1][j - 1];
} else {
// 插入
int insert = d[i][j - 1] + 1;
// 删除
int delete = d[i - 1][j] + 1;
// 替换
int replace = d[i - 1][j - 1] + 1;
d[i][j] = Math.min(insert, delete) > Math.min(delete, replace) ? Math.min(delete, replace)
: Math.min(insert, delete);
}
}
}
return d[sourceLen][targetLen];
}
public static Date formatDate(String str, String format) {
if (format == null || format.isEmpty()) {
return null;
}
try {
return new SimpleDateFormat(format).parse(str);
} catch (ParseException e) {
}
return null;
}
public static String getMD5(String inStr) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bs = md5.digest(inStr.getBytes());
StringBuilder sb = new StringBuilder(40);
for (byte x : bs) {
if ((x & 0xff) >> 4 == 0) {
sb.append("0").append(Integer.toHexString(x & 0xff));
} else {
sb.append(Integer.toHexString(x & 0xff));
}
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return inStr;
}
}
public static boolean hasChinese(String str) {
return Pattern.compile("[\\u4e00-\\u9fa5]").matcher(str).find();
}
public static boolean isChinese(String str) {
return str.matches("[\\u4e00-\\u9fa5]+");
}
public static boolean hasNumber(String str) {
return Pattern.compile("\\d+").matcher(str).find();
}
public static boolean hasLetter(String str) {
return Pattern.compile("[a-zA-Z]+").matcher(str).find();
}
public static boolean hasNocrediteNumber(String text) {
// (2018)苏0205民初6040号
Pattern pattern = Pattern
.compile("[\\((][\\d]{4}[)\\)][\\u4e00-\\u9fa5]{1,3}[\\d]{4,5}[\\u4e00-\\u9fa5]{1,3}[\\d]{4,5}号");
return pattern.matcher(text).find();
}
public static String getPersonName(String name) throws Exception {
if (!isValidString(name)) {
throw new Exception("字符串无效:" + name);
}
if (name.contains("*")) {
throw new Exception("名字不能有*:" + name);
}
StringBuilder sb = new StringBuilder();
Matcher matcher = Pattern.compile("[\u4e00-\u9fa5a-zA-Z]").matcher(name);
while (matcher.find()) {
sb.append(matcher.group());
}
return sb.toString();
}
public static String filterNoNumber(String number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < number.length(); i++) {
if (number.charAt(i) == '*' || (number.charAt(i) >= '0' && number.charAt(i) <= '9')) {
sb.append(number.charAt(i));
}
}
return sb.toString();
}
public static String getNumber(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
return filterNoNumber(number);
}
public static String getCardIdNumber(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
Matcher matcher = Pattern.compile("\\d[\\d*a-zA-Z]{17}").matcher(number);
if (matcher.find()) {
return matcher.group(0);
}
throw new Exception("找不到身份证号:" + number);
}
public static String getTelephoneNumber(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
number = filterNoNumber(number);
if (number.startsWith("+86")) {
number = number.substring(3);
} else if (number.startsWith("86")) {
number = number.substring(2);
}
Matcher matcher = Pattern.compile("[\\d*\\-]{7,13}").matcher(number);
if (matcher.find()) {
number = matcher.group(0);
if (number.length() > 11) {
return number.substring(number.length() - 11);
}
return number;
}
throw new Exception("找不到手机号:" + number);
}
public static String getTelephoneNumberNoStar(String number) throws Exception {
if (!isValidString(number)) {
throw new Exception("字符串无效:" + number);
}
number = filterNoNumber(number);
if (number.startsWith("+86")) {
number = number.substring(3);
} else if (number.startsWith("86")) {
number = number.substring(2);
}
Matcher matcher = Pattern.compile("[\\d]{7,11}").matcher(number);
if (matcher.find()) {
number = matcher.group(0);
if (number.length() > 11) {
return number.substring(number.length() - 11);
}
return number;
}
throw new Exception("找不到手机号:" + number);
}
public static String mergeText(String a, String b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
if (!isSameText(a, b)) {
return a;
}
String n = "";
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != '*') {
n += a.charAt(i);
} else if (b.length() > i) {
n += b.charAt(i);
}
}
return n;
}
public static boolean isSameText(String cardIdA, String cardIdB) {
if (cardIdA != null && cardIdB != null && cardIdA.length() == cardIdB.length()) {
for (int i = 0; i < cardIdA.length(); i++) {
if (cardIdA.charAt(i) == '*' || cardIdB.charAt(i) == '*') {
continue;
}
if (cardIdA.charAt(i) != cardIdB.charAt(i)) {
return false;
}
}
}
return true;
}
/**
* @param str str
* @return starts ends of array
*/
public static String[] extractDesensitizationInfo(String str) {
String[] result = new String[2];
if (!str.startsWith("*")) {
String temp = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != '*') {
temp += ch;
} else {
result[0] = temp;
break;
}
if (temp.length() >= 5) {
result[0] = temp;
break;
}
}
}
if (!str.endsWith("*")) {
String temp = "";
int i = str.length() - 1;
for (; i < str.length(); i--) {
char ch = str.charAt(i);
if (ch != '*') {
temp = ch + temp;
} else {
result[1] = temp;
break;
}
if (temp.length() >= 5) {
result[1] = temp;
break;
}
}
}
return result;
}
public static boolean isValidString(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
return !str.contains("正在加载..");
}
public static boolean isValidTelephone(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
Matcher matcher = Pattern.compile("[\u4e00-\u9fa5]").matcher(str);
return !matcher.find();
}
public static boolean isSamePrefix(String a, String b, int num) {
for (int i = 0; i < num; i++) {
if (a.charAt(i) != b.charAt(i)) {
return false;
}
}
return true;
}
/**
* 区县名字简易化
*
* @param district addr text
* @return simple name
*/
public static String district2SimpleText(String district) {
if (district.endsWith("市") || district.endsWith("区")) {
return district.substring(0, district.length() - 1);
}
return district;
}
/**
* 乡镇名字简易化
*
* @param village addr text
* @return simple name
*/
public static String village2SimpleText(String village) {
if (village.endsWith("镇") || village.endsWith("乡") || village.endsWith("村") || village.endsWith("组")) {
return village.substring(0, village.length() - 1);
}
if (village.endsWith("街道") || village.endsWith("集团") || village.endsWith("林场") || village.endsWith("大队")
|| village.endsWith("基地")) {
return village.substring(0, village.length() - 2);
}
return village;
}
/**
* 公司名字简易化
*
* @param companyName name
* @return simple name
*/
public static String companyName2SimpleText(String companyName) {
if (companyName.contains("有限公司")) {
companyName = companyName.substring(0, companyName.indexOf("有限公司") - 2);
}
if (companyName.contains("有限责任公司")) {
companyName = companyName.substring(0, companyName.indexOf("有限责任公司") - 2);
}
return companyName;
}
/**
* 去除括号里面的
*
* @param addressText addr text
* @return no symbol name
*/
public static String removeParenthesis(String addressText) {
int startIndex = addressText.indexOf("(");
int endIndex = addressText.indexOf(")");
while (endIndex > startIndex && startIndex > 0) {
addressText = addressText.substring(0, startIndex) + addressText.substring(endIndex + 1);
addressText.indexOf("(");
endIndex = addressText.indexOf(")");
}
startIndex = addressText.indexOf("(");
endIndex = addressText.indexOf(")");
while (endIndex > startIndex && startIndex > 0) {
addressText = addressText.substring(0, startIndex) + addressText.substring(endIndex + 1);
addressText.indexOf("(");
endIndex = addressText.indexOf(")");
}
addressText = addressText.replaceAll("\\(", "").replaceAll("\\)", "");
addressText = addressText.replaceAll("(", "").replaceAll(")", "");
return addressText;
}
}
| 1 | 16 | 1 |
20931_4 | package com.lou.simhasher;
import java.math.BigInteger;
import java.util.Map;
import java.util.Set;
import com.lou.simhasher.util.FNVHash;
/**
* 文本去重算法的simhash类
* 步骤如下:
* 1,对文本分词,得到N维特征向量(默认为64维)
* 2,为分词设置权重(tf-idf)
* 3,为特征向量计算哈希
* 4,对所有特征向量加权,累加(目前仅进行非加权累加)
* 5,对累加结果,大于零置一,小于零置零
* 6,得到文本指纹(fingerprint)
*
* @author [email protected]
*/
public class SimHasher {
private String hash;
private BigInteger signature;
private KeywordExtractor wordExtractor = KeywordExtractor.getInstance();
/**
* 构造函数
*
* @param content 字符串
*/
public SimHasher(String content) {
this.analysis(content);
}
private void analysis(String content) {
Map<String, Double> wordInfos = wordExtractor.extract(content);
double[] featureVector = new double[FNVHash.HASH_BITS];
Set<String> words = wordInfos.keySet();
// System.out.println(words);
for (String word : words) {
BigInteger wordhash = FNVHash.fnv1aHash64(word);
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
BigInteger bitmask = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1);
if (wordhash.and(bitmask).signum() != 0) {
featureVector[i] += wordInfos.get(word);
} else {
featureVector[i] -= wordInfos.get(word);
}
}
}
BigInteger signature = BigInteger.ZERO;
StringBuffer hashBuffer = new StringBuffer();
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
if (featureVector[i] >= 0) {
signature = signature.add(BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1));
hashBuffer.append("1");
} else {
hashBuffer.append("0");
}
}
this.hash = hashBuffer.toString();
this.signature = signature;
}
/**
* 汉明距离
*
* @param targetSignature 比较签名
* @return
*/
public int getHammingDistance(BigInteger targetSignature) {
BigInteger x = this.getSignature().xor(targetSignature);
int tot = 0;
// 统计x中二进制位数为1的个数
// 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了,
// 对吧,然后,n&(n-1)就相当于把后面的数字清0,
// 我们看n能做多少次这样的操作就OK了。
while (x.signum() != 0) {
tot += 1;
x = x.and(x.subtract(new BigInteger("1")));
}
return tot;
}
/**
* hash距离。二进制比较
*
* @param targetHash 比较目标
* @return
*/
public int getHashDistance(String targetHash) {
int distance;
if (this.getHash().length() != targetHash.length()) {
distance = -1;
} else {
distance = 0;
for (int i = 0; i < this.getHash().length(); i++) {
if (this.getHash().charAt(i) != targetHash.charAt(i)) {
distance++;
}
}
}
return distance;
}
public String getHash() {
return this.hash;
}
public BigInteger getSignature() {
return this.signature;
}
}
| CreekLou/simhash | src/main/java/com/lou/simhasher/SimHasher.java | 1,024 | // 统计x中二进制位数为1的个数
| line_comment | zh-cn | package com.lou.simhasher;
import java.math.BigInteger;
import java.util.Map;
import java.util.Set;
import com.lou.simhasher.util.FNVHash;
/**
* 文本去重算法的simhash类
* 步骤如下:
* 1,对文本分词,得到N维特征向量(默认为64维)
* 2,为分词设置权重(tf-idf)
* 3,为特征向量计算哈希
* 4,对所有特征向量加权,累加(目前仅进行非加权累加)
* 5,对累加结果,大于零置一,小于零置零
* 6,得到文本指纹(fingerprint)
*
* @author [email protected]
*/
public class SimHasher {
private String hash;
private BigInteger signature;
private KeywordExtractor wordExtractor = KeywordExtractor.getInstance();
/**
* 构造函数
*
* @param content 字符串
*/
public SimHasher(String content) {
this.analysis(content);
}
private void analysis(String content) {
Map<String, Double> wordInfos = wordExtractor.extract(content);
double[] featureVector = new double[FNVHash.HASH_BITS];
Set<String> words = wordInfos.keySet();
// System.out.println(words);
for (String word : words) {
BigInteger wordhash = FNVHash.fnv1aHash64(word);
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
BigInteger bitmask = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1);
if (wordhash.and(bitmask).signum() != 0) {
featureVector[i] += wordInfos.get(word);
} else {
featureVector[i] -= wordInfos.get(word);
}
}
}
BigInteger signature = BigInteger.ZERO;
StringBuffer hashBuffer = new StringBuffer();
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
if (featureVector[i] >= 0) {
signature = signature.add(BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1));
hashBuffer.append("1");
} else {
hashBuffer.append("0");
}
}
this.hash = hashBuffer.toString();
this.signature = signature;
}
/**
* 汉明距离
*
* @param targetSignature 比较签名
* @return
*/
public int getHammingDistance(BigInteger targetSignature) {
BigInteger x = this.getSignature().xor(targetSignature);
int tot = 0;
// 统计 <SUF>
// 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了,
// 对吧,然后,n&(n-1)就相当于把后面的数字清0,
// 我们看n能做多少次这样的操作就OK了。
while (x.signum() != 0) {
tot += 1;
x = x.and(x.subtract(new BigInteger("1")));
}
return tot;
}
/**
* hash距离。二进制比较
*
* @param targetHash 比较目标
* @return
*/
public int getHashDistance(String targetHash) {
int distance;
if (this.getHash().length() != targetHash.length()) {
distance = -1;
} else {
distance = 0;
for (int i = 0; i < this.getHash().length(); i++) {
if (this.getHash().charAt(i) != targetHash.charAt(i)) {
distance++;
}
}
}
return distance;
}
public String getHash() {
return this.hash;
}
public BigInteger getSignature() {
return this.signature;
}
}
| 1 | 18 | 1 |
56734_18 | import java.util.ArrayList;
import java.util.HashMap;
public class Excel_info {
ArrayList<String> excelList = new ArrayList<String>();
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
static public ArrayList<String> get_planting_area_excelList(){
// 涉及的表有: 1,3,13,15
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表1:水稻直补、农资综合、机育插秧补贴-2013.xlsx");
list.add("崇明县-表1:水稻直补、农资综合、机育插秧补贴-2014.xlsx");
list.add("崇明县-表1:水稻直补、农资综合、机育插秧补贴-2015.xlsx");
list.add("崇明县-表3:农作物良种补贴-2013.xlsx");
list.add("崇明县-表3:农作物良种补贴-2014.xlsx");
list.add("崇明县-表3:农作物良种补贴-2015.xlsx");
list.add("崇明县-表13:绿肥种植补贴-2013.xlsx");
list.add("崇明县-表13:绿肥种植补贴-2014.xlsx");
list.add("崇明县-表13:绿肥种植补贴-2015.xlsx");
list.add("崇明县-表15:“夏淡”绿叶菜种植补贴-2013.xlsx");
list.add("崇明县-表15:“夏淡”绿叶菜种植补贴-2014.xlsx");
list.add("崇明县-表15:“夏淡”绿叶菜种植补贴-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_planting_area_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,种植作物,种植面积
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(10);args.add(11);
// 3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(10);args.add(11);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("绿肥");args.add(10);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("夏淡绿叶菜");args.add(11);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_fertilizer_pesticide_are_excelList(){
// 涉及的表有: 7,17,18,43
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表7:蔬菜农药补贴-2012.xlsx");
list.add("崇明县-表7:蔬菜农药补贴-2013.xlsx");
list.add("崇明县-表7:蔬菜农药补贴-2014.xlsx");
list.add("崇明县-表17:水稻农药补贴-2013.xlsx");
list.add("崇明县-表17:水稻农药补贴-2014.xlsx");
list.add("崇明县-表17:水稻农药补贴-2015.xlsx");
list.add("崇明县-表18:商品有机肥补贴-2013.xlsx");
list.add("崇明县-表18:商品有机肥补贴-2014.xlsx");
list.add("崇明县-表18:商品有机肥补贴-2015.xlsx");
list.add("崇明县-表43:小麦赤霉病防治药剂补贴-2013.xlsx");
list.add("崇明县-表43:小麦赤霉病防治药剂补贴-2014.xlsx");
list.add("崇明县-表43:小麦赤霉病防治药剂补贴-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_fertilizer_pesticide_are_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,农药肥料类型,使用量,单位
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("蔬菜农药");args.add(11);args.add("亩");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("水稻农药");args.add(10);args.add("亩");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("商品有机肥");args.add(10);args.add("件");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("小麦赤霉病防治药剂");args.add(10);args.add("亩");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_fishing_scale_excelList(){
// 涉及的表有: 5
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表5:渔业油价补贴-2012.xlsx");
list.add("崇明县-表5:渔业油价补贴-2013.xlsx");
list.add("崇明县-表5:渔业油价补贴-2014.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_fishing_scale_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,渔船类型,渔船名号,渔船功率
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(11);args.add(10);args.add(12);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_graziery_scale_excelList(){
// 涉及的表有:
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表11:动物强制免疫-2013.xlsx");
list.add("崇明县-表11:动物强制免疫-2014.xlsx");
list.add("崇明县-表11:动物强制免疫-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_graziery_scale_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,养殖品种,养殖规模
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(10);args.add(11);;
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_insurance_excelList(){
// 涉及的表有: 9,
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表9:农业保险补贴-2013.xlsx");
list.add("崇明县-表9:农业保险补贴-2014.xlsx");
list.add("崇明县-表9:农业保险补贴-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_insurance_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,农业类型,险种,投保数量(万)
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("...");args.add(11);args.add(13);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
static public String get_type_by_insurance(String insurance){
if(insurance == null)
return null;
HashMap<String,String> map = new HashMap<String,String>();
map.put("'保淡绿叶菜综合成本价格保险'", "'种植业'");
map.put("'大棚设施保险'", "'种植业'");
map.put("'果树(水果收获)保险'", "'种植业'");
map.put("'麦子种植保险'", "'种植业'");
map.put("'农机具综合保险'", "'种植业'");
map.put("'蔬菜种植保险'", "'种植业'");
map.put("'水稻制种保险'", "'种植业'");
map.put("'水稻种植保险'", "'种植业'");
map.put("'西甜瓜种植成本保险'", "'种植业'");
map.put("'鲜食玉米种植保险'", "'种植业'");
map.put("'油菜种植保险'", "'种植业'");
map.put("'林木种植保险'", "'种植业'");
map.put("'露地种植青菜鸡毛菜气象指数保险'", "'种植业'");
map.put("'淡水养殖(经济鱼虾)保险'", "'渔业'");
map.put("'淡水养殖(南美白对虾)保险'", "'渔业'");
map.put("'群众渔船综合保险'", "'渔业'");
map.put("'淡水养殖(南美白对虾)保险'", "'渔业'");
map.put("'奶牛养殖保险'", "'畜牧业'");
map.put("'能繁母猪养殖保险'", "'畜牧业'");
map.put("'生猪养殖保险'", "'畜牧业'");
map.put("'羊养殖保险'", "'畜牧业'");
String ans = map.get(insurance);
if(ans!=null)
return ans;
ans = insurance;
if(ans.indexOf("菜")!=-1){
return "种植业";
}else if (ans.indexOf("瓜")!=-1){
return "种植业";
}else if (ans.indexOf("果")!=-1){
return "种植业";
}else if (ans.indexOf("农")!=-1){
return "种植业";
}else if (ans.indexOf("林")!=-1){
return "种植业";
}else if (ans.indexOf("米")!=-1){
return "种植业";
}else if (ans.indexOf("稻")!=-1){
return "种植业";
}else if (ans.indexOf("麦")!=-1){
return "种植业";
}else if (ans.indexOf("鱼")!=-1){
return "渔业";
}else if (ans.indexOf("虾")!=-1){
return "渔业";
}else if (ans.indexOf("淡水")!=-1){
return "渔业";
}else if (ans.indexOf("海")!=-1){
return "渔业";
}else if (ans.indexOf("渔")!=-1){
return "渔业";
}else if (ans.indexOf("船")!=-1){
return "渔业";
}else {
return "畜牧业";
}
}
}
| CrisJk/Agriculture | eason_project/NW_createDB/src/Excel_info.java | 4,073 | //姓名,身份证,企业名,区县,镇,村,年度,渔船类型,渔船名号,渔船功率 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.HashMap;
public class Excel_info {
ArrayList<String> excelList = new ArrayList<String>();
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
static public ArrayList<String> get_planting_area_excelList(){
// 涉及的表有: 1,3,13,15
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表1:水稻直补、农资综合、机育插秧补贴-2013.xlsx");
list.add("崇明县-表1:水稻直补、农资综合、机育插秧补贴-2014.xlsx");
list.add("崇明县-表1:水稻直补、农资综合、机育插秧补贴-2015.xlsx");
list.add("崇明县-表3:农作物良种补贴-2013.xlsx");
list.add("崇明县-表3:农作物良种补贴-2014.xlsx");
list.add("崇明县-表3:农作物良种补贴-2015.xlsx");
list.add("崇明县-表13:绿肥种植补贴-2013.xlsx");
list.add("崇明县-表13:绿肥种植补贴-2014.xlsx");
list.add("崇明县-表13:绿肥种植补贴-2015.xlsx");
list.add("崇明县-表15:“夏淡”绿叶菜种植补贴-2013.xlsx");
list.add("崇明县-表15:“夏淡”绿叶菜种植补贴-2014.xlsx");
list.add("崇明县-表15:“夏淡”绿叶菜种植补贴-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_planting_area_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,种植作物,种植面积
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(10);args.add(11);
// 3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(10);args.add(11);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("绿肥");args.add(10);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("夏淡绿叶菜");args.add(11);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_fertilizer_pesticide_are_excelList(){
// 涉及的表有: 7,17,18,43
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表7:蔬菜农药补贴-2012.xlsx");
list.add("崇明县-表7:蔬菜农药补贴-2013.xlsx");
list.add("崇明县-表7:蔬菜农药补贴-2014.xlsx");
list.add("崇明县-表17:水稻农药补贴-2013.xlsx");
list.add("崇明县-表17:水稻农药补贴-2014.xlsx");
list.add("崇明县-表17:水稻农药补贴-2015.xlsx");
list.add("崇明县-表18:商品有机肥补贴-2013.xlsx");
list.add("崇明县-表18:商品有机肥补贴-2014.xlsx");
list.add("崇明县-表18:商品有机肥补贴-2015.xlsx");
list.add("崇明县-表43:小麦赤霉病防治药剂补贴-2013.xlsx");
list.add("崇明县-表43:小麦赤霉病防治药剂补贴-2014.xlsx");
list.add("崇明县-表43:小麦赤霉病防治药剂补贴-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_fertilizer_pesticide_are_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,农药肥料类型,使用量,单位
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("蔬菜农药");args.add(11);args.add("亩");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("水稻农药");args.add(10);args.add("亩");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("商品有机肥");args.add(10);args.add("件");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("小麦赤霉病防治药剂");args.add(10);args.add("亩");
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_fishing_scale_excelList(){
// 涉及的表有: 5
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表5:渔业油价补贴-2012.xlsx");
list.add("崇明县-表5:渔业油价补贴-2013.xlsx");
list.add("崇明县-表5:渔业油价补贴-2014.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_fishing_scale_argList(){
//姓名 <SUF>
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(11);args.add(10);args.add(12);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_graziery_scale_excelList(){
// 涉及的表有:
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表11:动物强制免疫-2013.xlsx");
list.add("崇明县-表11:动物强制免疫-2014.xlsx");
list.add("崇明县-表11:动物强制免疫-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_graziery_scale_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,养殖品种,养殖规模
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add(10);args.add(11);;
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
//填写需要读取的文件名
static public ArrayList<String> get_insurance_excelList(){
// 涉及的表有: 9,
ArrayList<String> list = new ArrayList<String>();
list.add("崇明县-表9:农业保险补贴-2013.xlsx");
list.add("崇明县-表9:农业保险补贴-2014.xlsx");
list.add("崇明县-表9:农业保险补贴-2015.xlsx");
return list;
}
//填写需要读取的参数信息
static public ArrayList<ArrayList<Object>> get_insurance_argList(){
//姓名,身份证,企业名,区县,镇,村,年度,农业类型,险种,投保数量(万)
ArrayList<ArrayList<Object>> argList = new ArrayList<ArrayList<Object>>();
ArrayList <Object> args = null;
args = new ArrayList <Object>();
args.add(7);args.add(8);args.add(9);args.add(3);args.add(4);args.add(5);args.add(0);
args.add("...");args.add(11);args.add(13);
//3个表参数一样
argList.add(args);
argList.add(args);
argList.add(args);
return argList;
}
static public String get_type_by_insurance(String insurance){
if(insurance == null)
return null;
HashMap<String,String> map = new HashMap<String,String>();
map.put("'保淡绿叶菜综合成本价格保险'", "'种植业'");
map.put("'大棚设施保险'", "'种植业'");
map.put("'果树(水果收获)保险'", "'种植业'");
map.put("'麦子种植保险'", "'种植业'");
map.put("'农机具综合保险'", "'种植业'");
map.put("'蔬菜种植保险'", "'种植业'");
map.put("'水稻制种保险'", "'种植业'");
map.put("'水稻种植保险'", "'种植业'");
map.put("'西甜瓜种植成本保险'", "'种植业'");
map.put("'鲜食玉米种植保险'", "'种植业'");
map.put("'油菜种植保险'", "'种植业'");
map.put("'林木种植保险'", "'种植业'");
map.put("'露地种植青菜鸡毛菜气象指数保险'", "'种植业'");
map.put("'淡水养殖(经济鱼虾)保险'", "'渔业'");
map.put("'淡水养殖(南美白对虾)保险'", "'渔业'");
map.put("'群众渔船综合保险'", "'渔业'");
map.put("'淡水养殖(南美白对虾)保险'", "'渔业'");
map.put("'奶牛养殖保险'", "'畜牧业'");
map.put("'能繁母猪养殖保险'", "'畜牧业'");
map.put("'生猪养殖保险'", "'畜牧业'");
map.put("'羊养殖保险'", "'畜牧业'");
String ans = map.get(insurance);
if(ans!=null)
return ans;
ans = insurance;
if(ans.indexOf("菜")!=-1){
return "种植业";
}else if (ans.indexOf("瓜")!=-1){
return "种植业";
}else if (ans.indexOf("果")!=-1){
return "种植业";
}else if (ans.indexOf("农")!=-1){
return "种植业";
}else if (ans.indexOf("林")!=-1){
return "种植业";
}else if (ans.indexOf("米")!=-1){
return "种植业";
}else if (ans.indexOf("稻")!=-1){
return "种植业";
}else if (ans.indexOf("麦")!=-1){
return "种植业";
}else if (ans.indexOf("鱼")!=-1){
return "渔业";
}else if (ans.indexOf("虾")!=-1){
return "渔业";
}else if (ans.indexOf("淡水")!=-1){
return "渔业";
}else if (ans.indexOf("海")!=-1){
return "渔业";
}else if (ans.indexOf("渔")!=-1){
return "渔业";
}else if (ans.indexOf("船")!=-1){
return "渔业";
}else {
return "畜牧业";
}
}
}
| 1 | 37 | 1 |
18675_4 | package UI;
// 所有的道具包
public class Bag extends FlyObject {
public Bag(int x, int y) {
this.x = x;
this.y = y;
this.height = 50;
this.width = 50;
}
/**
* 根据的类型来获取新的道具包,x和y是被打的砖块的位置,道具在砖块的位置生成
* @param i
* @param x
* @param y
* @return
*/
public static Bag getBag(int i, int x, int y) {
Bag bag = null;
switch (i) {
case 1:
bag = new RocketBag(x, y);
break;
case 2:
bag = new PunchBag(x, y);
break;
case 3:
bag = new BoomBag(x, y);
break;
case 4:
bag = new LengthenBag(x, y);
break;
case 5:
bag = new ShortenBag(x, y);
break;
case 6:
bag = new DieBag(x, y);
break;
case 7:
bag = new BigBallBag(x, y);
break;
case 8:
bag = new SmallBallBag(x, y);
break;
case 9:
bag = new CommonBallBag(x, y);
break;
}
return bag;
}
}
// 导弹球
class RocketBag extends Bag {
public RocketBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/RocketBag.png");
}
}
// 穿刺球
class PunchBag extends Bag {
public PunchBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/PunchBag.png");
}
}
// 炸弹球
class BoomBag extends Bag {
public BoomBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BoomBag.png");
}
}
// 让挡板变长
class LengthenBag extends Bag {
public LengthenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/LengthenBag.png");
}
}
// 让挡板变小
class ShortenBag extends Bag {
public ShortenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ShortenBag.png");
}
}
// 死亡
class DieBag extends Bag {
public DieBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/DieBag.png");
}
}
// 让球变大
class BigBallBag extends Bag {
public BigBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BigBallBag.png");
}
}
// 让球变小
class SmallBallBag extends Bag {
public SmallBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/SmallBallBag.png");
}
}
// 普通球道具包
class CommonBallBag extends Bag {
public CommonBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ball.png");
}
}
| CrispyCandy750/hit_brick | UI/Bag.java | 841 | // 炸弹球 | line_comment | zh-cn | package UI;
// 所有的道具包
public class Bag extends FlyObject {
public Bag(int x, int y) {
this.x = x;
this.y = y;
this.height = 50;
this.width = 50;
}
/**
* 根据的类型来获取新的道具包,x和y是被打的砖块的位置,道具在砖块的位置生成
* @param i
* @param x
* @param y
* @return
*/
public static Bag getBag(int i, int x, int y) {
Bag bag = null;
switch (i) {
case 1:
bag = new RocketBag(x, y);
break;
case 2:
bag = new PunchBag(x, y);
break;
case 3:
bag = new BoomBag(x, y);
break;
case 4:
bag = new LengthenBag(x, y);
break;
case 5:
bag = new ShortenBag(x, y);
break;
case 6:
bag = new DieBag(x, y);
break;
case 7:
bag = new BigBallBag(x, y);
break;
case 8:
bag = new SmallBallBag(x, y);
break;
case 9:
bag = new CommonBallBag(x, y);
break;
}
return bag;
}
}
// 导弹球
class RocketBag extends Bag {
public RocketBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/RocketBag.png");
}
}
// 穿刺球
class PunchBag extends Bag {
public PunchBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/PunchBag.png");
}
}
// 炸弹 <SUF>
class BoomBag extends Bag {
public BoomBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BoomBag.png");
}
}
// 让挡板变长
class LengthenBag extends Bag {
public LengthenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/LengthenBag.png");
}
}
// 让挡板变小
class ShortenBag extends Bag {
public ShortenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ShortenBag.png");
}
}
// 死亡
class DieBag extends Bag {
public DieBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/DieBag.png");
}
}
// 让球变大
class BigBallBag extends Bag {
public BigBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BigBallBag.png");
}
}
// 让球变小
class SmallBallBag extends Bag {
public SmallBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/SmallBallBag.png");
}
}
// 普通球道具包
class CommonBallBag extends Bag {
public CommonBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ball.png");
}
}
| 1 | 6 | 1 |
30983_23 | package com.shop.common;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
/**
* 公用静态类
*/
public class Constants {
//读取配置文件
private static Configuration cacheConfig;
static {
try {
cacheConfig = new PropertiesConfiguration("ApplicationResources.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
/**
* 当前登录用户Session常量
*/
public static final String CURRENT_LOGIN_USER="CURRENT_LOGIN_USER";
/**
* 登录验证码Session常量
*/
public static final String KAPTCHA_SESSION_KEY="KAPTCHA_SESSION_KEY";
/**
* 一级菜单标记
*/
public static final String FIRST_MENU_FLAG="0";
/**
* 角色树根标识
*/
public static final String ROLE_TREE_ROOT_FLAG="0";
/**
* 角色树根名称
*/
public static final String ROLE_TREE_ROOT_NAME="角色";
/**
* 按钮树根名称
*/
public static final String BUTTON_TREE_ROOT_NAME="按钮";
/**
* 运行按钮的code
*/
public static final String RUN_BUTTON_CODE="f14f35f8-2246-41h2-34f2-4cg56ad75ead";
/**
* 权限树根名称
*/
public static final String AUTH_TREE_ROOT_NAME="权限";
/**
* 权限树根标识
*/
public static final String AUTH_TREE_ROOT_FLAG="";
/***
* 列表数据每页默认条数
*/
//public static final int DEFAULT_PAGE_SIZE=cacheConfig.getInt("DEFAULT_PAGE_SIZE");
/**
* 系统用户状态:1 有效 0 无效
*/
public static final String SYSUSER_STATUS_VALID = "1";
/**
* 系统admin 角色id
*/
public static final String ADMIN_ROLE_CODE ="d22f30b8-2716-41d2-84f2-4cd56bb75ecc";
/**
* 合作商和把握公司合作状态: 1 正常合作 2 暂停 合作 3 取消合作
*/
public static final String PARTNER_COOPERATE_STATUS_NORMAL="1";
public static final String PARTNER_COOPERATE_STATUS_PAUSE="2";
public static final String PARTNER_COOPERATE_STATUS_DELETE="3";
/**
* 合作商和铺设点合作状态: 1 正常合作 2 暂停 合作 3 取消合作
*/
public static final String PARTNER_PAVE_COOPERATE_STATUS_NORMAL = "1";
/**
* 电子券的状态 :0未认证 3 冻结
*
*/
public static final String ELECTICKET_STATUS_FREEZE="3";
public static final String ELECTICKET_STATUS_UNAPPROVE="0";
/**
* 电子券的操作类型 1 冻结 2 恢复
*/
public static final String ELECTICKET_OPTYPE_FREEZE="1";
public static final String ELECTICKET_OPTYPE_RECOVER="2";
/**
* pov机心跳间隔多久判断为运行故障 默认40分钟
*/
public static final int POV_RUNNING_STATUS_TIME=40;
/**
* pov机在铺设点的使用状态 1 正常 2 暂停
*/
public static final String POV_USE_STATUS_NORMAL = "1";
public static final String POV_USE_STATUS_NORMAL_STR = "正常";
public static final String POV_USE_STATUS_PAUSE_STR = "暂停";
/**
* 铺设点状态 1 正常 2 暂停
*/
public static final String PAVE_STATUS_NORMAL = "1";
public static final String PAVE_STATUS_PAUSE = "2";
public static final String PAVE_STATUS_NORMAL_STR = "正常";
public static final String PAVE_STATUS_PAUSE_STR = "暂停";
/**
* pov机的使用状态1 正常,2 暂停
*/
public static final String POV_USE_STATUS_PAUSE="2";
public static final String POV_USE_STATUS_RECOVER="1";
public static final String POV_USE_STATUS_RELEVANCE="已关联";
public static final String POV_USE_STATUS_RELIVE="暂停";
/**
* 铺设点操作类型 3 删除, 2 暂停
*/
public static final String PAVE_OPERATE_DELETE = "3";
/**
* POV添加方式 1 单个添加 2 批量添加
*/
public static final String WAREHOUSE_POV_ADD_SATUS="1";
public static final String WAREHOUSE_POV_ADD_LIST_SATUS="2";
/**
* POV仓库管理状态 1 已入库 2 已出库 3维修中
*/
public static final String WAREHOUSE_POV_SATUS_IN="1";
public static final String WAREHOUSE_POV_SATUS_OUT="2";
public static final String WAREHOUSE_POV_SATUS_MAINTAIN="3";
/**
* 解析Excel保存在session中的KEY
*/
public static final String PARSE_EXCEL_SESSION_KEY = "PaveListFromParseExcel";
}
| CruiseLiugit/shop | src/com/shop/common/Constants.java | 1,406 | /**
* 铺设点操作类型 3 删除, 2 暂停
*/ | block_comment | zh-cn | package com.shop.common;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
/**
* 公用静态类
*/
public class Constants {
//读取配置文件
private static Configuration cacheConfig;
static {
try {
cacheConfig = new PropertiesConfiguration("ApplicationResources.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
/**
* 当前登录用户Session常量
*/
public static final String CURRENT_LOGIN_USER="CURRENT_LOGIN_USER";
/**
* 登录验证码Session常量
*/
public static final String KAPTCHA_SESSION_KEY="KAPTCHA_SESSION_KEY";
/**
* 一级菜单标记
*/
public static final String FIRST_MENU_FLAG="0";
/**
* 角色树根标识
*/
public static final String ROLE_TREE_ROOT_FLAG="0";
/**
* 角色树根名称
*/
public static final String ROLE_TREE_ROOT_NAME="角色";
/**
* 按钮树根名称
*/
public static final String BUTTON_TREE_ROOT_NAME="按钮";
/**
* 运行按钮的code
*/
public static final String RUN_BUTTON_CODE="f14f35f8-2246-41h2-34f2-4cg56ad75ead";
/**
* 权限树根名称
*/
public static final String AUTH_TREE_ROOT_NAME="权限";
/**
* 权限树根标识
*/
public static final String AUTH_TREE_ROOT_FLAG="";
/***
* 列表数据每页默认条数
*/
//public static final int DEFAULT_PAGE_SIZE=cacheConfig.getInt("DEFAULT_PAGE_SIZE");
/**
* 系统用户状态:1 有效 0 无效
*/
public static final String SYSUSER_STATUS_VALID = "1";
/**
* 系统admin 角色id
*/
public static final String ADMIN_ROLE_CODE ="d22f30b8-2716-41d2-84f2-4cd56bb75ecc";
/**
* 合作商和把握公司合作状态: 1 正常合作 2 暂停 合作 3 取消合作
*/
public static final String PARTNER_COOPERATE_STATUS_NORMAL="1";
public static final String PARTNER_COOPERATE_STATUS_PAUSE="2";
public static final String PARTNER_COOPERATE_STATUS_DELETE="3";
/**
* 合作商和铺设点合作状态: 1 正常合作 2 暂停 合作 3 取消合作
*/
public static final String PARTNER_PAVE_COOPERATE_STATUS_NORMAL = "1";
/**
* 电子券的状态 :0未认证 3 冻结
*
*/
public static final String ELECTICKET_STATUS_FREEZE="3";
public static final String ELECTICKET_STATUS_UNAPPROVE="0";
/**
* 电子券的操作类型 1 冻结 2 恢复
*/
public static final String ELECTICKET_OPTYPE_FREEZE="1";
public static final String ELECTICKET_OPTYPE_RECOVER="2";
/**
* pov机心跳间隔多久判断为运行故障 默认40分钟
*/
public static final int POV_RUNNING_STATUS_TIME=40;
/**
* pov机在铺设点的使用状态 1 正常 2 暂停
*/
public static final String POV_USE_STATUS_NORMAL = "1";
public static final String POV_USE_STATUS_NORMAL_STR = "正常";
public static final String POV_USE_STATUS_PAUSE_STR = "暂停";
/**
* 铺设点状态 1 正常 2 暂停
*/
public static final String PAVE_STATUS_NORMAL = "1";
public static final String PAVE_STATUS_PAUSE = "2";
public static final String PAVE_STATUS_NORMAL_STR = "正常";
public static final String PAVE_STATUS_PAUSE_STR = "暂停";
/**
* pov机的使用状态1 正常,2 暂停
*/
public static final String POV_USE_STATUS_PAUSE="2";
public static final String POV_USE_STATUS_RECOVER="1";
public static final String POV_USE_STATUS_RELEVANCE="已关联";
public static final String POV_USE_STATUS_RELIVE="暂停";
/**
* 铺设点 <SUF>*/
public static final String PAVE_OPERATE_DELETE = "3";
/**
* POV添加方式 1 单个添加 2 批量添加
*/
public static final String WAREHOUSE_POV_ADD_SATUS="1";
public static final String WAREHOUSE_POV_ADD_LIST_SATUS="2";
/**
* POV仓库管理状态 1 已入库 2 已出库 3维修中
*/
public static final String WAREHOUSE_POV_SATUS_IN="1";
public static final String WAREHOUSE_POV_SATUS_OUT="2";
public static final String WAREHOUSE_POV_SATUS_MAINTAIN="3";
/**
* 解析Excel保存在session中的KEY
*/
public static final String PARSE_EXCEL_SESSION_KEY = "PaveListFromParseExcel";
}
| 0 | 32 | 0 |
62978_3 | package org.brewchain.account.function;
import org.apache.felix.ipojo.util.Log;
import org.brewchain.account.core.AccountHelper;
import org.brewchain.account.test.InternalCallTest;
import com.google.protobuf.ByteString;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class InternalFunction {
/**
* 挖矿奖励
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerReward(AccountHelper accountHelper, String... params) throws Exception {
String blackHoleAddress = "";
String balance = "0";
String coinBase = "";
log.debug(String.format("call MinerReward!"));
accountHelper.addBalance(ByteString.copyFromUtf8(coinBase).toByteArray(), Long.valueOf(balance));
// 黑洞地址
accountHelper.addBalance(ByteString.copyFromUtf8(blackHoleAddress).toByteArray(), 0 - Long.valueOf(balance));
}
/**
* 挖矿惩罚
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerPunish(AccountHelper accountHelper, byte[] blackHoleAddress, byte[] coinBase, long balance)
throws Exception {
accountHelper.addBalance(coinBase, 0 - balance);
// 黑洞地址
accountHelper.addBalance(blackHoleAddress, balance);
}
}
| CryptoWorldChain/chaincore | account/src/main/java/org/brewchain/account/function/InternalFunction.java | 389 | // 黑洞地址 | line_comment | zh-cn | package org.brewchain.account.function;
import org.apache.felix.ipojo.util.Log;
import org.brewchain.account.core.AccountHelper;
import org.brewchain.account.test.InternalCallTest;
import com.google.protobuf.ByteString;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class InternalFunction {
/**
* 挖矿奖励
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerReward(AccountHelper accountHelper, String... params) throws Exception {
String blackHoleAddress = "";
String balance = "0";
String coinBase = "";
log.debug(String.format("call MinerReward!"));
accountHelper.addBalance(ByteString.copyFromUtf8(coinBase).toByteArray(), Long.valueOf(balance));
// 黑洞地址
accountHelper.addBalance(ByteString.copyFromUtf8(blackHoleAddress).toByteArray(), 0 - Long.valueOf(balance));
}
/**
* 挖矿惩罚
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerPunish(AccountHelper accountHelper, byte[] blackHoleAddress, byte[] coinBase, long balance)
throws Exception {
accountHelper.addBalance(coinBase, 0 - balance);
// 黑洞 <SUF>
accountHelper.addBalance(blackHoleAddress, balance);
}
}
| 1 | 7 | 1 |
44371_4 | /**
* <li>文件名:Config.java
* <li>说明:
* <li>创建人: CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
package com.jason;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jason.util.MyStringUtil;
/**
* <li>类型名称:
* <li>说明:服务器参数配置文件
* <li>创建人: CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public class Config {
private static Log log = LogFactory.getLog(Config.class);// 日志记录器
private static final String CONFIG_FILE = "config.properties";// 数据库连接池配置文件,支持配置多个数据库链接
private static Properties props = new Properties();// 属性
static{
// 读取配置文件,根据配置文件创建配置信息
try {
InputStream fileInput =Config.class.getResourceAsStream(CONFIG_FILE);
// 加载配置文件
props.load(fileInput);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.info("配置文件不存在,请仔细检查");
} catch (IOException e) {
e.printStackTrace();
log.info("配置文件读取错误");
}
}
/**
*
* <li>方法名:getProperty
* <li>@param key
* <li>@return
* <li>返回类型:String
* <li>说明:获取指定配置信息
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static String getStr(String key){
return props.getProperty(key);
}
/**
*
* <li>方法名:getLong
* <li>@param key
* <li>@return
* <li>返回类型:Long
* <li>说明:根据指定的属性获取值为Long的属性
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static Long getLong(String key){
String str = props.getProperty(key);
if(MyStringUtil.isBlank(str.trim())){
return null;
}
return Long.valueOf(str.trim());
}
/**
*
* <li>方法名:getInt
* <li>@param key
* <li>@return
* <li>返回类型:Integer
* <li>说明:根据指定的属性获取为Integer类型的值
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static Integer getInt(String key){
String str = props.getProperty(key);
if(MyStringUtil.isBlank(str.trim())){
return null;
}
return Integer.valueOf(str.trim());
}
/**
*
* <li>方法名:getBoolean
* <li>@param key
* <li>@return
* <li>返回类型:Boolean
* <li>说明:获取boolean型参数,0为真,非0为假
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2012-2-29
* <li>修改人:
* <li>修改日期:
*/
public static Boolean getBoolean(String key){
String str = props.getProperty(key);
if(MyStringUtil.isBlank(str)){
return false;
}
return Integer.valueOf(str.trim()) > 0 ? true : false;
}
}
| CshBBrain/CshBBrain | CshBBrain/src/com/jason/Config.java | 1,094 | // 属性
| line_comment | zh-cn | /**
* <li>文件名:Config.java
* <li>说明:
* <li>创建人: CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
package com.jason;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jason.util.MyStringUtil;
/**
* <li>类型名称:
* <li>说明:服务器参数配置文件
* <li>创建人: CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public class Config {
private static Log log = LogFactory.getLog(Config.class);// 日志记录器
private static final String CONFIG_FILE = "config.properties";// 数据库连接池配置文件,支持配置多个数据库链接
private static Properties props = new Properties();// 属性 <SUF>
static{
// 读取配置文件,根据配置文件创建配置信息
try {
InputStream fileInput =Config.class.getResourceAsStream(CONFIG_FILE);
// 加载配置文件
props.load(fileInput);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.info("配置文件不存在,请仔细检查");
} catch (IOException e) {
e.printStackTrace();
log.info("配置文件读取错误");
}
}
/**
*
* <li>方法名:getProperty
* <li>@param key
* <li>@return
* <li>返回类型:String
* <li>说明:获取指定配置信息
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static String getStr(String key){
return props.getProperty(key);
}
/**
*
* <li>方法名:getLong
* <li>@param key
* <li>@return
* <li>返回类型:Long
* <li>说明:根据指定的属性获取值为Long的属性
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static Long getLong(String key){
String str = props.getProperty(key);
if(MyStringUtil.isBlank(str.trim())){
return null;
}
return Long.valueOf(str.trim());
}
/**
*
* <li>方法名:getInt
* <li>@param key
* <li>@return
* <li>返回类型:Integer
* <li>说明:根据指定的属性获取为Integer类型的值
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static Integer getInt(String key){
String str = props.getProperty(key);
if(MyStringUtil.isBlank(str.trim())){
return null;
}
return Integer.valueOf(str.trim());
}
/**
*
* <li>方法名:getBoolean
* <li>@param key
* <li>@return
* <li>返回类型:Boolean
* <li>说明:获取boolean型参数,0为真,非0为假
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2012-2-29
* <li>修改人:
* <li>修改日期:
*/
public static Boolean getBoolean(String key){
String str = props.getProperty(key);
if(MyStringUtil.isBlank(str)){
return false;
}
return Integer.valueOf(str.trim()) > 0 ? true : false;
}
}
| 0 | 7 | 0 |