file_id
stringlengths
5
9
content
stringlengths
24
16.1k
repo
stringlengths
8
84
path
stringlengths
7
167
token_length
int64
18
3.48k
original_comment
stringlengths
5
2.57k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
11
16.1k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
14
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
1.74k
file-tokens-bigcode/starcoder2-7b
int64
18
3.48k
comment-tokens-bigcode/starcoder2-7b
int64
2
2.11k
file-tokens-google/codegemma-7b
int64
14
3.57k
comment-tokens-google/codegemma-7b
int64
2
1.75k
file-tokens-ibm-granite/granite-8b-code-base
int64
18
3.48k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
2.11k
file-tokens-meta-llama/CodeLlama-7b-hf
int64
31
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
2.71k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
54295_15
package 牛客必刷101.二叉树系列; //二叉树的中序遍历 //●给定一颗二叉树的根节点,输出其前序遍历的结果 //方法一:递归(推荐使用) //具体做法: //什么是二叉树的中序遍历,简单来说就是“左根右”,展开来说就是对于一棵二叉树,我们优先访问它的左子树,等到 //左子树全部节点都访问完毕,再访问根节点,最后访问右子树。同时访问子树的时候,顺序也与访问整棵树相同。 //从上述对于中序遍历的解释中,我们不难发现它存在递归的子问题,根节点的左右子树访问方式与原本的树相同,可以 //看成一颗树进行中序遍历,因此可以用递归处理: //●终止条件:当子问题到达叶子节点后,后一个不无识别结果, 因此遇到空节点就返回。 //●返回值:每次处理完子问题后,就是将子问题访问过的元素返回,依次存入了数组中。 //●本级任务:每个子问题优先访问左子树的子问题,等到左子树的结果返回后,再访问自己的根节点,然后进入右 //子树。 //因此处理的时候,过程就是: //●step1: 准备数组用来记录遍历到的节点值,Java可以用List, C++可以直接用vector。 //●step2:从根节点开始进入递归,遇到空节点就返回,否则优先进入左子树进行递归访问。 //●step3: 左子树访问完毕再回到根节点访问。 //●step4:最后进入根节点的右子树进行递归。 import 二叉树.BTNode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static 二叉树.CreateTree.preCreat; public class BM24 { public static class Solution { public void inorder(List<Integer> list, BTNode root){ if(root == null) //遇到空节点则返回 return; inorder(list, root.getlchild()); //先去左子树 list.add(root.getdata()); //再访问根节点 inorder(list, root.getrchild()); //最后去右子树 } public int[] inorderTraversal (BTNode root) { List<Integer> list = new ArrayList(); //添加遍历结果的数组 inorder(list, root); //递归中序遍历 int[] res = new int[list.size()]; //返回的结果 for(int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } } public static void main(String[] args) { BTNode tree = new BTNode(); tree = preCreat(tree); Solution s=new Solution(); int[] res=s.inorderTraversal(tree); System.out.println(Arrays.toString(res)); } }
Tokymin/datasructure_and_algorithm
牛客必刷101/二叉树系列/BM24.java
750
//●step3: 左子树访问完毕再回到根节点访问。
line_comment
zh-cn
package 牛客必刷101.二叉树系列; //二叉树的中序遍历 //●给定一颗二叉树的根节点,输出其前序遍历的结果 //方法一:递归(推荐使用) //具体做法: //什么是二叉树的中序遍历,简单来说就是“左根右”,展开来说就是对于一棵二叉树,我们优先访问它的左子树,等到 //左子树全部节点都访问完毕,再访问根节点,最后访问右子树。同时访问子树的时候,顺序也与访问整棵树相同。 //从上述对于中序遍历的解释中,我们不难发现它存在递归的子问题,根节点的左右子树访问方式与原本的树相同,可以 //看成一颗树进行中序遍历,因此可以用递归处理: //●终止条件:当子问题到达叶子节点后,后一个不无识别结果, 因此遇到空节点就返回。 //●返回值:每次处理完子问题后,就是将子问题访问过的元素返回,依次存入了数组中。 //●本级任务:每个子问题优先访问左子树的子问题,等到左子树的结果返回后,再访问自己的根节点,然后进入右 //子树。 //因此处理的时候,过程就是: //●step1: 准备数组用来记录遍历到的节点值,Java可以用List, C++可以直接用vector。 //●step2:从根节点开始进入递归,遇到空节点就返回,否则优先进入左子树进行递归访问。 //●s <SUF> //●step4:最后进入根节点的右子树进行递归。 import 二叉树.BTNode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static 二叉树.CreateTree.preCreat; public class BM24 { public static class Solution { public void inorder(List<Integer> list, BTNode root){ if(root == null) //遇到空节点则返回 return; inorder(list, root.getlchild()); //先去左子树 list.add(root.getdata()); //再访问根节点 inorder(list, root.getrchild()); //最后去右子树 } public int[] inorderTraversal (BTNode root) { List<Integer> list = new ArrayList(); //添加遍历结果的数组 inorder(list, root); //递归中序遍历 int[] res = new int[list.size()]; //返回的结果 for(int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } } public static void main(String[] args) { BTNode tree = new BTNode(); tree = preCreat(tree); Solution s=new Solution(); int[] res=s.inorderTraversal(tree); System.out.println(Arrays.toString(res)); } }
false
653
17
750
20
701
16
750
20
1,125
30
false
false
false
false
false
true
7597_17
/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon) 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 zblibrary.demo.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.KeyEvent; import zblibrary.demo.DEMO.DemoTabFragment; import zblibrary.demo.R; import zblibrary.demo.fragment.SettingFragment; import zblibrary.demo.fragment.UserListFragment; import zblibrary.demo.fragment.UserRecyclerFragment; import zuo.biao.library.base.BaseBottomTabActivity; import zuo.biao.library.interfaces.OnBottomDragListener; /**应用主页 * @author Lemon * @use MainTabActivity.createIntent(...) */ public class MainTabActivity extends BaseBottomTabActivity implements OnBottomDragListener { // private static final String TAG = "MainTabActivity"; //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**启动这个Activity的Intent * @param context * @return */ public static Intent createIntent(Context context) { return new Intent(context, MainTabActivity.class); } //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_tab_activity, this); //功能归类分区方法,必须调用<<<<<<<<<< initView(); initData(); initEvent(); //功能归类分区方法,必须调用>>>>>>>>>> } // UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< private DemoTabFragment demoTabFragment; @Override public void initView() {// 必须调用 super.initView(); exitAnim = R.anim.bottom_push_out; demoTabFragment = DemoTabFragment.createInstance("杭州"); } @Override protected int[] getTabClickIds() { return new int[]{R.id.llBottomTabTab0, R.id.llBottomTabTab1, R.id.llBottomTabTab2, R.id.llBottomTabTab3}; } @Override protected int[][] getTabSelectIds() { return new int[][]{ new int[]{R.id.ivBottomTabTab0, R.id.ivBottomTabTab1, R.id.ivBottomTabTab2, R.id.ivBottomTabTab3},//顶部图标 new int[]{R.id.tvBottomTabTab0, R.id.tvBottomTabTab1, R.id.tvBottomTabTab2, R.id.tvBottomTabTab3}//底部文字 }; } @Override public int getFragmentContainerResId() { return R.id.flMainTabFragmentContainer; } @Override protected Fragment getFragment(int position) { switch (position) { case 1: return UserRecyclerFragment.createInstance(UserRecyclerFragment.RANGE_RECOMMEND); case 2: return demoTabFragment; case 3: return SettingFragment.createInstance(); default: return UserListFragment.createInstance(UserListFragment.RANGE_ALL); } }; private static final String[] TAB_NAMES = {"主页", "消息", "发现", "设置"}; @Override protected void selectTab(int position) { //导致切换时闪屏,建议去掉BottomTabActivity中的topbar,在fragment中显示topbar // rlBottomTabTopbar.setVisibility(position == 2 ? View.GONE : View.VISIBLE); tvBaseTitle.setText(TAB_NAMES[position]); //点击底部tab切换顶部tab,非必要 if (position == 2 && position == currentPosition && demoTabFragment != null) { demoTabFragment.selectNext(); } } // UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Data数据区(存在数据获取或处理代码,但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initData() {// 必须调用 super.initData(); } // Data数据区(存在数据获取或处理代码,但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initEvent() {// 必须调用 super.initEvent(); } @Override public void onDragBottom(boolean rightToLeft) { //将Activity的onDragBottom事件传递到Fragment,非必要<<<<<<<<<<<<<<<<<<<<<<<<<<< switch (currentPosition) { case 2: if (demoTabFragment != null) { if (rightToLeft) { demoTabFragment.selectMan(); } else { demoTabFragment.selectPlace(); } } break; default: break; } //将Activity的onDragBottom事件传递到Fragment,非必要>>>>>>>>>>>>>>>>>>>>>>>>>>> } //双击手机返回键退出<<<<<<<<<<<<<<<<<<<<< private long firstTime = 0;//第一次返回按钮计时 @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode){ case KeyEvent.KEYCODE_BACK: long secondTime = System.currentTimeMillis(); if(secondTime - firstTime > 2000){ showShortToast("再按一次退出"); firstTime = secondTime; } else {//完全退出 moveTaskToBack(false);//应用退到后台 System.exit(0); } return true; } return super.onKeyUp(keyCode, event); } //双击手机返回键退出>>>>>>>>>>>>>>>>>>>>> //生命周期、onActivityResult<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //生命周期、onActivityResult>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // 内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // 内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> }
TommyLemon/Android-ZBLibrary
app/src/main/java/zblibrary/demo/activity/MainTabActivity.java
1,712
// 必须调用
line_comment
zh-cn
/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon) 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 zblibrary.demo.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.KeyEvent; import zblibrary.demo.DEMO.DemoTabFragment; import zblibrary.demo.R; import zblibrary.demo.fragment.SettingFragment; import zblibrary.demo.fragment.UserListFragment; import zblibrary.demo.fragment.UserRecyclerFragment; import zuo.biao.library.base.BaseBottomTabActivity; import zuo.biao.library.interfaces.OnBottomDragListener; /**应用主页 * @author Lemon * @use MainTabActivity.createIntent(...) */ public class MainTabActivity extends BaseBottomTabActivity implements OnBottomDragListener { // private static final String TAG = "MainTabActivity"; //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**启动这个Activity的Intent * @param context * @return */ public static Intent createIntent(Context context) { return new Intent(context, MainTabActivity.class); } //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_tab_activity, this); //功能归类分区方法,必须调用<<<<<<<<<< initView(); initData(); initEvent(); //功能归类分区方法,必须调用>>>>>>>>>> } // UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< private DemoTabFragment demoTabFragment; @Override public void initView() {// 必须调用 super.initView(); exitAnim = R.anim.bottom_push_out; demoTabFragment = DemoTabFragment.createInstance("杭州"); } @Override protected int[] getTabClickIds() { return new int[]{R.id.llBottomTabTab0, R.id.llBottomTabTab1, R.id.llBottomTabTab2, R.id.llBottomTabTab3}; } @Override protected int[][] getTabSelectIds() { return new int[][]{ new int[]{R.id.ivBottomTabTab0, R.id.ivBottomTabTab1, R.id.ivBottomTabTab2, R.id.ivBottomTabTab3},//顶部图标 new int[]{R.id.tvBottomTabTab0, R.id.tvBottomTabTab1, R.id.tvBottomTabTab2, R.id.tvBottomTabTab3}//底部文字 }; } @Override public int getFragmentContainerResId() { return R.id.flMainTabFragmentContainer; } @Override protected Fragment getFragment(int position) { switch (position) { case 1: return UserRecyclerFragment.createInstance(UserRecyclerFragment.RANGE_RECOMMEND); case 2: return demoTabFragment; case 3: return SettingFragment.createInstance(); default: return UserListFragment.createInstance(UserListFragment.RANGE_ALL); } }; private static final String[] TAB_NAMES = {"主页", "消息", "发现", "设置"}; @Override protected void selectTab(int position) { //导致切换时闪屏,建议去掉BottomTabActivity中的topbar,在fragment中显示topbar // rlBottomTabTopbar.setVisibility(position == 2 ? View.GONE : View.VISIBLE); tvBaseTitle.setText(TAB_NAMES[position]); //点击底部tab切换顶部tab,非必要 if (position == 2 && position == currentPosition && demoTabFragment != null) { demoTabFragment.selectNext(); } } // UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Data数据区(存在数据获取或处理代码,但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initData() {// 必须 <SUF> super.initData(); } // Data数据区(存在数据获取或处理代码,但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initEvent() {// 必须调用 super.initEvent(); } @Override public void onDragBottom(boolean rightToLeft) { //将Activity的onDragBottom事件传递到Fragment,非必要<<<<<<<<<<<<<<<<<<<<<<<<<<< switch (currentPosition) { case 2: if (demoTabFragment != null) { if (rightToLeft) { demoTabFragment.selectMan(); } else { demoTabFragment.selectPlace(); } } break; default: break; } //将Activity的onDragBottom事件传递到Fragment,非必要>>>>>>>>>>>>>>>>>>>>>>>>>>> } //双击手机返回键退出<<<<<<<<<<<<<<<<<<<<< private long firstTime = 0;//第一次返回按钮计时 @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode){ case KeyEvent.KEYCODE_BACK: long secondTime = System.currentTimeMillis(); if(secondTime - firstTime > 2000){ showShortToast("再按一次退出"); firstTime = secondTime; } else {//完全退出 moveTaskToBack(false);//应用退到后台 System.exit(0); } return true; } return super.onKeyUp(keyCode, event); } //双击手机返回键退出>>>>>>>>>>>>>>>>>>>>> //生命周期、onActivityResult<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //生命周期、onActivityResult>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // 内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // 内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> }
false
1,448
7
1,691
5
1,625
5
1,691
5
2,515
9
false
false
false
false
false
true
31523_9
import java.io.*; import java.net.*; public class Server{ // サーバーの最大接続人数 static final int ACCEPTMAX = 2; // サーバーを起動 public void start(int port){ // サーバー ServerSocket server; // 接続しているクライアントの人数 int acceptCount = 0; try{ // サーバーを起動 server = new ServerSocket(port); // サーバー起動を通知 System.out.println("Server Start!! (Port:" + port +")"); // 接続している人数が最大人数未満なら while(acceptCount < ACCEPTMAX){ try{ Socket socket = null; // クライアントを受け入れ socket = server.accept(); // スレッドを作成 new ServerThread(socket).start(); // 接続人数を追加 acceptCount++; }catch(IOException e){ e.printStackTrace(); } } }catch(IOException e){ System.err.println(e); } } public static void main(String[] args){ if(args.length == 1){ int port = Integer.parseInt(args[0]); Server server = new Server(); server.start(port); }else{ System.out.println("引数: ポート番号"); } return; } }
Tomopu/ChatServer
Server.java
319
// 接続人数を追加
line_comment
zh-cn
import java.io.*; import java.net.*; public class Server{ // サーバーの最大接続人数 static final int ACCEPTMAX = 2; // サーバーを起動 public void start(int port){ // サーバー ServerSocket server; // 接続しているクライアントの人数 int acceptCount = 0; try{ // サーバーを起動 server = new ServerSocket(port); // サーバー起動を通知 System.out.println("Server Start!! (Port:" + port +")"); // 接続している人数が最大人数未満なら while(acceptCount < ACCEPTMAX){ try{ Socket socket = null; // クライアントを受け入れ socket = server.accept(); // スレッドを作成 new ServerThread(socket).start(); // 接続 <SUF> acceptCount++; }catch(IOException e){ e.printStackTrace(); } } }catch(IOException e){ System.err.println(e); } } public static void main(String[] args){ if(args.length == 1){ int port = Integer.parseInt(args[0]); Server server = new Server(); server.start(port); }else{ System.out.println("引数: ポート番号"); } return; } }
false
311
8
319
7
332
5
319
7
422
13
false
false
false
false
false
true
45655_2
package oracle; public interface NewSqls { //初始化 String lab_index_d="select instrument,index_id,method,name,sample_from,unitfrom lab_index where " + "instrument like '%XMZ-BN2%'OR instrument like '%XMZ-XP%'"; String l_device_d = "select * from l_device where id in ('XMZ-XP','XMZ-BN2')"; String l_ylxhdescribe_d = "select ylxh,profiletest from l_ylxhdescribe where in ('21','200010')"; String lab_channel_d = "select testid,channel,sampletype from lab_channel where deviceid in ('RL7600','PREMIER300')"; //------------------------------------------------- String l_device = "select * from l_device where id=?"; String l_ylxhdescribe = "select ylxh,profiletest from l_ylxhdescribe where ksdm=?"; String lab_channel = "select testid,channel,sampletype from lab_channel where deviceid=?"; String lab_index="select instrument,index_id,method,name,sample_from,unit from lab_index where instrument like ?"; //查询 String getSampleBy_code = "select sex, sampleno, ylxh, barcode, symstatus from l_sample where barcode=? and rownum<=1"; String getsampleBy_No = "select birthday, sex, sampleno, ylxh, cycle, symstatus from l_sample where sampleno=?"; //保存 String get_checker="select tester from l_tester_set where deviceid=? and segment=?"; String update_sample="update l_sample set auditstatus=?,samplestatus=?,chkoper2=? where sampleno=?"; String has_l_sample_update="select auditstatus,samplestatus from l_sample where sampleno=?"; String hasTestResult_sql = "select * from l_testresult where sampleno=? and testid=? and rownum<=1"; String insert_TestResult = "insert into l_testresult (sampleno,testid,deviceid,measuretime,operator,sampletype," + "testresult,teststatus,unit,testname,method) values(?,?,?,?,?,?,?,?,?,?,?)"; String update_TestResult = "update l_testresult set testresult=?,deviceid=?, measuretime=?,operator=? where sampleno=? and testid=?"; String new_update_result="update l_testresult set testresult=?,measuretime=? where sampleno=? and testid=?"; String getSampleNoByCode="select sex, sampleno,ageunit,cycle,age from L_SAMPLE where barcode=? and rownum<=1"; String insert_TestResult_log="insert into l_testresult_log (sampleno,testid,deviceid,measuretime,operator,sampletype," + "testresult,teststatus,unit,testname,method) values(?,?,?,?,?,?,?,?,?,?,?)"; //监视 String monitor_sql="select * from l_sample where samplestatus=3"; }
TongChuang/BNII
GEM3000/src/oracle/NewSqls.java
731
//查询
line_comment
zh-cn
package oracle; public interface NewSqls { //初始化 String lab_index_d="select instrument,index_id,method,name,sample_from,unitfrom lab_index where " + "instrument like '%XMZ-BN2%'OR instrument like '%XMZ-XP%'"; String l_device_d = "select * from l_device where id in ('XMZ-XP','XMZ-BN2')"; String l_ylxhdescribe_d = "select ylxh,profiletest from l_ylxhdescribe where in ('21','200010')"; String lab_channel_d = "select testid,channel,sampletype from lab_channel where deviceid in ('RL7600','PREMIER300')"; //------------------------------------------------- String l_device = "select * from l_device where id=?"; String l_ylxhdescribe = "select ylxh,profiletest from l_ylxhdescribe where ksdm=?"; String lab_channel = "select testid,channel,sampletype from lab_channel where deviceid=?"; String lab_index="select instrument,index_id,method,name,sample_from,unit from lab_index where instrument like ?"; //查询 <SUF> String getSampleBy_code = "select sex, sampleno, ylxh, barcode, symstatus from l_sample where barcode=? and rownum<=1"; String getsampleBy_No = "select birthday, sex, sampleno, ylxh, cycle, symstatus from l_sample where sampleno=?"; //保存 String get_checker="select tester from l_tester_set where deviceid=? and segment=?"; String update_sample="update l_sample set auditstatus=?,samplestatus=?,chkoper2=? where sampleno=?"; String has_l_sample_update="select auditstatus,samplestatus from l_sample where sampleno=?"; String hasTestResult_sql = "select * from l_testresult where sampleno=? and testid=? and rownum<=1"; String insert_TestResult = "insert into l_testresult (sampleno,testid,deviceid,measuretime,operator,sampletype," + "testresult,teststatus,unit,testname,method) values(?,?,?,?,?,?,?,?,?,?,?)"; String update_TestResult = "update l_testresult set testresult=?,deviceid=?, measuretime=?,operator=? where sampleno=? and testid=?"; String new_update_result="update l_testresult set testresult=?,measuretime=? where sampleno=? and testid=?"; String getSampleNoByCode="select sex, sampleno,ageunit,cycle,age from L_SAMPLE where barcode=? and rownum<=1"; String insert_TestResult_log="insert into l_testresult_log (sampleno,testid,deviceid,measuretime,operator,sampletype," + "testresult,teststatus,unit,testname,method) values(?,?,?,?,?,?,?,?,?,?,?)"; //监视 String monitor_sql="select * from l_sample where samplestatus=3"; }
false
629
3
730
3
731
3
730
3
840
6
false
false
false
false
false
true
32934_1
package com.tongming.jianshu.bean; /** * Created by Tongming on 2016/5/22. */ public class Detail { /** * id : 4059369 * title : 为什么我就是想去大城市受苦受累? - 简书 * content : * comments_count : 433 * url : http://www.jianshu.com/p/e9ba83e9b5d4 * created_at : 2016.05.22 11:25 * views_count : 14280 * slug : e9ba83e9b5d4 * wordage : 2072 * image_url : http://cwb.assets.jianshu.io/notes/images/4059369/weibo/image_c809812e778e.jpg * rewards_total_count : 8 * likes_count : 821 * has_further_readings : false * abbr : 毕业季,面临各种选择,读研?工作?出国?但是无论走哪条路,关于日后的发展总是逃不开这个问题:“你以后想留在哪个城市?”不知从什么时候开始,“逃离北上广”的论调日渐甚嚣尘上,新闻报道的大多是大城市打拼的艰难困苦、小城市安家的逍遥自在,似乎选择“大城小床”可笑而愚蠢,选择“小城大床”才是准确而明智。“阶级固化”理论说,穷人向上流动的成本越来越高、动力越来越小,大城市的每一块砖瓦的缝隙之间都流动着户籍歧视、就业歧视、竞争激烈、人脉至上、拜金主义的冰冷血液,令人胆颤,让人心寒。电影里的大城市,X二代爱上穷人;现实里,X二代碾压穷人。大城里的小床可能第二天就被房东收走,小城里的大床却可以一直为我所... */ private ArticleBean article; /** * uuid : 5079b620-025c-0134-350b-52540095852f */ private UuidBean uuid; /** * id : 1484196 * public_notes_count : 26 * total_likes_count : 10039 * font_count : 51797 * followers_count : 3408 * slug : 2d016299d2b5 * nickname : 李小狼不狼 * is_signed_author : true * is_current_user : false * avatar : http://upload.jianshu.io/users/upload_avatars/1484196/09845ba52f5d.jpg?imageMogr/thumbnail/90x90/quality/100 */ private AuthorBean author; public ArticleBean getArticle() { return article; } public void setArticle(ArticleBean article) { this.article = article; } public UuidBean getUuid() { return uuid; } public void setUuid(UuidBean uuid) { this.uuid = uuid; } public AuthorBean getAuthor() { return author; } public void setAuthor(AuthorBean author) { this.author = author; } public static class ArticleBean { private int id; private String title; private String content; private int comments_count; private String url; private String created_at; private int views_count; private String slug; private int wordage; private String image_url; private int rewards_total_count; private int likes_count; private boolean has_further_readings; private String abbr; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getComments_count() { return comments_count; } public void setComments_count(int comments_count) { this.comments_count = comments_count; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public int getViews_count() { return views_count; } public void setViews_count(int views_count) { this.views_count = views_count; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public int getWordage() { return wordage; } public void setWordage(int wordage) { this.wordage = wordage; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public int getRewards_total_count() { return rewards_total_count; } public void setRewards_total_count(int rewards_total_count) { this.rewards_total_count = rewards_total_count; } public int getLikes_count() { return likes_count; } public void setLikes_count(int likes_count) { this.likes_count = likes_count; } public boolean isHas_further_readings() { return has_further_readings; } public void setHas_further_readings(boolean has_further_readings) { this.has_further_readings = has_further_readings; } public String getAbbr() { return abbr; } public void setAbbr(String abbr) { this.abbr = abbr; } } public static class UuidBean { private String uuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } } public static class AuthorBean { private int id; private int public_notes_count; private int total_likes_count; private String font_count; private int followers_count; private String slug; private String nickname; private boolean is_signed_author; private boolean is_current_user; private String avatar; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPublic_notes_count() { return public_notes_count; } public void setPublic_notes_count(int public_notes_count) { this.public_notes_count = public_notes_count; } public int getTotal_likes_count() { return total_likes_count; } public void setTotal_likes_count(int total_likes_count) { this.total_likes_count = total_likes_count; } public String getFont_count() { return font_count; } public void setFont_count(String font_count) { this.font_count = font_count; } public int getFollowers_count() { return followers_count; } public void setFollowers_count(int followers_count) { this.followers_count = followers_count; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public boolean isIs_signed_author() { return is_signed_author; } public void setIs_signed_author(boolean is_signed_author) { this.is_signed_author = is_signed_author; } public boolean isIs_current_user() { return is_current_user; } public void setIs_current_user(boolean is_current_user) { this.is_current_user = is_current_user; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } } }
TongmingWu/Jianshu
app/src/main/java/com/tongming/jianshu/bean/Detail.java
2,173
/** * id : 4059369 * title : 为什么我就是想去大城市受苦受累? - 简书 * content : * comments_count : 433 * url : http://www.jianshu.com/p/e9ba83e9b5d4 * created_at : 2016.05.22 11:25 * views_count : 14280 * slug : e9ba83e9b5d4 * wordage : 2072 * image_url : http://cwb.assets.jianshu.io/notes/images/4059369/weibo/image_c809812e778e.jpg * rewards_total_count : 8 * likes_count : 821 * has_further_readings : false * abbr : 毕业季,面临各种选择,读研?工作?出国?但是无论走哪条路,关于日后的发展总是逃不开这个问题:“你以后想留在哪个城市?”不知从什么时候开始,“逃离北上广”的论调日渐甚嚣尘上,新闻报道的大多是大城市打拼的艰难困苦、小城市安家的逍遥自在,似乎选择“大城小床”可笑而愚蠢,选择“小城大床”才是准确而明智。“阶级固化”理论说,穷人向上流动的成本越来越高、动力越来越小,大城市的每一块砖瓦的缝隙之间都流动着户籍歧视、就业歧视、竞争激烈、人脉至上、拜金主义的冰冷血液,令人胆颤,让人心寒。电影里的大城市,X二代爱上穷人;现实里,X二代碾压穷人。大城里的小床可能第二天就被房东收走,小城里的大床却可以一直为我所... */
block_comment
zh-cn
package com.tongming.jianshu.bean; /** * Created by Tongming on 2016/5/22. */ public class Detail { /** * id <SUF>*/ private ArticleBean article; /** * uuid : 5079b620-025c-0134-350b-52540095852f */ private UuidBean uuid; /** * id : 1484196 * public_notes_count : 26 * total_likes_count : 10039 * font_count : 51797 * followers_count : 3408 * slug : 2d016299d2b5 * nickname : 李小狼不狼 * is_signed_author : true * is_current_user : false * avatar : http://upload.jianshu.io/users/upload_avatars/1484196/09845ba52f5d.jpg?imageMogr/thumbnail/90x90/quality/100 */ private AuthorBean author; public ArticleBean getArticle() { return article; } public void setArticle(ArticleBean article) { this.article = article; } public UuidBean getUuid() { return uuid; } public void setUuid(UuidBean uuid) { this.uuid = uuid; } public AuthorBean getAuthor() { return author; } public void setAuthor(AuthorBean author) { this.author = author; } public static class ArticleBean { private int id; private String title; private String content; private int comments_count; private String url; private String created_at; private int views_count; private String slug; private int wordage; private String image_url; private int rewards_total_count; private int likes_count; private boolean has_further_readings; private String abbr; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getComments_count() { return comments_count; } public void setComments_count(int comments_count) { this.comments_count = comments_count; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public int getViews_count() { return views_count; } public void setViews_count(int views_count) { this.views_count = views_count; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public int getWordage() { return wordage; } public void setWordage(int wordage) { this.wordage = wordage; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public int getRewards_total_count() { return rewards_total_count; } public void setRewards_total_count(int rewards_total_count) { this.rewards_total_count = rewards_total_count; } public int getLikes_count() { return likes_count; } public void setLikes_count(int likes_count) { this.likes_count = likes_count; } public boolean isHas_further_readings() { return has_further_readings; } public void setHas_further_readings(boolean has_further_readings) { this.has_further_readings = has_further_readings; } public String getAbbr() { return abbr; } public void setAbbr(String abbr) { this.abbr = abbr; } } public static class UuidBean { private String uuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } } public static class AuthorBean { private int id; private int public_notes_count; private int total_likes_count; private String font_count; private int followers_count; private String slug; private String nickname; private boolean is_signed_author; private boolean is_current_user; private String avatar; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPublic_notes_count() { return public_notes_count; } public void setPublic_notes_count(int public_notes_count) { this.public_notes_count = public_notes_count; } public int getTotal_likes_count() { return total_likes_count; } public void setTotal_likes_count(int total_likes_count) { this.total_likes_count = total_likes_count; } public String getFont_count() { return font_count; } public void setFont_count(String font_count) { this.font_count = font_count; } public int getFollowers_count() { return followers_count; } public void setFollowers_count(int followers_count) { this.followers_count = followers_count; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public boolean isIs_signed_author() { return is_signed_author; } public void setIs_signed_author(boolean is_signed_author) { this.is_signed_author = is_signed_author; } public boolean isIs_current_user() { return is_current_user; } public void setIs_current_user(boolean is_current_user) { this.is_current_user = is_current_user; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } } }
false
1,830
411
2,173
546
2,266
449
2,173
546
2,722
716
true
true
true
true
true
false
22940_2
package crawler; public enum FinalMatchStatusEnum { ZERO("状态零"), // 无精确结果,放弃;对该资源匹配状态标记为状态0 ONE("状态一"), // 精准匹配MV名,未匹配歌手名,标记为状态1 TWO("状态二"), // 精确匹配MV名和艺人名,标记为状态2 THREE("状态三"), // 虾米音乐歌名包含音悦台歌名,标记为状态3 FOUR("状态四"); // 音悦台歌名包含虾米音乐歌名,标记为状态4 public String name; private FinalMatchStatusEnum(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Tongzhenguo/Java-codes
src/main/java/crawler/FinalMatchStatusEnum.java
214
// 精确匹配MV名和艺人名,标记为状态2
line_comment
zh-cn
package crawler; public enum FinalMatchStatusEnum { ZERO("状态零"), // 无精确结果,放弃;对该资源匹配状态标记为状态0 ONE("状态一"), // 精准匹配MV名,未匹配歌手名,标记为状态1 TWO("状态二"), // 精确 <SUF> THREE("状态三"), // 虾米音乐歌名包含音悦台歌名,标记为状态3 FOUR("状态四"); // 音悦台歌名包含虾米音乐歌名,标记为状态4 public String name; private FinalMatchStatusEnum(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
false
182
16
214
16
192
14
214
16
285
26
false
false
false
false
false
true
37699_5
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; /** * Created by tongxiaotuo on 16/9/1. * 工具类 包括文件读取等等 */ public class Tools { /** * 文件读取(内存映射方式) * * @param filePath 文件的路径 * @return 返回一个String类型的字符串 * @throws IOException 抛出异常 */ public static String readInString(File filePath) throws IOException { FileInputStream in = new FileInputStream(filePath); FileChannel chan = in.getChannel(); MappedByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, filePath.length()); byte[] b = new byte[(int) filePath.length()]; int len = 0; while (buf.hasRemaining()) { b[len] = buf.get(); len++; } chan.close(); in.close(); return new String(b, 0, len, "GBK"); } public static void writeInString(String fileName, String content) { try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE}; public static int sizeOfInt(int x) { for (int i = 0; ; i++) if (x <= sizeTable[i]) return i + 1; } /** * 把文件里面的数字组成一个二维Node链表 * Node包含它的头结点和它的一堆尾节点 * * @param filePath 表示从文件里面读取的数值 * @return 一个带头结点和尾节点的二维Node链表 */ public static ArrayList<ArrayList<Node[]>> getNodesListFromText(File filePath) throws IOException { String nodesFronText = readInString(filePath); Node firstNodeHeadNode = new Node("-2"); //默认第一个结点的头结点为-2 Node defaultHeadNode = new Node("-3"); //默认头结点为-3 String lineNumbersOfArray[] = nodesFronText.split("\n"); int arrayListnumbers = lineNumbersOfArray.length; int time; Node nodesList[][] = new Node[arrayListnumbers][]; //控制行数 for (int i = 0; i < arrayListnumbers; i++) { String numbersListForTime[] = lineNumbersOfArray[i].split(" |\r"); time = Integer.parseInt(numbersListForTime[0]);//需要删除第一个数 lineNumbersOfArray[i] = lineNumbersOfArray[i].substring(sizeOfInt(time) + 1);//删除后添加的时间和空格 String numbersList[] = lineNumbersOfArray[i].split(" |\r"); //一行有几个数 nodesList[i] = new Node[numbersList.length - 3]; //每行去掉前三个数 for (int j = 0; j < numbersList.length - 3; j++) { nodesList[i][j] = new Node(String.valueOf(numbersList[j + 3]), time); //每一个Node不仅仅是一个数值而是一个对象 nodesList[i][j].setNodeHead(defaultHeadNode); //合并功能 if (j != nodesList[i].length - 1) { if (j == 0) { nodesList[i][j].setNodeHead(firstNodeHeadNode); //头结点添加firstNodeHeadNode } else { if (!nodesList[i][j].getNodenumber().equals("-1")) { nodesList[i][j].setNodeHead(nodesList[i][j - 1]); //如果后面的数不是-1,直接连接 nodesList[i][j - 1].addNodeTail(nodesList[i][j]); } if (nodesList[i][j].getNodenumber().equals("-1")) { //如果是-1,根据-1的次数来判定位置 //这里numberOfLayer表示-1出现了几次 出现几次就找几次nodesList[i][j - 1].getNodeHead() int numberOfLayer = 1; for (int k = j + 1; k < nodesList[i].length - 1; k++) { if (numbersList[k + 3].equals("-1")) { numberOfLayer++; } else { break; } } if (j + numberOfLayer != nodesList[i].length - 1) { //如果是最后一个位置,即-1时候,默认头结点 排除最后一个位置 Node node = nodesList[i][j - 1].getNodeHead(); //这个循环是为了循环找getNodeHead for (int num = 1; num < numberOfLayer; num++) { node = node.getNodeHead(); nodesList[i][j + num] = new Node(String.valueOf(numbersList[j + 3 + num]), time); //这里新建跳过的-1节点 } nodesList[i][j + numberOfLayer] = new Node(String.valueOf(numbersList[j + 3 + numberOfLayer]), time); nodesList[i][j + numberOfLayer].setNodeHead(node); node.addNodeTail(nodesList[i][j + numberOfLayer]); j += numberOfLayer; } } } } } } ArrayList<ArrayList<Node[]>> nodesListWithtime = new ArrayList<ArrayList<Node[]>>(); ArrayList<Node[]> test = new ArrayList<Node[]>(); int j = 0; int size = nodesList[nodesList.length - 1][0].getTime(); for (int i = 0; i < size; i++) { for (; j < nodesList.length; j++) { if (nodesList[j][0].getTime() == i + 1) { test.add(nodesList[j]); } else { nodesListWithtime.add((ArrayList<Node[]>) test.clone()); test.clear(); break; } } } nodesListWithtime.add(test); return nodesListWithtime; } /** * 读取node头节点信息 * * @param node 头节点 */ public static void readHeadNode(Node node) { System.out.println("当前节点是:" + node.nodenumber); for (Node n : node.getArrayListNodeTail()) { readHeadNode(n); } } }
Tongziqi/CITMiner
src/Tools.java
1,627
//默认头结点为-3
line_comment
zh-cn
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; /** * Created by tongxiaotuo on 16/9/1. * 工具类 包括文件读取等等 */ public class Tools { /** * 文件读取(内存映射方式) * * @param filePath 文件的路径 * @return 返回一个String类型的字符串 * @throws IOException 抛出异常 */ public static String readInString(File filePath) throws IOException { FileInputStream in = new FileInputStream(filePath); FileChannel chan = in.getChannel(); MappedByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, filePath.length()); byte[] b = new byte[(int) filePath.length()]; int len = 0; while (buf.hasRemaining()) { b[len] = buf.get(); len++; } chan.close(); in.close(); return new String(b, 0, len, "GBK"); } public static void writeInString(String fileName, String content) { try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE}; public static int sizeOfInt(int x) { for (int i = 0; ; i++) if (x <= sizeTable[i]) return i + 1; } /** * 把文件里面的数字组成一个二维Node链表 * Node包含它的头结点和它的一堆尾节点 * * @param filePath 表示从文件里面读取的数值 * @return 一个带头结点和尾节点的二维Node链表 */ public static ArrayList<ArrayList<Node[]>> getNodesListFromText(File filePath) throws IOException { String nodesFronText = readInString(filePath); Node firstNodeHeadNode = new Node("-2"); //默认第一个结点的头结点为-2 Node defaultHeadNode = new Node("-3"); //默认 <SUF> String lineNumbersOfArray[] = nodesFronText.split("\n"); int arrayListnumbers = lineNumbersOfArray.length; int time; Node nodesList[][] = new Node[arrayListnumbers][]; //控制行数 for (int i = 0; i < arrayListnumbers; i++) { String numbersListForTime[] = lineNumbersOfArray[i].split(" |\r"); time = Integer.parseInt(numbersListForTime[0]);//需要删除第一个数 lineNumbersOfArray[i] = lineNumbersOfArray[i].substring(sizeOfInt(time) + 1);//删除后添加的时间和空格 String numbersList[] = lineNumbersOfArray[i].split(" |\r"); //一行有几个数 nodesList[i] = new Node[numbersList.length - 3]; //每行去掉前三个数 for (int j = 0; j < numbersList.length - 3; j++) { nodesList[i][j] = new Node(String.valueOf(numbersList[j + 3]), time); //每一个Node不仅仅是一个数值而是一个对象 nodesList[i][j].setNodeHead(defaultHeadNode); //合并功能 if (j != nodesList[i].length - 1) { if (j == 0) { nodesList[i][j].setNodeHead(firstNodeHeadNode); //头结点添加firstNodeHeadNode } else { if (!nodesList[i][j].getNodenumber().equals("-1")) { nodesList[i][j].setNodeHead(nodesList[i][j - 1]); //如果后面的数不是-1,直接连接 nodesList[i][j - 1].addNodeTail(nodesList[i][j]); } if (nodesList[i][j].getNodenumber().equals("-1")) { //如果是-1,根据-1的次数来判定位置 //这里numberOfLayer表示-1出现了几次 出现几次就找几次nodesList[i][j - 1].getNodeHead() int numberOfLayer = 1; for (int k = j + 1; k < nodesList[i].length - 1; k++) { if (numbersList[k + 3].equals("-1")) { numberOfLayer++; } else { break; } } if (j + numberOfLayer != nodesList[i].length - 1) { //如果是最后一个位置,即-1时候,默认头结点 排除最后一个位置 Node node = nodesList[i][j - 1].getNodeHead(); //这个循环是为了循环找getNodeHead for (int num = 1; num < numberOfLayer; num++) { node = node.getNodeHead(); nodesList[i][j + num] = new Node(String.valueOf(numbersList[j + 3 + num]), time); //这里新建跳过的-1节点 } nodesList[i][j + numberOfLayer] = new Node(String.valueOf(numbersList[j + 3 + numberOfLayer]), time); nodesList[i][j + numberOfLayer].setNodeHead(node); node.addNodeTail(nodesList[i][j + numberOfLayer]); j += numberOfLayer; } } } } } } ArrayList<ArrayList<Node[]>> nodesListWithtime = new ArrayList<ArrayList<Node[]>>(); ArrayList<Node[]> test = new ArrayList<Node[]>(); int j = 0; int size = nodesList[nodesList.length - 1][0].getTime(); for (int i = 0; i < size; i++) { for (; j < nodesList.length; j++) { if (nodesList[j][0].getTime() == i + 1) { test.add(nodesList[j]); } else { nodesListWithtime.add((ArrayList<Node[]>) test.clone()); test.clear(); break; } } } nodesListWithtime.add(test); return nodesListWithtime; } /** * 读取node头节点信息 * * @param node 头节点 */ public static void readHeadNode(Node node) { System.out.println("当前节点是:" + node.nodenumber); for (Node n : node.getArrayListNodeTail()) { readHeadNode(n); } } }
false
1,500
8
1,627
7
1,714
8
1,627
7
2,044
9
false
false
false
false
false
true
26477_0
class Solution { /** * 解题思路双指针 * 每当指针值不同时,慢指针更改 * * @param nums * @return //给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。 * // * // 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 ¡ */ public static int removeDuplicates(int[] nums) { int i = 0; int j = 1; for (; j < nums.length; j++) { if (nums[i] == nums[j]) { } else { i++; nums[i] = nums[j]; } } return i + 1; } /** * 一个自己写的删除重复值的函数方法 * 尼玛 审题很重要 * 第一个是有序数组!!!! * 第二个是 返回删除后数组的新长度 这尼玛就是个坑啊 这尼玛不是要你删除重复的 就只是要你找下的有多少不重复的 * 元,不重复数量就++ 最后返回这个数值的长度就可以了 根本就不是让你返回数组的长度 * 出题的人该拉出去毙了 * * @param nums 数组 * @return intj */ public static int oneSelfWritingRemoveDuplicates(int[] nums) { if (nums.length == 0 || nums.length == 1) { return nums.length; } int slowPointer = 0; int quickPointer = 1; for (; quickPointer < nums.length; quickPointer++) { if (nums[quickPointer] != nums[slowPointer]) { slowPointer++; nums[slowPointer] = nums[quickPointer]; } } return slowPointer + 1; } public static void main(String[] args) { int[] nums = {1, 2, 2, 4, 5, 6, 6, 7,}; System.out.println(oneSelfWritingRemoveDuplicates(nums)); } }
TonyStarkShaDiao/algorithm
src/aaa.java
518
/** * 解题思路双指针 * 每当指针值不同时,慢指针更改 * * @param nums * @return //给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。 * // * // 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 ¡ */
block_comment
zh-cn
class Solution { /** * 解题思 <SUF>*/ public static int removeDuplicates(int[] nums) { int i = 0; int j = 1; for (; j < nums.length; j++) { if (nums[i] == nums[j]) { } else { i++; nums[i] = nums[j]; } } return i + 1; } /** * 一个自己写的删除重复值的函数方法 * 尼玛 审题很重要 * 第一个是有序数组!!!! * 第二个是 返回删除后数组的新长度 这尼玛就是个坑啊 这尼玛不是要你删除重复的 就只是要你找下的有多少不重复的 * 元,不重复数量就++ 最后返回这个数值的长度就可以了 根本就不是让你返回数组的长度 * 出题的人该拉出去毙了 * * @param nums 数组 * @return intj */ public static int oneSelfWritingRemoveDuplicates(int[] nums) { if (nums.length == 0 || nums.length == 1) { return nums.length; } int slowPointer = 0; int quickPointer = 1; for (; quickPointer < nums.length; quickPointer++) { if (nums[quickPointer] != nums[slowPointer]) { slowPointer++; nums[slowPointer] = nums[quickPointer]; } } return slowPointer + 1; } public static void main(String[] args) { int[] nums = {1, 2, 2, 4, 5, 6, 6, 7,}; System.out.println(oneSelfWritingRemoveDuplicates(nums)); } }
false
498
117
518
113
530
108
518
113
717
173
false
false
false
false
false
true
61127_2
/******************************************************************************* * Copyright (c) 2015 btows.com. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.cleanwiz.applock.files.activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.TextView; import com.cleanwiz.applock.R; import com.cleanwiz.applock.files.adapter.BaseHideAdapter; import com.cleanwiz.applock.ui.BaseActivity; import com.cleanwiz.applock.ui.activity.LockMainActivity; import com.cleanwiz.applock.ui.widget.actionview.ActionView; import com.cleanwiz.applock.ui.widget.actionview.BackAction; import com.cleanwiz.applock.ui.widget.actionview.CloseAction; import com.gc.materialdesign.views.CheckBox; import com.gc.materialdesign.widgets.Dialog; import java.util.List; /** * Created by dev on 2015/4/30. */ public abstract class BaseHideActivity extends BaseActivity implements BaseHideAdapter.OnListener { protected static final String TAG = "BaseHideActivity"; static final float ALPHA_DISABLE = 0.3f; static final float ALPHA_ENABLE = 1.0f; //按钮图层容器(切换状态) protected View mPic_hide_btn_preview; protected View mPic_hide_btn_edit; protected BaseHideAdapter mBaseHideAdapter; protected ActionView mBtn_back; protected CheckBox mCheckBox;//全选按钮 protected View mHide_btn_add; protected View mPic_hide_img_recovery;//恢复选中的内容 protected View mPic_hide_img_del;//彻底删除选中的内容 protected TextView mFile_hide_txt_title;//标题头 protected TextView mFile_bottom_txt_tips;//底部提示添加内容 protected View mFile_bottom_layout_tips;//底部提示添加内容 private int mRid_title_txt; private int mRid_title_txt_edit; /***/ protected int rid_string_type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initUI(); initAdapter(); } @Override protected void onDestroy() { if (mBaseHideAdapter != null) { mBaseHideAdapter.clear(); } super.onDestroy(); } abstract void initAdapter(); /** * 初始化UI设置 */ protected void initUI() { setContentView(R.layout.activity_file_hide); setUI(); } protected void setUI() { mPic_hide_btn_preview = findViewById(R.id.pic_hide_btn_preview); mPic_hide_btn_edit = findViewById(R.id.pic_hide_btn_edit); mBtn_back = (ActionView) findViewById(R.id.btn_back); mHide_btn_add = findViewById(R.id.hide_btn_add); mPic_hide_img_recovery = findViewById(R.id.pic_hide_img_recovery); mPic_hide_img_del = findViewById(R.id.pic_hide_img_del); mFile_hide_txt_title = (TextView) findViewById(R.id.file_hide_txt_title); mFile_bottom_txt_tips = (TextView) findViewById(R.id.file_bottom_txt_tips); mFile_bottom_layout_tips = findViewById(R.id.file_bottom_layout_tips); mCheckBox = (CheckBox) findViewById(R.id.item_file_checkbox); if (mCheckBox != null) mCheckBox.setOncheckListener(new CheckBox.OnCheckListener() { @Override public void onCheck(boolean check) { CheckBox checkBox = (CheckBox) findViewById(R.id.item_file_checkbox); selectAll(checkBox.isCheck()); } }); } /** * 设置资源id * * @param rid */ protected void setTitleRID(int rid, int ridEdit) { mRid_title_txt = rid; mRid_title_txt_edit = ridEdit; } @Override protected void onResume() { super.onResume(); setEditState(false); mCheckBox.setCheckedNoAnim(false); setSelect(false); openHolder(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.hide_btn_add://添加新文件 addFile(); break; case R.id.item_file_checkbox://全选/反选 selectAll(mCheckBox.isCheck()); break; case R.id.btn_back://返回 if (!onBack()) { finish(); onHome(); } break; case R.id.pic_hide_img_recovery://恢复选中的内容 if (v.getAlpha() == ALPHA_ENABLE) { recoveryDialog(); } break; case R.id.pic_hide_img_del://彻底删除选中的内容 if (v.getAlpha() == ALPHA_ENABLE) { delDialog(); } break; case R.id.pic_hide_btn_preview://预览状态切换到编辑状态 if (mPic_hide_btn_preview.getAlpha() == ALPHA_ENABLE) { setEditState(true); } break; case R.id.pic_hide_btn_edit://切换编辑状态 setEditState(false); break; } } protected void delDialog() { final Dialog dialog = new Dialog( this, ((getString(R.string.file_dialog_del)) + getString(rid_string_type)), getString(rid_string_type) + getString(R.string.file_dialog_del_missage) ); dialog.setOnAcceptButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { delFiles(); setEditState(false); openHolder(); } }); dialog.addCancelButton( getString(R.string.lock_cancel), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); dialog.getButtonAccept().setText(getString(R.string.lock_ok)); } /** * 恢复选中内容 */ protected void recoveryDialog() { final Dialog dialog = new Dialog( this, ((getString(R.string.file_dialog_recovery)) + getString(rid_string_type)), getString(rid_string_type) + getString(R.string.file_dialog_recovery_missage) ); dialog.setOnAcceptButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recoveryFiles(); setEditState(false); openHolder(); } }); dialog.addCancelButton( getString(R.string.lock_cancel), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); dialog.getButtonAccept().setText(getString(R.string.lock_ok)); } /** * 彻底删除选中的文件 */ protected abstract void delFiles(); /** * 全选切换 * * @param enable */ protected void selectAll(boolean enable) { mBaseHideAdapter.selectAll(enable); } /** * 返回主页面 */ private void onHome() { this.startActivity(new Intent(this, LockMainActivity.class)); } /** * 添加文件夹 */ abstract void addFolder(); /** * 删除文件夹(已选中的)同时恢复文件夹内的所有文件 * * @return */ abstract boolean delFolder(); /** * 恢复隐藏的文件 */ abstract void recoveryFiles(); /** * 添加新内容 */ abstract void addFile(); @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (onBack()) return true; } onHome(); return true; } /** * 返回/退出页面 * * @return 是否停留 */ protected boolean onBack() { if (!mBaseHideAdapter.isRoot()) { openHolder(mBaseHideAdapter.getGruopParentID()); return true; } // 切换为返回状态 if (mBtn_back.getAction() instanceof CloseAction) { setEditState(false); return true; } return false; } /** * 重新初始化列表数据 */ protected void openHolder() { openHolder(mBaseHideAdapter.getGruopID()); } /** * 打开指定分组内容 * * @param groupID */ abstract void openHolder(int groupID); /** * 是否编辑状态 */ private boolean mIsEdit; /** * 设置当前状态 * * @param isEdit (编辑/预览) */ protected void setEditState(boolean isEdit) { mIsEdit = isEdit; mBaseHideAdapter.setEditState(isEdit); if (isEdit) { mPic_hide_btn_preview.setVisibility(View.GONE); mPic_hide_btn_edit.setVisibility(View.VISIBLE); mBtn_back.setAction(new CloseAction(), ActionView.ROTATE_COUNTER_CLOCKWISE); mHide_btn_add.setVisibility(View.GONE); mFile_hide_txt_title.setText(""); } else { mPic_hide_btn_preview.setVisibility(View.VISIBLE); mPic_hide_btn_edit.setVisibility(View.GONE); mBtn_back.setAction(new BackAction(), ActionView.ROTATE_CLOCKWISE); mHide_btn_add.setVisibility(View.VISIBLE); mFile_hide_txt_title.setText(mRid_title_txt); } } public boolean isEditState() { return mIsEdit; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { // 恢复 boolean save = savedInstanceState.getBoolean("save"); if (save) { int gruopID = savedInstanceState.getInt("groupID"); mBaseHideAdapter.clear(); openHolder(gruopID); } else openHolder(); super.onRestoreInstanceState(savedInstanceState); } @Override protected void onSaveInstanceState(Bundle outState) { // 保存信息 boolean save = mBaseHideAdapter.isRoot(); outState.putBoolean("save", !mBaseHideAdapter.isRoot()); if (save) { outState.putInt("groupID", mBaseHideAdapter.getGruopID()); } super.onSaveInstanceState(outState); } @Override public void onLongClick(BaseHideAdapter.IEnable iEnable) { setEditState(true); mBaseHideAdapter.setSelect(iEnable); setSelect(true); } public void setSelect(boolean selected) { if (selected) { mPic_hide_img_recovery.setAlpha(ALPHA_ENABLE); mPic_hide_img_del.setAlpha(ALPHA_ENABLE); } else { mPic_hide_img_recovery.setAlpha(ALPHA_DISABLE); mPic_hide_img_del.setAlpha(ALPHA_DISABLE); } } /** * 设置是否有数据 * * @param groupList * @param list */ protected void setHasData(List<?> groupList, List<?> list) { boolean hasData = false; if (groupList != null && groupList.size() > 0 || list != null && list.size() > 0) hasData = true; if (hasData) { mPic_hide_btn_preview.setAlpha(ALPHA_ENABLE); mFile_bottom_layout_tips.setVisibility(View.GONE); } else { mPic_hide_btn_preview.setAlpha(ALPHA_DISABLE); if (mIsEdit) mFile_bottom_layout_tips.setVisibility(View.GONE); else mFile_bottom_layout_tips.setVisibility(View.VISIBLE); } } }
Toolwiz/ToolWizAppLock
src/com/cleanwiz/applock/files/activity/BaseHideActivity.java
3,006
//按钮图层容器(切换状态)
line_comment
zh-cn
/******************************************************************************* * Copyright (c) 2015 btows.com. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.cleanwiz.applock.files.activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.TextView; import com.cleanwiz.applock.R; import com.cleanwiz.applock.files.adapter.BaseHideAdapter; import com.cleanwiz.applock.ui.BaseActivity; import com.cleanwiz.applock.ui.activity.LockMainActivity; import com.cleanwiz.applock.ui.widget.actionview.ActionView; import com.cleanwiz.applock.ui.widget.actionview.BackAction; import com.cleanwiz.applock.ui.widget.actionview.CloseAction; import com.gc.materialdesign.views.CheckBox; import com.gc.materialdesign.widgets.Dialog; import java.util.List; /** * Created by dev on 2015/4/30. */ public abstract class BaseHideActivity extends BaseActivity implements BaseHideAdapter.OnListener { protected static final String TAG = "BaseHideActivity"; static final float ALPHA_DISABLE = 0.3f; static final float ALPHA_ENABLE = 1.0f; //按钮 <SUF> protected View mPic_hide_btn_preview; protected View mPic_hide_btn_edit; protected BaseHideAdapter mBaseHideAdapter; protected ActionView mBtn_back; protected CheckBox mCheckBox;//全选按钮 protected View mHide_btn_add; protected View mPic_hide_img_recovery;//恢复选中的内容 protected View mPic_hide_img_del;//彻底删除选中的内容 protected TextView mFile_hide_txt_title;//标题头 protected TextView mFile_bottom_txt_tips;//底部提示添加内容 protected View mFile_bottom_layout_tips;//底部提示添加内容 private int mRid_title_txt; private int mRid_title_txt_edit; /***/ protected int rid_string_type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initUI(); initAdapter(); } @Override protected void onDestroy() { if (mBaseHideAdapter != null) { mBaseHideAdapter.clear(); } super.onDestroy(); } abstract void initAdapter(); /** * 初始化UI设置 */ protected void initUI() { setContentView(R.layout.activity_file_hide); setUI(); } protected void setUI() { mPic_hide_btn_preview = findViewById(R.id.pic_hide_btn_preview); mPic_hide_btn_edit = findViewById(R.id.pic_hide_btn_edit); mBtn_back = (ActionView) findViewById(R.id.btn_back); mHide_btn_add = findViewById(R.id.hide_btn_add); mPic_hide_img_recovery = findViewById(R.id.pic_hide_img_recovery); mPic_hide_img_del = findViewById(R.id.pic_hide_img_del); mFile_hide_txt_title = (TextView) findViewById(R.id.file_hide_txt_title); mFile_bottom_txt_tips = (TextView) findViewById(R.id.file_bottom_txt_tips); mFile_bottom_layout_tips = findViewById(R.id.file_bottom_layout_tips); mCheckBox = (CheckBox) findViewById(R.id.item_file_checkbox); if (mCheckBox != null) mCheckBox.setOncheckListener(new CheckBox.OnCheckListener() { @Override public void onCheck(boolean check) { CheckBox checkBox = (CheckBox) findViewById(R.id.item_file_checkbox); selectAll(checkBox.isCheck()); } }); } /** * 设置资源id * * @param rid */ protected void setTitleRID(int rid, int ridEdit) { mRid_title_txt = rid; mRid_title_txt_edit = ridEdit; } @Override protected void onResume() { super.onResume(); setEditState(false); mCheckBox.setCheckedNoAnim(false); setSelect(false); openHolder(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.hide_btn_add://添加新文件 addFile(); break; case R.id.item_file_checkbox://全选/反选 selectAll(mCheckBox.isCheck()); break; case R.id.btn_back://返回 if (!onBack()) { finish(); onHome(); } break; case R.id.pic_hide_img_recovery://恢复选中的内容 if (v.getAlpha() == ALPHA_ENABLE) { recoveryDialog(); } break; case R.id.pic_hide_img_del://彻底删除选中的内容 if (v.getAlpha() == ALPHA_ENABLE) { delDialog(); } break; case R.id.pic_hide_btn_preview://预览状态切换到编辑状态 if (mPic_hide_btn_preview.getAlpha() == ALPHA_ENABLE) { setEditState(true); } break; case R.id.pic_hide_btn_edit://切换编辑状态 setEditState(false); break; } } protected void delDialog() { final Dialog dialog = new Dialog( this, ((getString(R.string.file_dialog_del)) + getString(rid_string_type)), getString(rid_string_type) + getString(R.string.file_dialog_del_missage) ); dialog.setOnAcceptButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { delFiles(); setEditState(false); openHolder(); } }); dialog.addCancelButton( getString(R.string.lock_cancel), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); dialog.getButtonAccept().setText(getString(R.string.lock_ok)); } /** * 恢复选中内容 */ protected void recoveryDialog() { final Dialog dialog = new Dialog( this, ((getString(R.string.file_dialog_recovery)) + getString(rid_string_type)), getString(rid_string_type) + getString(R.string.file_dialog_recovery_missage) ); dialog.setOnAcceptButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recoveryFiles(); setEditState(false); openHolder(); } }); dialog.addCancelButton( getString(R.string.lock_cancel), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); dialog.getButtonAccept().setText(getString(R.string.lock_ok)); } /** * 彻底删除选中的文件 */ protected abstract void delFiles(); /** * 全选切换 * * @param enable */ protected void selectAll(boolean enable) { mBaseHideAdapter.selectAll(enable); } /** * 返回主页面 */ private void onHome() { this.startActivity(new Intent(this, LockMainActivity.class)); } /** * 添加文件夹 */ abstract void addFolder(); /** * 删除文件夹(已选中的)同时恢复文件夹内的所有文件 * * @return */ abstract boolean delFolder(); /** * 恢复隐藏的文件 */ abstract void recoveryFiles(); /** * 添加新内容 */ abstract void addFile(); @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (onBack()) return true; } onHome(); return true; } /** * 返回/退出页面 * * @return 是否停留 */ protected boolean onBack() { if (!mBaseHideAdapter.isRoot()) { openHolder(mBaseHideAdapter.getGruopParentID()); return true; } // 切换为返回状态 if (mBtn_back.getAction() instanceof CloseAction) { setEditState(false); return true; } return false; } /** * 重新初始化列表数据 */ protected void openHolder() { openHolder(mBaseHideAdapter.getGruopID()); } /** * 打开指定分组内容 * * @param groupID */ abstract void openHolder(int groupID); /** * 是否编辑状态 */ private boolean mIsEdit; /** * 设置当前状态 * * @param isEdit (编辑/预览) */ protected void setEditState(boolean isEdit) { mIsEdit = isEdit; mBaseHideAdapter.setEditState(isEdit); if (isEdit) { mPic_hide_btn_preview.setVisibility(View.GONE); mPic_hide_btn_edit.setVisibility(View.VISIBLE); mBtn_back.setAction(new CloseAction(), ActionView.ROTATE_COUNTER_CLOCKWISE); mHide_btn_add.setVisibility(View.GONE); mFile_hide_txt_title.setText(""); } else { mPic_hide_btn_preview.setVisibility(View.VISIBLE); mPic_hide_btn_edit.setVisibility(View.GONE); mBtn_back.setAction(new BackAction(), ActionView.ROTATE_CLOCKWISE); mHide_btn_add.setVisibility(View.VISIBLE); mFile_hide_txt_title.setText(mRid_title_txt); } } public boolean isEditState() { return mIsEdit; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { // 恢复 boolean save = savedInstanceState.getBoolean("save"); if (save) { int gruopID = savedInstanceState.getInt("groupID"); mBaseHideAdapter.clear(); openHolder(gruopID); } else openHolder(); super.onRestoreInstanceState(savedInstanceState); } @Override protected void onSaveInstanceState(Bundle outState) { // 保存信息 boolean save = mBaseHideAdapter.isRoot(); outState.putBoolean("save", !mBaseHideAdapter.isRoot()); if (save) { outState.putInt("groupID", mBaseHideAdapter.getGruopID()); } super.onSaveInstanceState(outState); } @Override public void onLongClick(BaseHideAdapter.IEnable iEnable) { setEditState(true); mBaseHideAdapter.setSelect(iEnable); setSelect(true); } public void setSelect(boolean selected) { if (selected) { mPic_hide_img_recovery.setAlpha(ALPHA_ENABLE); mPic_hide_img_del.setAlpha(ALPHA_ENABLE); } else { mPic_hide_img_recovery.setAlpha(ALPHA_DISABLE); mPic_hide_img_del.setAlpha(ALPHA_DISABLE); } } /** * 设置是否有数据 * * @param groupList * @param list */ protected void setHasData(List<?> groupList, List<?> list) { boolean hasData = false; if (groupList != null && groupList.size() > 0 || list != null && list.size() > 0) hasData = true; if (hasData) { mPic_hide_btn_preview.setAlpha(ALPHA_ENABLE); mFile_bottom_layout_tips.setVisibility(View.GONE); } else { mPic_hide_btn_preview.setAlpha(ALPHA_DISABLE); if (mIsEdit) mFile_bottom_layout_tips.setVisibility(View.GONE); else mFile_bottom_layout_tips.setVisibility(View.VISIBLE); } } }
false
2,550
9
3,006
9
3,277
9
3,006
9
3,800
17
false
false
false
false
false
true
17328_6
package 集合框架; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class For { public static void main(String[]args){ List<Hero> LH=new ArrayList<>(); for(int i=0;i<5;i++){ LH.add(new Hero("Hero"+i)); } System.out.println(LH); // 第一种遍历 for循环 System.out.println("--------for 循环-------"); for(int i=0;i<LH.size();i++){ Hero h=LH.get(i); System.out.print(h+" "); } System.out.println(); //第二种遍历,使用迭代器 System.out.println("--------使用while的iterator-------"); Iterator<Hero> it=LH.iterator(); //从最开始的位置判断"下一个"位置是否有数据 //如果有就通过next取出来,并且把指针向下移动 //直到"下一个"位置没有数据 while(it.hasNext()){ Hero h = it.next(); System.out.print(h+" "); } System.out.println(); //迭代器的for写法 System.out.println("--------使用for的iterator-------"); for (Iterator<Hero> iterator = LH.iterator(); iterator.hasNext();) { Hero hero = (Hero) iterator.next(); System.out.print(hero+" "); } System.out.println(); // 第三种,增强型for循环 System.out.println("--------增强型for循环-------"); for (Hero h : LH) { System.out.print(h+" "); } } }
Touko-p/Java
src/集合框架/For.java
397
// 第三种,增强型for循环
line_comment
zh-cn
package 集合框架; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class For { public static void main(String[]args){ List<Hero> LH=new ArrayList<>(); for(int i=0;i<5;i++){ LH.add(new Hero("Hero"+i)); } System.out.println(LH); // 第一种遍历 for循环 System.out.println("--------for 循环-------"); for(int i=0;i<LH.size();i++){ Hero h=LH.get(i); System.out.print(h+" "); } System.out.println(); //第二种遍历,使用迭代器 System.out.println("--------使用while的iterator-------"); Iterator<Hero> it=LH.iterator(); //从最开始的位置判断"下一个"位置是否有数据 //如果有就通过next取出来,并且把指针向下移动 //直到"下一个"位置没有数据 while(it.hasNext()){ Hero h = it.next(); System.out.print(h+" "); } System.out.println(); //迭代器的for写法 System.out.println("--------使用for的iterator-------"); for (Iterator<Hero> iterator = LH.iterator(); iterator.hasNext();) { Hero hero = (Hero) iterator.next(); System.out.print(hero+" "); } System.out.println(); // 第三 <SUF> System.out.println("--------增强型for循环-------"); for (Hero h : LH) { System.out.print(h+" "); } } }
false
332
8
397
10
414
8
397
10
530
20
false
false
false
false
false
true
53947_4
package utils.phoenix; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import utils.ConnectUtil; /** * Created with IntelliJ IDEA. * User: lihaoran * Date: 2018/11/14 * Time: 8:40 * Description:Java使用spark操作phoenix,一般不用。 */ public class TestSpark02 { public static void main(String[] args) { SparkSession spark = ConnectUtil.spark(); //本地读取数据 Dataset<Row> ds = spark.read().format("jdbc") .option("driver", "org.apache.phoenix.jdbc.PhoenixDriver") .option("url", "jdbc:phoenix:localhost:2181") .option("dbtable", "(select * from student)") .load(); ds.show();//这里正常 JavaRDD<Row> javaRDD =ds.javaRDD();// 不能直接foreach,没数据 List<Row> list = javaRDD.collect(); System.out.println("list size=================="+list.size());//有数据,为4 List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>(); //更加详细的数据处理见PhoenixUtil。 for(int i = 0; i <list.size(); i++){ Row row = list.get(i); HashMap<String, String> map = new HashMap<String, String>(); map.put("ID",row.getString(0)); map.put("NAME",row.getString(1)); map.put("SEX",row.getString(2)); map.put("AGE",String.valueOf(row.getInt(3))); result.add(map); } System.out.println("result=============="+result.size()); } }
ToyHaoran/scala01
src/utils/phoenix/TestSpark02.java
483
//有数据,为4
line_comment
zh-cn
package utils.phoenix; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import utils.ConnectUtil; /** * Created with IntelliJ IDEA. * User: lihaoran * Date: 2018/11/14 * Time: 8:40 * Description:Java使用spark操作phoenix,一般不用。 */ public class TestSpark02 { public static void main(String[] args) { SparkSession spark = ConnectUtil.spark(); //本地读取数据 Dataset<Row> ds = spark.read().format("jdbc") .option("driver", "org.apache.phoenix.jdbc.PhoenixDriver") .option("url", "jdbc:phoenix:localhost:2181") .option("dbtable", "(select * from student)") .load(); ds.show();//这里正常 JavaRDD<Row> javaRDD =ds.javaRDD();// 不能直接foreach,没数据 List<Row> list = javaRDD.collect(); System.out.println("list size=================="+list.size());//有数 <SUF> List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>(); //更加详细的数据处理见PhoenixUtil。 for(int i = 0; i <list.size(); i++){ Row row = list.get(i); HashMap<String, String> map = new HashMap<String, String>(); map.put("ID",row.getString(0)); map.put("NAME",row.getString(1)); map.put("SEX",row.getString(2)); map.put("AGE",String.valueOf(row.getInt(3))); result.add(map); } System.out.println("result=============="+result.size()); } }
false
403
6
483
6
495
6
483
6
564
7
false
false
false
false
false
true
16211_2
package edu.hdu.gk.utils; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; /** * @author: Keynes Zhang * @E-mail: [email protected] @time:2016年10月18日, 下午10:29:11 * @annotation: 定义相关常量 */ public class Config { private Config(){} // 返回值常量 public static final String Data = "data"; public static final String Success = "success"; // 数据库常量 public static final String DBURL = "mongodb://localhost:27017"; // 参数名常量 public static final String Query = "query"; public static final String Page = "page"; public static final String PageSize = "pageSize"; public static final String QueryKeyValueParameterReg; public static final String QueryBasicParameterReg = "\\s*(\"[\\s\\S]*?\"|[\\S]*)"; public static final Map<String, String> Mapping = new HashMap<>(); public static final Map<String, String> GroupMapping = new HashMap<>(); static { Mapping.put("port", "port"); Mapping.put("端口","port"); Mapping.put("端口号", "port"); Mapping.put("transport", "transport"); Mapping.put("传输", "transport"); Mapping.put("网络协议", "transport"); Mapping.put("country", "location.country_code"); Mapping.put("国家", "location.country_code"); Mapping.put("countryName", "location.country_name"); Mapping.put("国家名", "location.country_name"); Mapping.put("city", "location.city"); Mapping.put("城市", "location.city"); Mapping.put("module", "module"); Mapping.put("协议", "module"); Mapping.put("设备协议", "module"); Mapping.put("isp", "isp"); Mapping.put("供应商", "isp"); Mapping.put("服务提供商", "isp"); Mapping.put("org", "org"); Mapping.put("企业", "org"); Mapping.put("ip", "ip_str"); Mapping.put("data", "data"); Mapping.put("tags", "tags"); Mapping.put("server", "http.server"); Mapping.put("服务", "http.server"); QueryKeyValueParameterReg = Mapping.keySet().stream().collect(Collectors.joining("|","(",")\\s*:\\s*(\"[\\s\\S]*?\"|[\\S]*)")); GroupMapping.put("port", "port"); GroupMapping.put("domains", "domains_row"); GroupMapping.put("hostnames", "hostnames_row"); GroupMapping.put("isp", "isp_row"); GroupMapping.put("city", "location.city_row"); GroupMapping.put("country", "location.country_name_row"); GroupMapping.put("countryCode", "location.country_code"); GroupMapping.put("module", "module_row"); GroupMapping.put("org", "org_row"); GroupMapping.put("os", "os_row"); GroupMapping.put("product", "product_row"); GroupMapping.put("tags", "tags"); GroupMapping.put("server", "http.server_row"); } }
Trace-Seeker/vis-project
src/main/java/edu/hdu/gk/utils/Config.java
847
// 数据库常量
line_comment
zh-cn
package edu.hdu.gk.utils; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; /** * @author: Keynes Zhang * @E-mail: [email protected] @time:2016年10月18日, 下午10:29:11 * @annotation: 定义相关常量 */ public class Config { private Config(){} // 返回值常量 public static final String Data = "data"; public static final String Success = "success"; // 数据 <SUF> public static final String DBURL = "mongodb://localhost:27017"; // 参数名常量 public static final String Query = "query"; public static final String Page = "page"; public static final String PageSize = "pageSize"; public static final String QueryKeyValueParameterReg; public static final String QueryBasicParameterReg = "\\s*(\"[\\s\\S]*?\"|[\\S]*)"; public static final Map<String, String> Mapping = new HashMap<>(); public static final Map<String, String> GroupMapping = new HashMap<>(); static { Mapping.put("port", "port"); Mapping.put("端口","port"); Mapping.put("端口号", "port"); Mapping.put("transport", "transport"); Mapping.put("传输", "transport"); Mapping.put("网络协议", "transport"); Mapping.put("country", "location.country_code"); Mapping.put("国家", "location.country_code"); Mapping.put("countryName", "location.country_name"); Mapping.put("国家名", "location.country_name"); Mapping.put("city", "location.city"); Mapping.put("城市", "location.city"); Mapping.put("module", "module"); Mapping.put("协议", "module"); Mapping.put("设备协议", "module"); Mapping.put("isp", "isp"); Mapping.put("供应商", "isp"); Mapping.put("服务提供商", "isp"); Mapping.put("org", "org"); Mapping.put("企业", "org"); Mapping.put("ip", "ip_str"); Mapping.put("data", "data"); Mapping.put("tags", "tags"); Mapping.put("server", "http.server"); Mapping.put("服务", "http.server"); QueryKeyValueParameterReg = Mapping.keySet().stream().collect(Collectors.joining("|","(",")\\s*:\\s*(\"[\\s\\S]*?\"|[\\S]*)")); GroupMapping.put("port", "port"); GroupMapping.put("domains", "domains_row"); GroupMapping.put("hostnames", "hostnames_row"); GroupMapping.put("isp", "isp_row"); GroupMapping.put("city", "location.city_row"); GroupMapping.put("country", "location.country_name_row"); GroupMapping.put("countryCode", "location.country_code"); GroupMapping.put("module", "module_row"); GroupMapping.put("org", "org_row"); GroupMapping.put("os", "os_row"); GroupMapping.put("product", "product_row"); GroupMapping.put("tags", "tags"); GroupMapping.put("server", "http.server_row"); } }
false
736
6
845
6
866
5
845
6
1,006
8
false
false
false
false
false
true
37627_0
package com.inst.aop.entity; import com.inst.aop.annotation.After; import com.inst.aop.annotation.Before; import com.inst.aop.annotation.MyAspect; @MyAspect // 标明切点类 public class Waitress { // 前置通知,当调用eatFood方法被调用的时候该方法会被在它之前调用 @Before("com.inst.aop.entity.Person.eatFood()") public void beforePersonEat() { System.out.println("开始上菜"); } // 后置通知,当调用eatFood方法被调用的时候该方法会被在它之后调用 @After("com.inst.aop.entity.Person.eatFood()") public void afterPersonEat() { System.out.println("开始收拾"); } }
TrustMSYT/SpringAOPCGLIB
src/com/inst/aop/entity/Waitress.java
205
// 标明切点类
line_comment
zh-cn
package com.inst.aop.entity; import com.inst.aop.annotation.After; import com.inst.aop.annotation.Before; import com.inst.aop.annotation.MyAspect; @MyAspect // 标明 <SUF> public class Waitress { // 前置通知,当调用eatFood方法被调用的时候该方法会被在它之前调用 @Before("com.inst.aop.entity.Person.eatFood()") public void beforePersonEat() { System.out.println("开始上菜"); } // 后置通知,当调用eatFood方法被调用的时候该方法会被在它之后调用 @After("com.inst.aop.entity.Person.eatFood()") public void afterPersonEat() { System.out.println("开始收拾"); } }
false
165
7
205
7
194
6
205
7
250
7
false
false
false
false
false
true
48945_24
package leetcodeDaily; //给你一个数组 towers 和一个整数 radius 。 // 数组 towers 中包含一些网络信号塔,其中 towers[i] = [xi, yi, qi] 表示第 i 个网络信号塔的坐标是 (xi, yi) 且信 //号强度参数为 qi 。所有坐标都是在 X-Y 坐标系内的 整数 坐标。两个坐标之间的距离用 欧几里得距离 计算。 // 整数 radius 表示一个塔 能到达 的 最远距离 。如果一个坐标跟塔的距离在 radius 以内,那么该塔的信号可以到达该坐标。在这个范围以外信号会很 //微弱,所以 radius 以外的距离该塔是 不能到达的 。 // 如果第 i 个塔能到达 (x, y) ,那么该塔在此处的信号为 ⌊qi / (1 + d)⌋ ,其中 d 是塔跟此坐标的距离。一个坐标的 信号强度 是所有 // 能到达 该坐标的塔的信号强度之和。 // 请你返回数组 [cx, cy] ,表示 信号强度 最大的 整数 坐标点 (cx, cy) 。如果有多个坐标网络信号一样大,请你返回字典序最小的 非负 坐标 // 注意: // 坐标 (x1, y1) 字典序比另一个坐标 (x2, y2) 小,需满足以下条件之一: // 要么 x1 < x2 , // 要么 x1 == x2 且 y1 < y2 。 // ⌊val⌋ 表示小于等于 val 的最大整数(向下取整函数)。 // 示例 1: //输入:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2 //输出:[2,1] //解释: //坐标 (2, 1) 信号强度之和为 13 //- 塔 (2, 1) 强度参数为 7 ,在该点强度为 ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 //- 塔 (1, 2) 强度参数为 5 ,在该点强度为 ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 //- 塔 (3, 1) 强度参数为 9 ,在该点强度为 ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 //没有别的坐标有更大的信号强度。 // 示例 2: //输入:towers = [[23,11,21]], radius = 9 //输出:[23,11] //解释:由于仅存在一座信号塔,所以塔的位置信号强度最大。 // 示例 3: //输入:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2 //输出:[1,2] //解释:坐标 (1, 2) 的信号强度最大。 public class B1620 { public static void main(String[] args) { } public int[] bestCoordinate(int[][] towers, int radius) { int max =0; int[] ans = new int[] {0,0}; for (int i = 0; i < 51; ++i) { for (int j = 0; j < 51; ++j) { int t=0; for(var e:towers){ double d = Math.sqrt((i-e[0])*(i-e[0])+(j-e[1])+(j-e[1])); if(d<=radius){ t+=Math.floor(e[2]/(1+d)); } } if(max<t){ max = t; ans = new int[]{i,j}; } } } return ans; } } class Solution { public int[] bestCoordinate(int[][] towers, int radius) { int mx = 0; int[] ans = new int[] {0, 0}; for (int i = 0; i < 51; ++i) { for (int j = 0; j < 51; ++j) { int t = 0; for (var e : towers) { double d = Math.sqrt((i - e[0]) * (i - e[0]) + (j - e[1]) * (j - e[1])); if (d <= radius) { t += Math.floor(e[2] / (1 + d)); } } if (mx < t) { mx = t; ans = new int[] {i, j}; } } } return ans; } }
Tsalter1019/ODTest19
src/leetcodeDaily/B1620.java
1,188
//输出:[23,11]
line_comment
zh-cn
package leetcodeDaily; //给你一个数组 towers 和一个整数 radius 。 // 数组 towers 中包含一些网络信号塔,其中 towers[i] = [xi, yi, qi] 表示第 i 个网络信号塔的坐标是 (xi, yi) 且信 //号强度参数为 qi 。所有坐标都是在 X-Y 坐标系内的 整数 坐标。两个坐标之间的距离用 欧几里得距离 计算。 // 整数 radius 表示一个塔 能到达 的 最远距离 。如果一个坐标跟塔的距离在 radius 以内,那么该塔的信号可以到达该坐标。在这个范围以外信号会很 //微弱,所以 radius 以外的距离该塔是 不能到达的 。 // 如果第 i 个塔能到达 (x, y) ,那么该塔在此处的信号为 ⌊qi / (1 + d)⌋ ,其中 d 是塔跟此坐标的距离。一个坐标的 信号强度 是所有 // 能到达 该坐标的塔的信号强度之和。 // 请你返回数组 [cx, cy] ,表示 信号强度 最大的 整数 坐标点 (cx, cy) 。如果有多个坐标网络信号一样大,请你返回字典序最小的 非负 坐标 // 注意: // 坐标 (x1, y1) 字典序比另一个坐标 (x2, y2) 小,需满足以下条件之一: // 要么 x1 < x2 , // 要么 x1 == x2 且 y1 < y2 。 // ⌊val⌋ 表示小于等于 val 的最大整数(向下取整函数)。 // 示例 1: //输入:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2 //输出:[2,1] //解释: //坐标 (2, 1) 信号强度之和为 13 //- 塔 (2, 1) 强度参数为 7 ,在该点强度为 ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 //- 塔 (1, 2) 强度参数为 5 ,在该点强度为 ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 //- 塔 (3, 1) 强度参数为 9 ,在该点强度为 ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 //没有别的坐标有更大的信号强度。 // 示例 2: //输入:towers = [[23,11,21]], radius = 9 //输出 <SUF> //解释:由于仅存在一座信号塔,所以塔的位置信号强度最大。 // 示例 3: //输入:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2 //输出:[1,2] //解释:坐标 (1, 2) 的信号强度最大。 public class B1620 { public static void main(String[] args) { } public int[] bestCoordinate(int[][] towers, int radius) { int max =0; int[] ans = new int[] {0,0}; for (int i = 0; i < 51; ++i) { for (int j = 0; j < 51; ++j) { int t=0; for(var e:towers){ double d = Math.sqrt((i-e[0])*(i-e[0])+(j-e[1])+(j-e[1])); if(d<=radius){ t+=Math.floor(e[2]/(1+d)); } } if(max<t){ max = t; ans = new int[]{i,j}; } } } return ans; } } class Solution { public int[] bestCoordinate(int[][] towers, int radius) { int mx = 0; int[] ans = new int[] {0, 0}; for (int i = 0; i < 51; ++i) { for (int j = 0; j < 51; ++j) { int t = 0; for (var e : towers) { double d = Math.sqrt((i - e[0]) * (i - e[0]) + (j - e[1]) * (j - e[1])); if (d <= radius) { t += Math.floor(e[2] / (1 + d)); } } if (mx < t) { mx = t; ans = new int[] {i, j}; } } } return ans; } }
false
1,095
10
1,188
9
1,115
9
1,188
9
1,553
11
false
false
false
false
false
true
31681_28
// QScript.MetaData.Start // QScript.MetaData.Name = QScript脚本示例 // QScript.MetaData.Desc = QScript官方给出的脚本示例 // QScript.MetaData.Version = 1.0.0 // QScript.MetaData.Author = Tsihen-Ho // QScript.MetaData.Label = qscript-demo // QScript.MetaData.Permission.Network // QScript.MetaData.End // 注:上面的 Label 标签是分辨脚本的唯一属性,如果两个脚本 Label 相同,就会被判别为同一个脚本 // 注:如果需要网络,请添加 QScript.MetaData.Permission.Network // 任何脚本只能 import java.* 下的内容,其他东西,如 com.tencent.mobileqq.activity.BaseChatpie、 // android.app.Activity、me.tsihen.qscript.util.Utils 都不能导入 // 每个脚本必须以 QScript.MetaData.Start 开头 // 这仅仅是一个演示脚本,我们不建议您启用这个脚本 /* * 所有的方法都在脚本里面,自己看 * 预定义变量: * Conntext ctx : QQ 的 Application * long mQNum : 您的 QQ 号码 * QScript thisScript : 该脚本,如:thisScript.getName() * ScriptApi api : 能够调用 API 的对象,如:api.sendTextMsg("something", 334092396l) */ /** * 在脚本加载的时候调用 */ public void onLoad(){ api.log("onLoad() : User's QNum is " + mQNum.toString()); // 发消息的时候,QQ号末尾必须加 L 表示长整形 // 第一个 String 代表文本内容 api.sendTextMsg(api.createData("3340792396",false),"QScript 脚本发消息测试:表情:\u0014\u0003"); // 发表情: 反斜杠u0014反斜杠u表情id // api.sendCardMsg(String 卡片代码, long 消息接受者, boolean 是否群聊) // 发送卡片需要完成高级验证,否则报错 api.sendCardMsg(api.createData("818333976",true),"<?xml version='1.0' encoding='UTF-8' "+ "standalone='yes' ?><msg serviceID=\"33\" templateID=\"123\" "+ "action=\"web\" brief=\"【链接】Golink加速器-国内首款免费游戏加速器【官方\" "+ "sourceMsgId=\"0\" url=\"https://www.golink.com/?code=JYPYKZWN\""+ " flag=\"8\" adverSign=\"0\" multiMsgFlag=\"0\"><item layout=\"2\""+ " advertiser_id=\"0\" aid=\"0\"><picture cover=\"https://qq.ugcimg.cn/v1/o3upv4dbs"+ "quu39i05lpnt57nmuaae2q4lus62r1u22o1cav00k7jus7po80am2j17r004ultmqfsq/s6vskamj00lmmk"+ "t83jce822lfg\" w=\"0\" h=\"0\" /><title>QScript XML 消息测试</titl"+ "e><summary>XML 消息</summary></ite"+ "m><source name=\"\" icon=\"\" action=\"\" appid=\"-1\" /></msg>"); // api.sendPhotoMsg(data, String 图片路径) api.sendPhotoMsg(api.createData("818333976",true),"/sdcard/QQColor2/vip/fullBackground/chat/imgs_touch.jpeg"); // 下面演示网络连接,注意申请网络权限(QScript.MetaData.Permission.Network) Object network=api.getNetwork(); Object doc=network.fromUrl("https://zh.numberempire.com/simplifyexpression.php") .header( "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3" ) .header("Accept-Encoding","gzip, deflate") .header("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8") .header("Cache-Control","no-cache") .header("Pragma","no-cache") .header("Proxy-Connection","keep-alive") .header( "User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 (compatible; Baiduspider-render/2.0; +http://www.baidu.com/search/spider.html)" ) // 设置HEADER .data("function","1+2+3") // 这是表单数据 .post(); // 这里演示POST,GET同理 Object result=doc.getElementById("result1").text(); api.log("网络连接结果:"+result.toString()); } /** * 文本消息 */ public void onMsg(Object param){ // 发送给消息发送者(群或者人)的函数:api.sendTextMsg(param, "消息") 或者 (param, "消息", new long[]{1L, 2L, 3L}) String l = param.senderUin; // 发送者 String s = param.content; // 文本内容 String s2 = param.content2; // 暂时我也不知道有什么用 String name = param.nickname; // 名字 String f = param.friendUin; // 如果是群消息,这个就是群聊号码,否则就是发送者 String source = param.source; // 消息源代码。是卡片消息的代码!!!! int type = param.type; // int type 消息类型 1-文字 2-图片 3-xml卡片 4-json卡片 5-回复消息 6-图文消息 0-其他消息 api.log("atMe : " + param.atMe.toString()); // boolean atMe : 是否艾特自己 String[] atList = param.atList; // 被艾特的列表 String[]。注:老版本是 LinkedList if(s.equals("群消息测试") && param.isGroupMsg()){ api.log("尝试群消息测试"); // 最后一个参数表示被艾特的人 // 如果要发送群消息但不艾特,请 api.sendTextMsg(String 消息内容, long 接受者即群号码, new long[]{}); // 发送私聊消息,请 api.sendTextMsg(String 消息内容, long 接受者) // api.getNickname(String 人, String 群) 获取 人 在 群 里面的昵称 // api.getNickname(String 人, String 人) 获取 人 的名称 // api.getNickname(Object data) 根据 data 获取发送者的昵称,如 api.getNickname(param); api.sendTextMsg(param, "@" + api.getNickname(3318448676L, 818333976L) + " @" + api.getNickname(3340792396L, 818333976L) + "群测试A", new long[]{3318448676L,3340792396L}); api.sendTextMsg(param, "测试完成", api.str2long(l)); return; } api.log("source = " + source); if(param.isGroupMsg() || l.equals(mQNum.toString())){ return; } api.sendTip(param, "Tip 消息,仅自己可见"); api.sendShakeMsg(param); // 抖动 // api.sendTextMsg(param, "nmsl(bushi"); } /** * 新成员入群 */ public void onJoin(Object data) { String group = data.groupUin; String member = data.uin; api.log("新成员" + member + "加入群聊" + group); if (!group.equals("818333976")) return; // shutUp(long 群号码, long 成员号码, long 时间) 禁言某人,单位秒 api.shutUp(api.str2long(group), api.str2long(member), 20L); api.sendTextMsg("嘿!" + member + ",别忙着说话!", group, new long[]{api.str2long(member)}); // shutAllUp(long 群号码, boolean 是否启动) 全体禁言,最后的 boolean ,true = 开启禁言,false反之 api.shutAllUp(api.str2long(group), true); Thread.sleep(10000); api.shutAllUp(api.str2long(group), false); // 解除禁言 }
TsihenHo/QScript
app/src/main/assets/demo.java
2,220
// 发送者
line_comment
zh-cn
// QScript.MetaData.Start // QScript.MetaData.Name = QScript脚本示例 // QScript.MetaData.Desc = QScript官方给出的脚本示例 // QScript.MetaData.Version = 1.0.0 // QScript.MetaData.Author = Tsihen-Ho // QScript.MetaData.Label = qscript-demo // QScript.MetaData.Permission.Network // QScript.MetaData.End // 注:上面的 Label 标签是分辨脚本的唯一属性,如果两个脚本 Label 相同,就会被判别为同一个脚本 // 注:如果需要网络,请添加 QScript.MetaData.Permission.Network // 任何脚本只能 import java.* 下的内容,其他东西,如 com.tencent.mobileqq.activity.BaseChatpie、 // android.app.Activity、me.tsihen.qscript.util.Utils 都不能导入 // 每个脚本必须以 QScript.MetaData.Start 开头 // 这仅仅是一个演示脚本,我们不建议您启用这个脚本 /* * 所有的方法都在脚本里面,自己看 * 预定义变量: * Conntext ctx : QQ 的 Application * long mQNum : 您的 QQ 号码 * QScript thisScript : 该脚本,如:thisScript.getName() * ScriptApi api : 能够调用 API 的对象,如:api.sendTextMsg("something", 334092396l) */ /** * 在脚本加载的时候调用 */ public void onLoad(){ api.log("onLoad() : User's QNum is " + mQNum.toString()); // 发消息的时候,QQ号末尾必须加 L 表示长整形 // 第一个 String 代表文本内容 api.sendTextMsg(api.createData("3340792396",false),"QScript 脚本发消息测试:表情:\u0014\u0003"); // 发表情: 反斜杠u0014反斜杠u表情id // api.sendCardMsg(String 卡片代码, long 消息接受者, boolean 是否群聊) // 发送卡片需要完成高级验证,否则报错 api.sendCardMsg(api.createData("818333976",true),"<?xml version='1.0' encoding='UTF-8' "+ "standalone='yes' ?><msg serviceID=\"33\" templateID=\"123\" "+ "action=\"web\" brief=\"【链接】Golink加速器-国内首款免费游戏加速器【官方\" "+ "sourceMsgId=\"0\" url=\"https://www.golink.com/?code=JYPYKZWN\""+ " flag=\"8\" adverSign=\"0\" multiMsgFlag=\"0\"><item layout=\"2\""+ " advertiser_id=\"0\" aid=\"0\"><picture cover=\"https://qq.ugcimg.cn/v1/o3upv4dbs"+ "quu39i05lpnt57nmuaae2q4lus62r1u22o1cav00k7jus7po80am2j17r004ultmqfsq/s6vskamj00lmmk"+ "t83jce822lfg\" w=\"0\" h=\"0\" /><title>QScript XML 消息测试</titl"+ "e><summary>XML 消息</summary></ite"+ "m><source name=\"\" icon=\"\" action=\"\" appid=\"-1\" /></msg>"); // api.sendPhotoMsg(data, String 图片路径) api.sendPhotoMsg(api.createData("818333976",true),"/sdcard/QQColor2/vip/fullBackground/chat/imgs_touch.jpeg"); // 下面演示网络连接,注意申请网络权限(QScript.MetaData.Permission.Network) Object network=api.getNetwork(); Object doc=network.fromUrl("https://zh.numberempire.com/simplifyexpression.php") .header( "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3" ) .header("Accept-Encoding","gzip, deflate") .header("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8") .header("Cache-Control","no-cache") .header("Pragma","no-cache") .header("Proxy-Connection","keep-alive") .header( "User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 (compatible; Baiduspider-render/2.0; +http://www.baidu.com/search/spider.html)" ) // 设置HEADER .data("function","1+2+3") // 这是表单数据 .post(); // 这里演示POST,GET同理 Object result=doc.getElementById("result1").text(); api.log("网络连接结果:"+result.toString()); } /** * 文本消息 */ public void onMsg(Object param){ // 发送给消息发送者(群或者人)的函数:api.sendTextMsg(param, "消息") 或者 (param, "消息", new long[]{1L, 2L, 3L}) String l = param.senderUin; // 发送 <SUF> String s = param.content; // 文本内容 String s2 = param.content2; // 暂时我也不知道有什么用 String name = param.nickname; // 名字 String f = param.friendUin; // 如果是群消息,这个就是群聊号码,否则就是发送者 String source = param.source; // 消息源代码。是卡片消息的代码!!!! int type = param.type; // int type 消息类型 1-文字 2-图片 3-xml卡片 4-json卡片 5-回复消息 6-图文消息 0-其他消息 api.log("atMe : " + param.atMe.toString()); // boolean atMe : 是否艾特自己 String[] atList = param.atList; // 被艾特的列表 String[]。注:老版本是 LinkedList if(s.equals("群消息测试") && param.isGroupMsg()){ api.log("尝试群消息测试"); // 最后一个参数表示被艾特的人 // 如果要发送群消息但不艾特,请 api.sendTextMsg(String 消息内容, long 接受者即群号码, new long[]{}); // 发送私聊消息,请 api.sendTextMsg(String 消息内容, long 接受者) // api.getNickname(String 人, String 群) 获取 人 在 群 里面的昵称 // api.getNickname(String 人, String 人) 获取 人 的名称 // api.getNickname(Object data) 根据 data 获取发送者的昵称,如 api.getNickname(param); api.sendTextMsg(param, "@" + api.getNickname(3318448676L, 818333976L) + " @" + api.getNickname(3340792396L, 818333976L) + "群测试A", new long[]{3318448676L,3340792396L}); api.sendTextMsg(param, "测试完成", api.str2long(l)); return; } api.log("source = " + source); if(param.isGroupMsg() || l.equals(mQNum.toString())){ return; } api.sendTip(param, "Tip 消息,仅自己可见"); api.sendShakeMsg(param); // 抖动 // api.sendTextMsg(param, "nmsl(bushi"); } /** * 新成员入群 */ public void onJoin(Object data) { String group = data.groupUin; String member = data.uin; api.log("新成员" + member + "加入群聊" + group); if (!group.equals("818333976")) return; // shutUp(long 群号码, long 成员号码, long 时间) 禁言某人,单位秒 api.shutUp(api.str2long(group), api.str2long(member), 20L); api.sendTextMsg("嘿!" + member + ",别忙着说话!", group, new long[]{api.str2long(member)}); // shutAllUp(long 群号码, boolean 是否启动) 全体禁言,最后的 boolean ,true = 开启禁言,false反之 api.shutAllUp(api.str2long(group), true); Thread.sleep(10000); api.shutAllUp(api.str2long(group), false); // 解除禁言 }
false
2,015
4
2,220
4
2,155
3
2,220
4
2,734
5
false
false
false
false
false
true
51392_8
package com.tsroad.map.util; /** % @authors Keung Charteris & T.s.road CZQ % @version 1.0 ($Revision$) % @addr. GUET, Gui Lin, 540001, P.R.China % @contact : [email protected] % @date Copyright(c) 2016-2020, All rights reserved. % This is an open access code distributed under the Creative Commons Attribution License, which permits % unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. */ public class ChString { public static final String Kilometer = "\u516c\u91cc";// "公里"; public static final String Meter = "\u7c73";// "米"; public static final String ByFoot = "\u6b65\u884c";// "步行"; public static final String To = "\u53bb\u5f80";// "去往"; public static final String Station = "\u8f66\u7ad9";// "车站"; public static final String TargetPlace = "\u76ee\u7684\u5730";// "目的地"; public static final String StartPlace = "\u51fa\u53d1\u5730";// "出发地"; public static final String About = "\u5927\u7ea6";// "大约"; public static final String Direction = "\u65b9\u5411";// "方向"; public static final String GetOn = "\u4e0a\u8f66";// "上车"; public static final String GetOff = "\u4e0b\u8f66";// "下车"; public static final String Zhan = "\u7ad9";// "站"; public static final String cross = "\u4ea4\u53c9\u8def\u53e3"; // 交叉路口 public static final String type = "\u7c7b\u522b"; // 类别 public static final String address = "\u5730\u5740"; // 地址 public static final String PrevStep = "\u4e0a\u4e00\u6b65"; public static final String NextStep = "\u4e0b\u4e00\u6b65"; public static final String Gong = "\u516c\u4ea4"; public static final String ByBus = "\u4e58\u8f66"; public static final String Arrive = "\u5230\u8FBE";// 到达 }
Tsroad/Road
app/src/main/java/com/tsroad/map/util/ChString.java
687
// "大约";
line_comment
zh-cn
package com.tsroad.map.util; /** % @authors Keung Charteris & T.s.road CZQ % @version 1.0 ($Revision$) % @addr. GUET, Gui Lin, 540001, P.R.China % @contact : [email protected] % @date Copyright(c) 2016-2020, All rights reserved. % This is an open access code distributed under the Creative Commons Attribution License, which permits % unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. */ public class ChString { public static final String Kilometer = "\u516c\u91cc";// "公里"; public static final String Meter = "\u7c73";// "米"; public static final String ByFoot = "\u6b65\u884c";// "步行"; public static final String To = "\u53bb\u5f80";// "去往"; public static final String Station = "\u8f66\u7ad9";// "车站"; public static final String TargetPlace = "\u76ee\u7684\u5730";// "目的地"; public static final String StartPlace = "\u51fa\u53d1\u5730";// "出发地"; public static final String About = "\u5927\u7ea6";// "大 <SUF> public static final String Direction = "\u65b9\u5411";// "方向"; public static final String GetOn = "\u4e0a\u8f66";// "上车"; public static final String GetOff = "\u4e0b\u8f66";// "下车"; public static final String Zhan = "\u7ad9";// "站"; public static final String cross = "\u4ea4\u53c9\u8def\u53e3"; // 交叉路口 public static final String type = "\u7c7b\u522b"; // 类别 public static final String address = "\u5730\u5740"; // 地址 public static final String PrevStep = "\u4e0a\u4e00\u6b65"; public static final String NextStep = "\u4e0b\u4e00\u6b65"; public static final String Gong = "\u516c\u4ea4"; public static final String ByBus = "\u4e58\u8f66"; public static final String Arrive = "\u5230\u8FBE";// 到达 }
false
573
4
680
6
645
5
680
6
711
8
false
false
false
false
false
true
54843_1
package algorithm; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * * T 有一个n个结点m条边的有向图,请输出他的关联矩阵。 * * * 输入格式 * 第一行两个整数n、m,表示图中结点和边的数目。n<=100,m<=1000。 * 接下来m行,每行两个整数a、b,表示图中有(a,b)边。 * 注意图中可能含有重边,但不会有自环。 * * 输出格式 * 输出该图的关联矩阵,注意请勿改变边和结点的顺序。 * * * * 样例输入 * 5 9 * 1 2 * 3 1 * 1 5 * 2 5 * 2 3 * 2 3 * 3 2 * 4 3 * 5 4 * * 样例输出 * 1 -1 1 0 0 0 0 0 0 * -1 0 0 1 1 1 -1 0 0 * 0 1 0 0 -1 -1 1 -1 0 * 0 0 0 0 0 0 0 1 -1 * 0 0 -1 -1 0 0 0 0 1 * * * B[i][k]表示 * (1)如果B[i][k]=1,则第k条边为点i的 出边; * (2)如果B[i][k]=-1;则第k条边为点i的 入边; * (3)如果B[i][k]=0;则点i与第k条边无关; * * * (a -> b : a = -1, b = 1;) * * * * @author tugeng * */ public class Incidence_Matrix { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] one = bf.readLine().split(" "); Integer n = Integer.valueOf(one[0]); // n 个 顶点 Integer m = Integer.valueOf(one[1]); // m 条 边 int rs[][] = new int[n + 1][m + 1]; for (int i = 1; i <= m; i++) { String two[] = bf.readLine().split(" "); rs[Integer.valueOf(two[0])][i] = 1; rs[Integer.valueOf(two[1])][i] = -1; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { System.out.print(rs[i][j] + " "); } System.out.println(); } } }
TuGengs/Blue_Bridge_Cup
src/algorithm/Incidence_Matrix.java
732
// n 个 顶点
line_comment
zh-cn
package algorithm; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * * T 有一个n个结点m条边的有向图,请输出他的关联矩阵。 * * * 输入格式 * 第一行两个整数n、m,表示图中结点和边的数目。n<=100,m<=1000。 * 接下来m行,每行两个整数a、b,表示图中有(a,b)边。 * 注意图中可能含有重边,但不会有自环。 * * 输出格式 * 输出该图的关联矩阵,注意请勿改变边和结点的顺序。 * * * * 样例输入 * 5 9 * 1 2 * 3 1 * 1 5 * 2 5 * 2 3 * 2 3 * 3 2 * 4 3 * 5 4 * * 样例输出 * 1 -1 1 0 0 0 0 0 0 * -1 0 0 1 1 1 -1 0 0 * 0 1 0 0 -1 -1 1 -1 0 * 0 0 0 0 0 0 0 1 -1 * 0 0 -1 -1 0 0 0 0 1 * * * B[i][k]表示 * (1)如果B[i][k]=1,则第k条边为点i的 出边; * (2)如果B[i][k]=-1;则第k条边为点i的 入边; * (3)如果B[i][k]=0;则点i与第k条边无关; * * * (a -> b : a = -1, b = 1;) * * * * @author tugeng * */ public class Incidence_Matrix { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] one = bf.readLine().split(" "); Integer n = Integer.valueOf(one[0]); // n <SUF> Integer m = Integer.valueOf(one[1]); // m 条 边 int rs[][] = new int[n + 1][m + 1]; for (int i = 1; i <= m; i++) { String two[] = bf.readLine().split(" "); rs[Integer.valueOf(two[0])][i] = 1; rs[Integer.valueOf(two[1])][i] = -1; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { System.out.print(rs[i][j] + " "); } System.out.println(); } } }
false
672
7
732
6
768
6
732
6
916
9
false
false
false
false
false
true
37137_5
package com.halfmoon.cloudmanager.common; import java.text.SimpleDateFormat; /** * * @author xiaogao.XU * 一些常用的常量 */ public class Constant { // 创建者为1 辅助检查为0 public static final int CREATOR = 1; public static final int FOLLOWER = 0; //是否允许添加学生 1为允许 0为不允许 public static final int ALLOW = 1; public static final int NOT_ALLOW = 0; // 分享的类别 1为辅助签到 0为查看检查 public static final int HELPER = 1; public static final int LOOKER = 0; // 扣分项是对个人还是团体 public static final int IS_TO_SINGLE = 1; public static final int NOT_TO_SINGLE = 0; // 扣分检查和签到检查 public static final int GRADE_CHECK = 0; public static final int SIGN_IN_CHECK = 1; // 检查是否开启 public static final int IS_OPEN = 1; public static final int NOT_OPNE = 0; // 缺到、迟到、 、到了 public static final int LACK = 0; public static final int LATE = 1; public static final int LEAVE = 2; public static final int IS_HERE = 3; public static final int DISTANCE = 1000; public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); }
TuGengs/cloudmanager
src/main/java/com/halfmoon/cloudmanager/common/Constant.java
397
// 扣分检查和签到检查
line_comment
zh-cn
package com.halfmoon.cloudmanager.common; import java.text.SimpleDateFormat; /** * * @author xiaogao.XU * 一些常用的常量 */ public class Constant { // 创建者为1 辅助检查为0 public static final int CREATOR = 1; public static final int FOLLOWER = 0; //是否允许添加学生 1为允许 0为不允许 public static final int ALLOW = 1; public static final int NOT_ALLOW = 0; // 分享的类别 1为辅助签到 0为查看检查 public static final int HELPER = 1; public static final int LOOKER = 0; // 扣分项是对个人还是团体 public static final int IS_TO_SINGLE = 1; public static final int NOT_TO_SINGLE = 0; // 扣分 <SUF> public static final int GRADE_CHECK = 0; public static final int SIGN_IN_CHECK = 1; // 检查是否开启 public static final int IS_OPEN = 1; public static final int NOT_OPNE = 0; // 缺到、迟到、 、到了 public static final int LACK = 0; public static final int LATE = 1; public static final int LEAVE = 2; public static final int IS_HERE = 3; public static final int DISTANCE = 1000; public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); }
false
349
9
397
10
379
7
397
10
518
19
false
false
false
false
false
true
50818_1
package pers.tuershen.nbtedit; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import pers.tuershen.nbtedit.bstats.Metrics; import pers.tuershen.nbtedit.command.BaseCommand; import pers.tuershen.nbtedit.compoundlibrary.CompoundLibraryManager; import pers.tuershen.nbtedit.compoundlibrary.api.CompoundLibraryApi; import pers.tuershen.nbtedit.configuration.DynamicLoadingFunction; import pers.tuershen.nbtedit.configuration.EditFunctionSetting; import pers.tuershen.nbtedit.event.listener.PushBukkitChatMessages; import pers.tuershen.nbtedit.listener.*; import pers.tuershen.nbtedit.panel.AbstractEdit; import java.io.File; /** * @auther Tuershen update Date on 2020/11/29 */ public class NBTEditPanel extends JavaPlugin { public static NBTEditPanel plugin; @Override public void onEnable() { //插件实例 plugin = this; //NBT接口 CompoundLibraryApi compoundLibraryApi = CompoundLibraryManager.getPluginManager(this); EditFunctionSetting functionSetting = new EditFunctionSetting(); //编辑器初始化 AbstractEdit.init(compoundLibraryApi); //初始化快捷功能 DynamicLoadingFunction function = new DynamicLoadingFunction(getFunctionFile()); function.loadJarFile(); //指令 BaseCommand baseCommand = new BaseCommand(compoundLibraryApi, functionSetting, function); //指令注册 getCommand("edit").setExecutor(baseCommand); //事件注册 Bukkit.getPluginManager().registerEvents(new PlayerEditPanelEvent(),this); Bukkit.getPluginManager().registerEvents(new PlayerChatEvent(PushBukkitChatMessages.registerReceiveObject()),this); Bukkit.getPluginManager().registerEvents(new PlayerClickEntity(compoundLibraryApi, baseCommand),this); Bukkit.getPluginManager().registerEvents(new PlayerClickBlock(compoundLibraryApi, baseCommand),this); Bukkit.getConsoleSender().sendMessage( "§b_ _ ____ _______ ______ _ _ _ _____ _ " ); Bukkit.getConsoleSender().sendMessage( "§b | \\ | | _ \\__ __| ____| | (_) | | __ \\ | |" ); Bukkit.getConsoleSender().sendMessage( "§b | \\| | |_) | | | | |__ __| |_| |_| |__) |_ _ _ __ ___| |" ); Bukkit.getConsoleSender().sendMessage( "§b | . ` | _ < | | | __| / _` | | __| ___/ _` | '_ \\ / _ \\ |" ); Bukkit.getConsoleSender().sendMessage( "§b | |\\ | |_) | | | | |___| (_| | | |_| | | (_| | | | | __/ |" ); Bukkit.getConsoleSender().sendMessage( "§b |_| \\_|____/ |_| |______\\__,_|_|\\__|_| \\__,_|_| |_|\\___|_|"); Bukkit.getConsoleSender().sendMessage("§eNBT编辑器加载成功!"); Bukkit.getConsoleSender().sendMessage("§e作者:兔儿神"); Bukkit.getConsoleSender().sendMessage("§e插件已开源,发现bug可以加群反馈,感激不尽"); Bukkit.getConsoleSender().sendMessage("§e插件交流群:978420514"); Bukkit.getConsoleSender().sendMessage("§e最新版本: v1.35"); //插件统计 new Metrics(this,8933); } public void loadJarLogger(String jar, int count) { Bukkit.getConsoleSender().sendMessage("§b成功载入:§a"+jar+", §b功能数:§e"+count); } public static File getFunctionFile() { return new File(NBTEditPanel.plugin.getDataFolder(),"function"); } }
Tuershen/NBTEditPanel
src/pers/tuershen/nbtedit/NBTEditPanel.java
945
//插件实例
line_comment
zh-cn
package pers.tuershen.nbtedit; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import pers.tuershen.nbtedit.bstats.Metrics; import pers.tuershen.nbtedit.command.BaseCommand; import pers.tuershen.nbtedit.compoundlibrary.CompoundLibraryManager; import pers.tuershen.nbtedit.compoundlibrary.api.CompoundLibraryApi; import pers.tuershen.nbtedit.configuration.DynamicLoadingFunction; import pers.tuershen.nbtedit.configuration.EditFunctionSetting; import pers.tuershen.nbtedit.event.listener.PushBukkitChatMessages; import pers.tuershen.nbtedit.listener.*; import pers.tuershen.nbtedit.panel.AbstractEdit; import java.io.File; /** * @auther Tuershen update Date on 2020/11/29 */ public class NBTEditPanel extends JavaPlugin { public static NBTEditPanel plugin; @Override public void onEnable() { //插件 <SUF> plugin = this; //NBT接口 CompoundLibraryApi compoundLibraryApi = CompoundLibraryManager.getPluginManager(this); EditFunctionSetting functionSetting = new EditFunctionSetting(); //编辑器初始化 AbstractEdit.init(compoundLibraryApi); //初始化快捷功能 DynamicLoadingFunction function = new DynamicLoadingFunction(getFunctionFile()); function.loadJarFile(); //指令 BaseCommand baseCommand = new BaseCommand(compoundLibraryApi, functionSetting, function); //指令注册 getCommand("edit").setExecutor(baseCommand); //事件注册 Bukkit.getPluginManager().registerEvents(new PlayerEditPanelEvent(),this); Bukkit.getPluginManager().registerEvents(new PlayerChatEvent(PushBukkitChatMessages.registerReceiveObject()),this); Bukkit.getPluginManager().registerEvents(new PlayerClickEntity(compoundLibraryApi, baseCommand),this); Bukkit.getPluginManager().registerEvents(new PlayerClickBlock(compoundLibraryApi, baseCommand),this); Bukkit.getConsoleSender().sendMessage( "§b_ _ ____ _______ ______ _ _ _ _____ _ " ); Bukkit.getConsoleSender().sendMessage( "§b | \\ | | _ \\__ __| ____| | (_) | | __ \\ | |" ); Bukkit.getConsoleSender().sendMessage( "§b | \\| | |_) | | | | |__ __| |_| |_| |__) |_ _ _ __ ___| |" ); Bukkit.getConsoleSender().sendMessage( "§b | . ` | _ < | | | __| / _` | | __| ___/ _` | '_ \\ / _ \\ |" ); Bukkit.getConsoleSender().sendMessage( "§b | |\\ | |_) | | | | |___| (_| | | |_| | | (_| | | | | __/ |" ); Bukkit.getConsoleSender().sendMessage( "§b |_| \\_|____/ |_| |______\\__,_|_|\\__|_| \\__,_|_| |_|\\___|_|"); Bukkit.getConsoleSender().sendMessage("§eNBT编辑器加载成功!"); Bukkit.getConsoleSender().sendMessage("§e作者:兔儿神"); Bukkit.getConsoleSender().sendMessage("§e插件已开源,发现bug可以加群反馈,感激不尽"); Bukkit.getConsoleSender().sendMessage("§e插件交流群:978420514"); Bukkit.getConsoleSender().sendMessage("§e最新版本: v1.35"); //插件统计 new Metrics(this,8933); } public void loadJarLogger(String jar, int count) { Bukkit.getConsoleSender().sendMessage("§b成功载入:§a"+jar+", §b功能数:§e"+count); } public static File getFunctionFile() { return new File(NBTEditPanel.plugin.getDataFolder(),"function"); } }
false
856
4
945
3
976
3
945
3
1,158
7
false
false
false
false
false
true
64807_16
import java.awt.*; import java.awt.event.*; import java.awt.image.*; /** * Description: * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br> * Copyright (C), 2001-2018, Yeeku.H.Lee<br> * This program is protected by copyright laws.<br> * Program Name:<br> * Date:<br> * @author Yeeku.H.Lee [email protected] * @version 1.0 */ public class HandDraw { // 画图区的宽度 private final int AREA_WIDTH = 500; // 画图区的高度 private final int AREA_HEIGHT = 400; // 下面的preX、preY保存了上一次鼠标拖动事件的鼠标坐标 private int preX = -1; private int preY = -1; // 定义一个右键菜单用于设置画笔颜色 PopupMenu pop = new PopupMenu(); MenuItem redItem = new MenuItem("红色"); MenuItem greenItem = new MenuItem("绿色"); MenuItem blueItem = new MenuItem("蓝色"); // 定义一个BufferedImage对象 BufferedImage image = new BufferedImage(AREA_WIDTH , AREA_HEIGHT , BufferedImage.TYPE_INT_RGB); // 获取image对象的Graphics Graphics g = image.getGraphics(); private Frame f = new Frame("简单手绘程序"); private DrawCanvas drawArea = new DrawCanvas(); // 用于保存画笔颜色 private Color foreColor = new Color(255, 0 ,0); public void init() { // 定义右键菜单的事件监听器。 ActionListener menuListener = e -> { if (e.getActionCommand().equals("绿色")) { foreColor = new Color(0 , 255 , 0); } if (e.getActionCommand().equals("红色")) { foreColor = new Color(255 , 0 , 0); } if (e.getActionCommand().equals("蓝色")) { foreColor = new Color(0 , 0 , 255); } }; // 为三个菜单添加事件监听器 redItem.addActionListener(menuListener); greenItem.addActionListener(menuListener); blueItem.addActionListener(menuListener); // 将菜单项组合成右键菜单 pop.add(redItem); pop.add(greenItem); pop.add(blueItem); // 将右键菜单添加到drawArea对象中 drawArea.add(pop); // 将image对象的背景色填充成白色 g.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT); drawArea.setPreferredSize(new Dimension(AREA_WIDTH , AREA_HEIGHT)); // 监听鼠标移动动作 drawArea.addMouseMotionListener(new MouseMotionAdapter() { // 实现按下鼠标键并拖动的事件处理器 public void mouseDragged(MouseEvent e) { // 如果preX和preY大于0 if (preX > 0 && preY > 0) { // 设置当前颜色 g.setColor(foreColor); // 绘制从上一次鼠标拖动事件点到本次鼠标拖动事件点的线段 g.drawLine(preX , preY , e.getX() , e.getY()); } // 将当前鼠标事件点的X、Y坐标保存起来 preX = e.getX(); preY = e.getY(); // 重绘drawArea对象 drawArea.repaint(); } }); // 监听鼠标事件 drawArea.addMouseListener(new MouseAdapter() { // 实现鼠标松开的事件处理器 public void mouseReleased(MouseEvent e) { // 弹出右键菜单 if (e.isPopupTrigger()) { pop.show(drawArea , e.getX() , e.getY()); } // 松开鼠标键时,把上一次鼠标拖动事件的X、Y坐标设为-1。 preX = -1; preY = -1; } }); f.add(drawArea); f.pack(); f.setVisible(true); } public static void main(String[] args) { new HandDraw().init(); } class DrawCanvas extends Canvas { // 重写Canvas的paint方法,实现绘画 public void paint(Graphics g) { // 将image绘制到该组件上 g.drawImage(image , 0 , 0 , null); } } }
TunomonSW/crazyJava
crazyJava/11/11.8/HandDraw.java
1,213
// 设置当前颜色
line_comment
zh-cn
import java.awt.*; import java.awt.event.*; import java.awt.image.*; /** * Description: * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br> * Copyright (C), 2001-2018, Yeeku.H.Lee<br> * This program is protected by copyright laws.<br> * Program Name:<br> * Date:<br> * @author Yeeku.H.Lee [email protected] * @version 1.0 */ public class HandDraw { // 画图区的宽度 private final int AREA_WIDTH = 500; // 画图区的高度 private final int AREA_HEIGHT = 400; // 下面的preX、preY保存了上一次鼠标拖动事件的鼠标坐标 private int preX = -1; private int preY = -1; // 定义一个右键菜单用于设置画笔颜色 PopupMenu pop = new PopupMenu(); MenuItem redItem = new MenuItem("红色"); MenuItem greenItem = new MenuItem("绿色"); MenuItem blueItem = new MenuItem("蓝色"); // 定义一个BufferedImage对象 BufferedImage image = new BufferedImage(AREA_WIDTH , AREA_HEIGHT , BufferedImage.TYPE_INT_RGB); // 获取image对象的Graphics Graphics g = image.getGraphics(); private Frame f = new Frame("简单手绘程序"); private DrawCanvas drawArea = new DrawCanvas(); // 用于保存画笔颜色 private Color foreColor = new Color(255, 0 ,0); public void init() { // 定义右键菜单的事件监听器。 ActionListener menuListener = e -> { if (e.getActionCommand().equals("绿色")) { foreColor = new Color(0 , 255 , 0); } if (e.getActionCommand().equals("红色")) { foreColor = new Color(255 , 0 , 0); } if (e.getActionCommand().equals("蓝色")) { foreColor = new Color(0 , 0 , 255); } }; // 为三个菜单添加事件监听器 redItem.addActionListener(menuListener); greenItem.addActionListener(menuListener); blueItem.addActionListener(menuListener); // 将菜单项组合成右键菜单 pop.add(redItem); pop.add(greenItem); pop.add(blueItem); // 将右键菜单添加到drawArea对象中 drawArea.add(pop); // 将image对象的背景色填充成白色 g.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT); drawArea.setPreferredSize(new Dimension(AREA_WIDTH , AREA_HEIGHT)); // 监听鼠标移动动作 drawArea.addMouseMotionListener(new MouseMotionAdapter() { // 实现按下鼠标键并拖动的事件处理器 public void mouseDragged(MouseEvent e) { // 如果preX和preY大于0 if (preX > 0 && preY > 0) { // 设置 <SUF> g.setColor(foreColor); // 绘制从上一次鼠标拖动事件点到本次鼠标拖动事件点的线段 g.drawLine(preX , preY , e.getX() , e.getY()); } // 将当前鼠标事件点的X、Y坐标保存起来 preX = e.getX(); preY = e.getY(); // 重绘drawArea对象 drawArea.repaint(); } }); // 监听鼠标事件 drawArea.addMouseListener(new MouseAdapter() { // 实现鼠标松开的事件处理器 public void mouseReleased(MouseEvent e) { // 弹出右键菜单 if (e.isPopupTrigger()) { pop.show(drawArea , e.getX() , e.getY()); } // 松开鼠标键时,把上一次鼠标拖动事件的X、Y坐标设为-1。 preX = -1; preY = -1; } }); f.add(drawArea); f.pack(); f.setVisible(true); } public static void main(String[] args) { new HandDraw().init(); } class DrawCanvas extends Canvas { // 重写Canvas的paint方法,实现绘画 public void paint(Graphics g) { // 将image绘制到该组件上 g.drawImage(image , 0 , 0 , null); } } }
false
1,041
4
1,213
4
1,127
4
1,213
4
1,601
10
false
false
false
false
false
true
46132_4
package com.ozm.tmall.entity.service; import com.ozm.tmall.entity.dao.ProductDAO; import com.ozm.tmall.entity.dao.ProductImageDAO; import com.ozm.tmall.entity.pojo.OrderItem; import com.ozm.tmall.entity.pojo.Product; import com.ozm.tmall.entity.pojo.ProductImage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; @Service @CacheConfig(cacheNames="productImages") public class ProductImageService { //创建ProductImageService,提供CRD。 //同时还提供了两个常量,分别表示单个图片和详情图片: public static final String type_single = "single"; public static final String type_detail = "detail"; @Autowired ProductImageDAO productImageDAO; //添加图片 @CacheEvict(allEntries=true) public void add(ProductImage bean){ productImageDAO.save(bean); } //查找单个照片列表 @Cacheable(key="'productImages-single-pid-'+ #p0.id") public List<ProductImage> listSingleProductImages(Product product){ return productImageDAO.findByProductAndTypeOrderByIdDesc(product,type_single); } //查找详细照片列表 @Cacheable(key="'productImages-detail-pid-'+ #p0.id") public List<ProductImage> listDetailProductImages(Product product){ return productImageDAO.findByProductAndTypeOrderByIdDesc(product,type_detail); } @Cacheable(key="'productImages-one-'+ #p0") public ProductImage get(int id) { return productImageDAO.findOne(id); } @CacheEvict(allEntries=true) //删除图片 public void delete(int id) { productImageDAO.delete(id); } //设置预览图 public void setFirstProdutImage(Product product) { //取出ProductImage 列表对象 一个Product id对应多个ProductImages对象 ,在乎你传入什么Product List<ProductImage> list = listSingleProductImages(product); //将取出的ProductImage 对象逐一赋值到对应的Product上 if (!list.isEmpty()){ product.setFirstProductImage(list.get(0)); }else{ product.setFirstProductImage(new ProductImage()); } } //为多个Product对象设置预览图 // (Ps:listProduct页显示多个Product,所以是为多个Product对象在内部使用setter的方式对Pro~img对象赋值) public void setFirstProdutImages(List<Product> products) { for (Product product : products) setFirstProdutImage(product); } public void setFirstProdutImagesOnOrderItems(List<OrderItem> ois) { for (OrderItem orderItem : ois) { setFirstProdutImage(orderItem.getProduct()); } } }
Tyler-Ou/tmall_springboot
tmall_springboot/src/main/java/com/ozm/tmall/entity/service/ProductImageService.java
743
//查找详细照片列表
line_comment
zh-cn
package com.ozm.tmall.entity.service; import com.ozm.tmall.entity.dao.ProductDAO; import com.ozm.tmall.entity.dao.ProductImageDAO; import com.ozm.tmall.entity.pojo.OrderItem; import com.ozm.tmall.entity.pojo.Product; import com.ozm.tmall.entity.pojo.ProductImage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; @Service @CacheConfig(cacheNames="productImages") public class ProductImageService { //创建ProductImageService,提供CRD。 //同时还提供了两个常量,分别表示单个图片和详情图片: public static final String type_single = "single"; public static final String type_detail = "detail"; @Autowired ProductImageDAO productImageDAO; //添加图片 @CacheEvict(allEntries=true) public void add(ProductImage bean){ productImageDAO.save(bean); } //查找单个照片列表 @Cacheable(key="'productImages-single-pid-'+ #p0.id") public List<ProductImage> listSingleProductImages(Product product){ return productImageDAO.findByProductAndTypeOrderByIdDesc(product,type_single); } //查找 <SUF> @Cacheable(key="'productImages-detail-pid-'+ #p0.id") public List<ProductImage> listDetailProductImages(Product product){ return productImageDAO.findByProductAndTypeOrderByIdDesc(product,type_detail); } @Cacheable(key="'productImages-one-'+ #p0") public ProductImage get(int id) { return productImageDAO.findOne(id); } @CacheEvict(allEntries=true) //删除图片 public void delete(int id) { productImageDAO.delete(id); } //设置预览图 public void setFirstProdutImage(Product product) { //取出ProductImage 列表对象 一个Product id对应多个ProductImages对象 ,在乎你传入什么Product List<ProductImage> list = listSingleProductImages(product); //将取出的ProductImage 对象逐一赋值到对应的Product上 if (!list.isEmpty()){ product.setFirstProductImage(list.get(0)); }else{ product.setFirstProductImage(new ProductImage()); } } //为多个Product对象设置预览图 // (Ps:listProduct页显示多个Product,所以是为多个Product对象在内部使用setter的方式对Pro~img对象赋值) public void setFirstProdutImages(List<Product> products) { for (Product product : products) setFirstProdutImage(product); } public void setFirstProdutImagesOnOrderItems(List<OrderItem> ois) { for (OrderItem orderItem : ois) { setFirstProdutImage(orderItem.getProduct()); } } }
false
628
5
743
6
772
5
743
6
935
17
false
false
false
false
false
true
8767_0
public class People { //属性(成员变量) 有什么 double height; //身高 int age; //年龄 int sex; //性别,0为男性,非0为女性 //方法 干什么 void cry(){ System.out.println("我在哭!"); } void laugh(){ System.out.println("我在笑!"); } void printBaseMes(){ System.out.println("我的身高是"+height+"cm"); System.out.println("我的年龄是"+age+"岁"); if(this.sex==0) System.out.println("我是男性!"); else System.out.println("我是女性!"); } }
TyouSF/JavaLR
Object-Oriented/day13/People.java
176
//属性(成员变量) 有什么
line_comment
zh-cn
public class People { //属性 <SUF> double height; //身高 int age; //年龄 int sex; //性别,0为男性,非0为女性 //方法 干什么 void cry(){ System.out.println("我在哭!"); } void laugh(){ System.out.println("我在笑!"); } void printBaseMes(){ System.out.println("我的身高是"+height+"cm"); System.out.println("我的年龄是"+age+"岁"); if(this.sex==0) System.out.println("我是男性!"); else System.out.println("我是女性!"); } }
false
140
8
176
8
167
8
176
8
217
15
false
false
false
false
false
true
27929_27
package com.wangpos.datastructure.leetcode2; import com.wangpos.datastructure.leetcode.LeetCode464; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.function.Consumer; public class LeetCode220 { public static void main(String args[]) { Solution solution = new Solution(); long nums[] = new long[]{1, 2, 3, 1}; long nums1[] = new long[]{1, 0, 1, 1}; long nums2[] = new long[]{1, 5, 9, 1, 5, 9}; long nums3[] = new long[]{-1, 2147483647}; int nums4[] = new int[]{2147483647, -2147483647}; // System.out.println(solution.containsNearbyAlmostDuplicate(nums,3,0)); // // System.out.println(solution.containsNearbyAlmostDuplicate(nums1,1,2)); // System.out.println(solution.containsNearbyAlmostDuplicate(nums2,2,3)); // System.out.println(solution.containsNearbyAlmostDuplicate(nums3,1,2147483647)); System.out.println(solution.containsNearbyAlmostDuplicate(nums4, 1, 2147483647)); // 报错的两种情况,因为虽然Number 是Float 父类,但是也推断不出来 List<Number> list44 是List<Integer>父类 // List<Float> list4 = new ArrayList<Number>(); // List<Number> list44 = new ArrayList<Float>(); //所以,就算容器里装的东西之间有继承关系,但容器之间是没有继承关系的 //为了让泛型用起来更舒服,Sun的大脑袋们就想出了<? extends T>和<? super T>的办法,来让”水果盘子“和”苹果盘子“之间发生关系。 // // List<? extends Number> list11 = new ArrayList<Number>(); // //Integer是Number的子类 // List<? extends Number> list22 = new ArrayList<Integer>(); // //Float也是Number的子类 // List<? extends Number> list33 = new ArrayList<Float>(); // // //上面只能遍历不能添加 获取Number 类型 // Number a = list11.get(0); // right // // Integer b = list22.get(0);// Error 只能取出Number 类型 // // 适合用场景,限制集合的修改操作, 只能获取Number 类型的元素 // // // // List<? super Float> list = new ArrayList<Float>(); // //Number是Float的父类 // List<? super Float> list2 = new ArrayList<Number>(); // list2.add(0.1f);//可以调价Float类型,相当于Float 可以复制给Number;子类可以复制给父类 // Object obj = list2.get(0); // //Object是Number的父类 // List<? super Float> list3 = new ArrayList<Object>(); // // //上面只能添加Float类型,但读出不出来具体类型,只能是Object,限制了集合的使用 // //// PECS(Producer Extends Consumer Super)原则,已经很好理解了: //// //// 频繁往外读取内容的,适合用上界Extends。 //// 经常往里插入的,适合用下界Super。 // Collections.copy(new ArrayList<Float>(),new ArrayList<Float>()); // Collections.copy(new ArrayList<Number>(),new ArrayList<Float>()); // // Collections.copy(new ArrayList<Float>(),new ArrayList<Number>());//Error //// Java中所有类的顶级父类是Object,可以认为Null是所有类的子类。 } static class Solution { // public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { // Set<String> records = new HashSet<>(); // for (int i = 0; i < nums.length; i++) { // int maxLength = i + k; // if (maxLength >= nums.length) maxLength = nums.length-1; // // // for (int j = i+1; j <= maxLength; j++) { // //去除重复计算 // if(records.contains(i+"_"+j)) continue; // long a = nums[i]; // long b = nums[j]; // long result = a - b; // if (Math.abs(result) <= t) { // return true; // } // records.add(i+"_"+j); // } // } // // return false; // } /** * TreeSet 实现使用TreeMap ,TreeMap 实现是红黑树,默认自然顺序 * TreeSet为基本操作(add、remove 和 contains)提供受保证的 log(n) 时间开销。 * 通过ceiling 和Floor 可以找到最贴近的元素 * * @param nums * @param k * @param t * @return */ public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { //自然平衡二叉树,来表示滑动窗口,这个窗口最大size 不能大于k TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < nums.length; ++i) { // Find the successor of current element // ceiling(E e) 方法返回在这个集合中大于或者等于给定元素的最小元素,如果不存在这样的元素,返回null. // 集合中大于此元素的最小值,最小值 Integer s = set.ceiling(nums[i]); //s - nums[i]<=t 等式变换得到,集合中满足条件的最小值都不可以,那就其余都不行 if (s != null && s <= nums[i] + t) return true; // 集合中小于此元素的最大值 // Find the predecessor of current element Integer g = set.floor(nums[i]); if (g != null && nums[i] <= g + t) return true; //没找到添加到树中,并且会自然平衡 set.add(nums[i]); if (set.size() > k) { //向前数第k个移除 set.remove(nums[i - k]); } } return false; } } }
UCodeUStory/DataStructure
app/src/main/java/com/wangpos/datastructure/leetcode2/LeetCode220.java
1,606
//// 频繁往外读取内容的,适合用上界Extends。
line_comment
zh-cn
package com.wangpos.datastructure.leetcode2; import com.wangpos.datastructure.leetcode.LeetCode464; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.function.Consumer; public class LeetCode220 { public static void main(String args[]) { Solution solution = new Solution(); long nums[] = new long[]{1, 2, 3, 1}; long nums1[] = new long[]{1, 0, 1, 1}; long nums2[] = new long[]{1, 5, 9, 1, 5, 9}; long nums3[] = new long[]{-1, 2147483647}; int nums4[] = new int[]{2147483647, -2147483647}; // System.out.println(solution.containsNearbyAlmostDuplicate(nums,3,0)); // // System.out.println(solution.containsNearbyAlmostDuplicate(nums1,1,2)); // System.out.println(solution.containsNearbyAlmostDuplicate(nums2,2,3)); // System.out.println(solution.containsNearbyAlmostDuplicate(nums3,1,2147483647)); System.out.println(solution.containsNearbyAlmostDuplicate(nums4, 1, 2147483647)); // 报错的两种情况,因为虽然Number 是Float 父类,但是也推断不出来 List<Number> list44 是List<Integer>父类 // List<Float> list4 = new ArrayList<Number>(); // List<Number> list44 = new ArrayList<Float>(); //所以,就算容器里装的东西之间有继承关系,但容器之间是没有继承关系的 //为了让泛型用起来更舒服,Sun的大脑袋们就想出了<? extends T>和<? super T>的办法,来让”水果盘子“和”苹果盘子“之间发生关系。 // // List<? extends Number> list11 = new ArrayList<Number>(); // //Integer是Number的子类 // List<? extends Number> list22 = new ArrayList<Integer>(); // //Float也是Number的子类 // List<? extends Number> list33 = new ArrayList<Float>(); // // //上面只能遍历不能添加 获取Number 类型 // Number a = list11.get(0); // right // // Integer b = list22.get(0);// Error 只能取出Number 类型 // // 适合用场景,限制集合的修改操作, 只能获取Number 类型的元素 // // // // List<? super Float> list = new ArrayList<Float>(); // //Number是Float的父类 // List<? super Float> list2 = new ArrayList<Number>(); // list2.add(0.1f);//可以调价Float类型,相当于Float 可以复制给Number;子类可以复制给父类 // Object obj = list2.get(0); // //Object是Number的父类 // List<? super Float> list3 = new ArrayList<Object>(); // // //上面只能添加Float类型,但读出不出来具体类型,只能是Object,限制了集合的使用 // //// PECS(Producer Extends Consumer Super)原则,已经很好理解了: //// //// 频繁 <SUF> //// 经常往里插入的,适合用下界Super。 // Collections.copy(new ArrayList<Float>(),new ArrayList<Float>()); // Collections.copy(new ArrayList<Number>(),new ArrayList<Float>()); // // Collections.copy(new ArrayList<Float>(),new ArrayList<Number>());//Error //// Java中所有类的顶级父类是Object,可以认为Null是所有类的子类。 } static class Solution { // public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { // Set<String> records = new HashSet<>(); // for (int i = 0; i < nums.length; i++) { // int maxLength = i + k; // if (maxLength >= nums.length) maxLength = nums.length-1; // // // for (int j = i+1; j <= maxLength; j++) { // //去除重复计算 // if(records.contains(i+"_"+j)) continue; // long a = nums[i]; // long b = nums[j]; // long result = a - b; // if (Math.abs(result) <= t) { // return true; // } // records.add(i+"_"+j); // } // } // // return false; // } /** * TreeSet 实现使用TreeMap ,TreeMap 实现是红黑树,默认自然顺序 * TreeSet为基本操作(add、remove 和 contains)提供受保证的 log(n) 时间开销。 * 通过ceiling 和Floor 可以找到最贴近的元素 * * @param nums * @param k * @param t * @return */ public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { //自然平衡二叉树,来表示滑动窗口,这个窗口最大size 不能大于k TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < nums.length; ++i) { // Find the successor of current element // ceiling(E e) 方法返回在这个集合中大于或者等于给定元素的最小元素,如果不存在这样的元素,返回null. // 集合中大于此元素的最小值,最小值 Integer s = set.ceiling(nums[i]); //s - nums[i]<=t 等式变换得到,集合中满足条件的最小值都不可以,那就其余都不行 if (s != null && s <= nums[i] + t) return true; // 集合中小于此元素的最大值 // Find the predecessor of current element Integer g = set.floor(nums[i]); if (g != null && nums[i] <= g + t) return true; //没找到添加到树中,并且会自然平衡 set.add(nums[i]); if (set.size() > k) { //向前数第k个移除 set.remove(nums[i - k]); } } return false; } } }
false
1,422
19
1,606
20
1,570
16
1,606
20
2,028
31
false
false
false
false
false
true
45289_10
package com.wangpos.soundrecordview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Allen on 2017/9/18. */ public class RecordView extends CustomSurfaceView { private static final String TAG = "RecordView"; private Paint mMainPaint; //背景色 private int mBgColor = Color.WHITE; //波浪颜色 private int mLineColor = Color.parseColor("#FF0000"); //主要线宽 private int mMainWidth = 7; private int mHeight; private int mWidth; private float mCenterY; /** * 点数,当然越多越细腻 */ private int pointSize = 200; /** * 声音分贝数 */ private float volume = 1; /** * 速度 */ private float velocity = 1; /** * 默认线的初始化振幅 */ private float[] shakeRatioArray = {1.6f,1.6f,1.6f}; /** * 默认线的偏移量 */ private float[] lineOffset = {0f,0.1f,0.2f}; /** * 默认颜色 */ private int[] lineColor = {Color.RED,Color.GREEN,Color.BLUE}; /** * 线的集合 */ Map<Integer, List<Point>> lines = new HashMap<>(); public RecordView(Context context) { this(context, null); } public RecordView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RecordView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initAttrs(attrs); initPaint(); } /** * 自定义属性 * * @param attrs */ private void initAttrs(AttributeSet attrs) { // TODO: 2017/9/18 } /** * 初始化画笔 */ private void initPaint() { mMainPaint = new Paint(); mMainPaint.setColor(mLineColor); mMainPaint.setStrokeWidth(mMainWidth); mMainPaint.setStyle(Paint.Style.FILL); mMainPaint.setAntiAlias(true); mMainPaint.setStrokeCap(Paint.Cap.ROUND); mMainPaint.setStrokeJoin(Paint.Join.ROUND); } @Override public void drawContent(Canvas canvas, long millisPassed) { initDraw(canvas, millisPassed); drawLine(canvas); } /** * 初始化参数以及计算出点的位置 * * @param canvas * @param millisPassed */ private void initDraw(Canvas canvas, long millisPassed) { lines.clear(); //根据时间偏移 float offset = millisPassed / 100f * velocity; mWidth = canvas.getWidth(); mHeight = canvas.getHeight(); mCenterY = mHeight / 2; float dx = (float) mWidth / (pointSize - 1);// 必须为float,否则丢失 Log.i("qiyue", "dx = " + dx + "offset=" + offset); for (int j = 0; j < shakeRatioArray.length; j++) { List<Point>points = new ArrayList<>(); initLine(offset, dx, shakeRatioArray[j], points,lineOffset[j]); lines.put(j,points); } } /** * 初始化一条线 * @param offset * @param dx * @param shakeRatio * @param points */ private void initLine(float offset, float dx, float shakeRatio, List<Point> points,float lOffset) { for (int i = 0; i < pointSize; i++) { float y; float x = dx * i; float adapterShakeParam; adapterShakeParam = convergenFunction(i); Log.i("qiyue", "adapterShakeParam=" + adapterShakeParam); y = calculateY(x, offset, adapterShakeParam, shakeRatio,lOffset); points.add(new Point(x, y)); } } /** * 收敛函数 这个函数可以用一个二次函数,效果更好 * * @param i * @return */ private float convergenFunction(int i) { float adapterShakeParam; if (i < pointSize / 2) { // 增加 0 adapterShakeParam = i; } else { // 减少 1 0 adapterShakeParam = pointSize - i; } return adapterShakeParam; } /** * 画线 * * @param canvas */ private void drawLine(Canvas canvas) { canvas.drawColor(mBgColor); Log.i("qiyue", "drawLine"); for (Integer key:lines.keySet()){ List<Point>points = lines.get(key); for (int i = 1; i < pointSize; i++) { Point p1 = points.get(i - 1); Point p2 = points.get(i); Log.i("qiyue", "p1=" + p1); canvas.drawLine(p1.x, p1.y, p2.x, p2.y, mMainPaint); } } } @Override public void stopAnim() { super.stopAnim(); clearDraw(); } /** * 设置音量大小 * * @param volume */ public void setVolume(int volume) { this.volume = volume; } public void clearDraw() { Canvas canvas = null; try { canvas = getHolder().lockCanvas(null); canvas.drawColor(mBgColor); } catch (Exception e) { } finally { if (canvas != null) { getHolder().unlockCanvasAndPost(canvas); } } } /** * 计算Y轴坐标 * * @param x * @param offset 偏移量 * @return */ private float calculateY(float x, float offset, float adapterShakeParam, float shakeRatio,float lOffset) { /** * 弧度取值范围 0 2π */ double rad = Math.toRadians(x) + lOffset; double fx = Math.sin(rad + offset ); float dy = (float) (fx); float calculateVolume = getCalculateVolume(); float finalDy = dy * adapterShakeParam * shakeRatio * calculateVolume; return (float) (mCenterY - finalDy); } /** * 声音分贝计算 * * @return */ private float getCalculateVolume() { return (volume + 10) / 20f; } /** * 绘制点Bean */ class Point { @Override public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } public float x; public float y; public Point(float x, float y) { this.x = x; this.y = y; } } }
UCodeUStory/RecordVoiceView
source/彩带线.java
1,748
/** * 线的集合 */
block_comment
zh-cn
package com.wangpos.soundrecordview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Allen on 2017/9/18. */ public class RecordView extends CustomSurfaceView { private static final String TAG = "RecordView"; private Paint mMainPaint; //背景色 private int mBgColor = Color.WHITE; //波浪颜色 private int mLineColor = Color.parseColor("#FF0000"); //主要线宽 private int mMainWidth = 7; private int mHeight; private int mWidth; private float mCenterY; /** * 点数,当然越多越细腻 */ private int pointSize = 200; /** * 声音分贝数 */ private float volume = 1; /** * 速度 */ private float velocity = 1; /** * 默认线的初始化振幅 */ private float[] shakeRatioArray = {1.6f,1.6f,1.6f}; /** * 默认线的偏移量 */ private float[] lineOffset = {0f,0.1f,0.2f}; /** * 默认颜色 */ private int[] lineColor = {Color.RED,Color.GREEN,Color.BLUE}; /** * 线的集 <SUF>*/ Map<Integer, List<Point>> lines = new HashMap<>(); public RecordView(Context context) { this(context, null); } public RecordView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RecordView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initAttrs(attrs); initPaint(); } /** * 自定义属性 * * @param attrs */ private void initAttrs(AttributeSet attrs) { // TODO: 2017/9/18 } /** * 初始化画笔 */ private void initPaint() { mMainPaint = new Paint(); mMainPaint.setColor(mLineColor); mMainPaint.setStrokeWidth(mMainWidth); mMainPaint.setStyle(Paint.Style.FILL); mMainPaint.setAntiAlias(true); mMainPaint.setStrokeCap(Paint.Cap.ROUND); mMainPaint.setStrokeJoin(Paint.Join.ROUND); } @Override public void drawContent(Canvas canvas, long millisPassed) { initDraw(canvas, millisPassed); drawLine(canvas); } /** * 初始化参数以及计算出点的位置 * * @param canvas * @param millisPassed */ private void initDraw(Canvas canvas, long millisPassed) { lines.clear(); //根据时间偏移 float offset = millisPassed / 100f * velocity; mWidth = canvas.getWidth(); mHeight = canvas.getHeight(); mCenterY = mHeight / 2; float dx = (float) mWidth / (pointSize - 1);// 必须为float,否则丢失 Log.i("qiyue", "dx = " + dx + "offset=" + offset); for (int j = 0; j < shakeRatioArray.length; j++) { List<Point>points = new ArrayList<>(); initLine(offset, dx, shakeRatioArray[j], points,lineOffset[j]); lines.put(j,points); } } /** * 初始化一条线 * @param offset * @param dx * @param shakeRatio * @param points */ private void initLine(float offset, float dx, float shakeRatio, List<Point> points,float lOffset) { for (int i = 0; i < pointSize; i++) { float y; float x = dx * i; float adapterShakeParam; adapterShakeParam = convergenFunction(i); Log.i("qiyue", "adapterShakeParam=" + adapterShakeParam); y = calculateY(x, offset, adapterShakeParam, shakeRatio,lOffset); points.add(new Point(x, y)); } } /** * 收敛函数 这个函数可以用一个二次函数,效果更好 * * @param i * @return */ private float convergenFunction(int i) { float adapterShakeParam; if (i < pointSize / 2) { // 增加 0 adapterShakeParam = i; } else { // 减少 1 0 adapterShakeParam = pointSize - i; } return adapterShakeParam; } /** * 画线 * * @param canvas */ private void drawLine(Canvas canvas) { canvas.drawColor(mBgColor); Log.i("qiyue", "drawLine"); for (Integer key:lines.keySet()){ List<Point>points = lines.get(key); for (int i = 1; i < pointSize; i++) { Point p1 = points.get(i - 1); Point p2 = points.get(i); Log.i("qiyue", "p1=" + p1); canvas.drawLine(p1.x, p1.y, p2.x, p2.y, mMainPaint); } } } @Override public void stopAnim() { super.stopAnim(); clearDraw(); } /** * 设置音量大小 * * @param volume */ public void setVolume(int volume) { this.volume = volume; } public void clearDraw() { Canvas canvas = null; try { canvas = getHolder().lockCanvas(null); canvas.drawColor(mBgColor); } catch (Exception e) { } finally { if (canvas != null) { getHolder().unlockCanvasAndPost(canvas); } } } /** * 计算Y轴坐标 * * @param x * @param offset 偏移量 * @return */ private float calculateY(float x, float offset, float adapterShakeParam, float shakeRatio,float lOffset) { /** * 弧度取值范围 0 2π */ double rad = Math.toRadians(x) + lOffset; double fx = Math.sin(rad + offset ); float dy = (float) (fx); float calculateVolume = getCalculateVolume(); float finalDy = dy * adapterShakeParam * shakeRatio * calculateVolume; return (float) (mCenterY - finalDy); } /** * 声音分贝计算 * * @return */ private float getCalculateVolume() { return (volume + 10) / 20f; } /** * 绘制点Bean */ class Point { @Override public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } public float x; public float y; public Point(float x, float y) { this.x = x; this.y = y; } } }
false
1,633
11
1,747
9
1,889
10
1,748
9
2,185
12
false
false
false
false
false
true
5236_20
package lucene; import java.io.*; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.ArrayList; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.store.*; import org.jsoup.Jsoup; import ICTCLAS_Analyzer.*; public class Index{ // indexPath - 存放index final public static String indexPath = "D:/2017.2/searchEngine/index"; // originDataPath - 存放.txt final private static String originDataPath = "D:/2017.2/searchEngine/originData"; final private static String[] uselessTags = {"<a ","</a>","<em>","</em>","<span ","</span>","<strong>","</strong>","<iframe ","</iframe>","&nbsp"}; final private static Pattern ptTitle = Pattern.compile("(<title>)(.*)(</title>)"); final private static Pattern ptUrl = Pattern.compile("(<url>)(.*)(</url>)"); final private static Pattern ptHtml = Pattern.compile("(<[^>]*>)"); private static Analyzer analyzer; private static Directory ramDirectory; // 在RAM中进行操作,加快速度,最后将创建的索引放在磁盘上. private static Directory fsDirectory; // 最后存在这里 private static IndexWriterConfig iwc; private static IndexWriter writer; private static File[] files; // 初始化 private static void init()throws IOException { ramDirectory = new RAMDirectory(); analyzer = new NLPIRTokenizerAnalyzer("", 1, "", "", false); iwc = new IndexWriterConfig(analyzer); iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); iwc.setRAMBufferSizeMB(4096.0); writer = new IndexWriter(ramDirectory, iwc); files = new File(originDataPath).listFiles(); fsDirectory = FSDirectory.open(Paths.get(indexPath)); } // 过滤无效标签 public static String filterTags(String s){ StringBuilder sb = new StringBuilder(s); // uselessTags中的前五对一起处理 for(int i = 0; i < 10; i+=2){ int j = sb.indexOf(uselessTags[i]); // 一直删除,直到sb里找不到. while(j > -1) { int k = sb.indexOf(uselessTags[i + 1]); if(k < 0) { sb.delete(j, j + uselessTags[i].length()); j = sb.indexOf(uselessTags[i]); continue; } if (k <= j) { sb.delete(k, k + uselessTags[i + 1].length()); continue; } sb.delete(j, k + uselessTags[i + 1].length()); j = sb.indexOf(uselessTags[i]); } } //"&nbsp" 单独处理 String nbsp = "&nbsp;"; int i = sb.indexOf(nbsp); while(i > -1) { sb.delete(i, i + nbsp.length()); i = sb.indexOf(nbsp); } return sb.toString(); } // 预处理文件,去掉无效标签, // 针对有效标签,以及content // 创建索引,存入writer public static void createIndexPerFile(File file) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); // count - 统计docs数量,方便输出进度 int count = 0; String content; boolean flag = false; while((content = br.readLine()) != null) { // 一次循环处理一个doc if(!content.equals("<doc>")) continue; if(count %400 == 0){ // 输出进度,每400个doc输出一个'.' System.out.print("."); } count++; Document docLucene = new Document(); StringBuffer body = new StringBuffer(); // while((content = br.readLine()) != null){ // 过滤无效标签 content = filterTags(content); if(content.length() == 0) // blank continue; if(content.equals("</doc>")) { // </doc> - doc结束 break; } if(content.charAt(0) != '<'){ // 找到content body,加入StringBuffer body.append(content); continue; } if(content.charAt(1) == 'm'){ // <meta attr> org.jsoup.nodes.Document doc = Jsoup.parse(content); org.jsoup.select.Elements attribute = doc.select("meta"); if(attribute.size() == 0) continue; if(attribute.attr("name").equals("keywords")) docLucene.add(new TextField("keywords", attribute.attr("content"), Store.YES)); else if(attribute.attr("name").equals("description") && (docLucene.get("description")==null || docLucene.get("description").length() == 0)) docLucene.add(new TextField("description", attribute.attr("content"), Store.YES)); else if(attribute.attr("name").equals("publishid")&& (docLucene.get("publishid")==null || docLucene.get("publishid").length() == 0)) docLucene.add(new StringField("publishid", attribute.attr("content"), Store.YES)); else if(attribute.attr("name").equals("subjectid")&& (docLucene.get("subjectid")==null || docLucene.get("subjectid").length() == 0)) docLucene.add(new StringField("subjectid", attribute.attr("content"), Store.YES)); } else{ Matcher m = ptTitle.matcher(content); String tmp; if(m.find()){ tmp = m.group(2).trim(); if(docLucene.get("title") == null || docLucene.get("title").length() == 0) docLucene.add(new TextField("title", tmp, Store.YES)); } m = ptUrl.matcher(content); if(m.find()){ tmp = m.group(2).trim(); if(docLucene.get("url") == null || docLucene.get("url").length() == 0) docLucene.add(new StringField("url", tmp, Store.YES)); } } } // 删除意料之外的标签. Matcher m = ptHtml.matcher(body); StringBuffer sb = new StringBuffer(); while(m.find()){ // 用StringBuffer,不用StringBuilder的原因,就在于这里要用前者. // 将m匹配到的部分用""替代,并且把""与""之间的部分加到sb里. m.appendReplacement(sb, ""); } // 将body剩下的部分加入到sb中. m.appendTail(sb); body = sb; // 标签彻底处理完毕 docLucene.add(new TextField("contents", body.toString(), Store.YES)); flag = false; try { writer.addDocument(docLucene); }catch(RuntimeException e){ System.out.println(docLucene.getField("title")); flag = true; // writer.delete } if(flag == false){ writer.flush(); writer.commit(); } } br.close(); } // 用于测试 - 在console中输出search结果,方便与tomcat结果比较. public static ArrayList<Map<String, String>> search(String q)throws IOException{ DirectoryReader reader = DirectoryReader.open(fsDirectory); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser("contents", analyzer); ArrayList<Map<String, String>> result = new ArrayList<>(); try { Query query = parser.parse(q); // 前10个 ScoreDoc[] hits = searcher.search(query, 10).scoreDocs; String contents; for (ScoreDoc hit : hits) { Document hitDoc = searcher.doc(hit.doc); Map<String, String> map = new HashMap<String, String>(); map.put("url", hitDoc.get("url")); map.put("title", hitDoc.get("title")); map.put("subjectid", hitDoc.get("subjectid")); map.put("publishid", hitDoc.get("publishid")); map.put("description", hitDoc.get("description")); map.put("keywords", hitDoc.get("keywords")); map.put("score", Float.toString(hit.score)); contents = hitDoc.get("contents"); if (contents.length() > 100) contents = contents.substring(0, 100) + "..."; map.put("contents", contents); // highlighter.setTextFragmenter(new SimpleFragmenter(contents.length())); // TokenStream tokenStream = analyzer.tokenStream("contents", new StringReader(contents)); // highLightText = highlighter.getBestFragment(tokenStream, contents); // map.put("contents", highLightText); result.add(map); } result = Search.search(q); reader.close(); fsDirectory.close(); }catch(Exception e){ e.printStackTrace(); } return result; } public static void main(String[] args)throws IOException { init(); if(fsDirectory.listAll().length == 0) { // 迭代处理每个.txt文件 for (File file : files) { System.out.print("creating index for " + file.getName()); createIndexPerFile(file); System.out.println("\n " + file.getName() + " done!"); } writer.forceMerge(1); writer.close(); } for (String file : ramDirectory.listAll()) { fsDirectory.copyFrom(ramDirectory, file, file, IOContext.DEFAULT); } search("篮球"); } }
USTC-Resource/USTC-Course
Web-信息处理与应用/labs/lab1-搜索引擎/src/lucene/Index.java
2,561
// 删除意料之外的标签.
line_comment
zh-cn
package lucene; import java.io.*; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.ArrayList; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.store.*; import org.jsoup.Jsoup; import ICTCLAS_Analyzer.*; public class Index{ // indexPath - 存放index final public static String indexPath = "D:/2017.2/searchEngine/index"; // originDataPath - 存放.txt final private static String originDataPath = "D:/2017.2/searchEngine/originData"; final private static String[] uselessTags = {"<a ","</a>","<em>","</em>","<span ","</span>","<strong>","</strong>","<iframe ","</iframe>","&nbsp"}; final private static Pattern ptTitle = Pattern.compile("(<title>)(.*)(</title>)"); final private static Pattern ptUrl = Pattern.compile("(<url>)(.*)(</url>)"); final private static Pattern ptHtml = Pattern.compile("(<[^>]*>)"); private static Analyzer analyzer; private static Directory ramDirectory; // 在RAM中进行操作,加快速度,最后将创建的索引放在磁盘上. private static Directory fsDirectory; // 最后存在这里 private static IndexWriterConfig iwc; private static IndexWriter writer; private static File[] files; // 初始化 private static void init()throws IOException { ramDirectory = new RAMDirectory(); analyzer = new NLPIRTokenizerAnalyzer("", 1, "", "", false); iwc = new IndexWriterConfig(analyzer); iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); iwc.setRAMBufferSizeMB(4096.0); writer = new IndexWriter(ramDirectory, iwc); files = new File(originDataPath).listFiles(); fsDirectory = FSDirectory.open(Paths.get(indexPath)); } // 过滤无效标签 public static String filterTags(String s){ StringBuilder sb = new StringBuilder(s); // uselessTags中的前五对一起处理 for(int i = 0; i < 10; i+=2){ int j = sb.indexOf(uselessTags[i]); // 一直删除,直到sb里找不到. while(j > -1) { int k = sb.indexOf(uselessTags[i + 1]); if(k < 0) { sb.delete(j, j + uselessTags[i].length()); j = sb.indexOf(uselessTags[i]); continue; } if (k <= j) { sb.delete(k, k + uselessTags[i + 1].length()); continue; } sb.delete(j, k + uselessTags[i + 1].length()); j = sb.indexOf(uselessTags[i]); } } //"&nbsp" 单独处理 String nbsp = "&nbsp;"; int i = sb.indexOf(nbsp); while(i > -1) { sb.delete(i, i + nbsp.length()); i = sb.indexOf(nbsp); } return sb.toString(); } // 预处理文件,去掉无效标签, // 针对有效标签,以及content // 创建索引,存入writer public static void createIndexPerFile(File file) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); // count - 统计docs数量,方便输出进度 int count = 0; String content; boolean flag = false; while((content = br.readLine()) != null) { // 一次循环处理一个doc if(!content.equals("<doc>")) continue; if(count %400 == 0){ // 输出进度,每400个doc输出一个'.' System.out.print("."); } count++; Document docLucene = new Document(); StringBuffer body = new StringBuffer(); // while((content = br.readLine()) != null){ // 过滤无效标签 content = filterTags(content); if(content.length() == 0) // blank continue; if(content.equals("</doc>")) { // </doc> - doc结束 break; } if(content.charAt(0) != '<'){ // 找到content body,加入StringBuffer body.append(content); continue; } if(content.charAt(1) == 'm'){ // <meta attr> org.jsoup.nodes.Document doc = Jsoup.parse(content); org.jsoup.select.Elements attribute = doc.select("meta"); if(attribute.size() == 0) continue; if(attribute.attr("name").equals("keywords")) docLucene.add(new TextField("keywords", attribute.attr("content"), Store.YES)); else if(attribute.attr("name").equals("description") && (docLucene.get("description")==null || docLucene.get("description").length() == 0)) docLucene.add(new TextField("description", attribute.attr("content"), Store.YES)); else if(attribute.attr("name").equals("publishid")&& (docLucene.get("publishid")==null || docLucene.get("publishid").length() == 0)) docLucene.add(new StringField("publishid", attribute.attr("content"), Store.YES)); else if(attribute.attr("name").equals("subjectid")&& (docLucene.get("subjectid")==null || docLucene.get("subjectid").length() == 0)) docLucene.add(new StringField("subjectid", attribute.attr("content"), Store.YES)); } else{ Matcher m = ptTitle.matcher(content); String tmp; if(m.find()){ tmp = m.group(2).trim(); if(docLucene.get("title") == null || docLucene.get("title").length() == 0) docLucene.add(new TextField("title", tmp, Store.YES)); } m = ptUrl.matcher(content); if(m.find()){ tmp = m.group(2).trim(); if(docLucene.get("url") == null || docLucene.get("url").length() == 0) docLucene.add(new StringField("url", tmp, Store.YES)); } } } // 删除 <SUF> Matcher m = ptHtml.matcher(body); StringBuffer sb = new StringBuffer(); while(m.find()){ // 用StringBuffer,不用StringBuilder的原因,就在于这里要用前者. // 将m匹配到的部分用""替代,并且把""与""之间的部分加到sb里. m.appendReplacement(sb, ""); } // 将body剩下的部分加入到sb中. m.appendTail(sb); body = sb; // 标签彻底处理完毕 docLucene.add(new TextField("contents", body.toString(), Store.YES)); flag = false; try { writer.addDocument(docLucene); }catch(RuntimeException e){ System.out.println(docLucene.getField("title")); flag = true; // writer.delete } if(flag == false){ writer.flush(); writer.commit(); } } br.close(); } // 用于测试 - 在console中输出search结果,方便与tomcat结果比较. public static ArrayList<Map<String, String>> search(String q)throws IOException{ DirectoryReader reader = DirectoryReader.open(fsDirectory); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser("contents", analyzer); ArrayList<Map<String, String>> result = new ArrayList<>(); try { Query query = parser.parse(q); // 前10个 ScoreDoc[] hits = searcher.search(query, 10).scoreDocs; String contents; for (ScoreDoc hit : hits) { Document hitDoc = searcher.doc(hit.doc); Map<String, String> map = new HashMap<String, String>(); map.put("url", hitDoc.get("url")); map.put("title", hitDoc.get("title")); map.put("subjectid", hitDoc.get("subjectid")); map.put("publishid", hitDoc.get("publishid")); map.put("description", hitDoc.get("description")); map.put("keywords", hitDoc.get("keywords")); map.put("score", Float.toString(hit.score)); contents = hitDoc.get("contents"); if (contents.length() > 100) contents = contents.substring(0, 100) + "..."; map.put("contents", contents); // highlighter.setTextFragmenter(new SimpleFragmenter(contents.length())); // TokenStream tokenStream = analyzer.tokenStream("contents", new StringReader(contents)); // highLightText = highlighter.getBestFragment(tokenStream, contents); // map.put("contents", highLightText); result.add(map); } result = Search.search(q); reader.close(); fsDirectory.close(); }catch(Exception e){ e.printStackTrace(); } return result; } public static void main(String[] args)throws IOException { init(); if(fsDirectory.listAll().length == 0) { // 迭代处理每个.txt文件 for (File file : files) { System.out.print("creating index for " + file.getName()); createIndexPerFile(file); System.out.println("\n " + file.getName() + " done!"); } writer.forceMerge(1); writer.close(); } for (String file : ramDirectory.listAll()) { fsDirectory.copyFrom(ramDirectory, file, file, IOContext.DEFAULT); } search("篮球"); } }
false
2,179
8
2,534
10
2,671
8
2,534
10
3,082
15
false
false
false
false
false
true
57276_0
package practice; /** * @author liuwenchen * @create 2020-07-02 10:47 * 问题描述:题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。 * 例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 */ public class question8 { public static void main(String[] args) { int a,b,c; for(int i=100;i<1000;i++) { int n=i; a=n%10; n/=10; b=n%10; c=n/10; if(i == a*a*a+b*b*b+c*c*c) System.out.println(i); } } } /* 153 370 371 407 */
UestcXiye/Java-Program-Design
LearnJava/src/practice/question8.java
268
/** * @author liuwenchen * @create 2020-07-02 10:47 * 问题描述:题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。 * 例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 */
block_comment
zh-cn
package practice; /** * @au <SUF>*/ public class question8 { public static void main(String[] args) { int a,b,c; for(int i=100;i<1000;i++) { int n=i; a=n%10; n/=10; b=n%10; c=n/10; if(i == a*a*a+b*b*b+c*c*c) System.out.println(i); } } } /* 153 370 371 407 */
false
221
105
268
124
263
108
268
124
307
150
false
false
false
false
false
true
27133_1
package Leet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Leet139 { public static void main(String[] args) { String s = "abcd"; List<String> wordDict = new ArrayList<>(); wordDict.add("a"); wordDict.add("abc"); wordDict.add("b"); wordDict.add("cd"); boolean result = new Leet139().wordBreak2(s, wordDict); System.out.println(result); } //自己的方法超时 public boolean wordBreak(String s, List<String> wordDict) { Set<String> set = new HashSet<>(wordDict); if (s.length() == 0) { return true; } String tmp = ""; String next = ""; for (int i = 0; i < s.length(); i++) { tmp = s.substring(0, i + 1); next = s.substring(i + 1); if (set.contains(tmp)) { if (wordBreak(next, wordDict)) { return true; } } } return false; } //记住(解答的第一个) public boolean wordBreak2(String s, List<String> wordDict) { Set<String> wordDictSet = new HashSet(wordDict); boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for (int i = 1; i <= s.length(); i++) { for (int j = 0; j < i; j++) { if (dp[j] && wordDictSet.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }
Ulmarr8861/leetcodeTest
leetcodeM/src/Leet/Leet139.java
438
//记住(解答的第一个)
line_comment
zh-cn
package Leet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Leet139 { public static void main(String[] args) { String s = "abcd"; List<String> wordDict = new ArrayList<>(); wordDict.add("a"); wordDict.add("abc"); wordDict.add("b"); wordDict.add("cd"); boolean result = new Leet139().wordBreak2(s, wordDict); System.out.println(result); } //自己的方法超时 public boolean wordBreak(String s, List<String> wordDict) { Set<String> set = new HashSet<>(wordDict); if (s.length() == 0) { return true; } String tmp = ""; String next = ""; for (int i = 0; i < s.length(); i++) { tmp = s.substring(0, i + 1); next = s.substring(i + 1); if (set.contains(tmp)) { if (wordBreak(next, wordDict)) { return true; } } } return false; } //记住 <SUF> public boolean wordBreak2(String s, List<String> wordDict) { Set<String> wordDictSet = new HashSet(wordDict); boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for (int i = 1; i <= s.length(); i++) { for (int j = 0; j < i; j++) { if (dp[j] && wordDictSet.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }
false
384
6
438
9
478
7
438
9
515
15
false
false
false
false
false
true
54993_17
package my.util; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * 加解密工具类 * @author Winter Lau */ public class CryptUtils { private final static String DES = "DES"; /** * 加密 * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return 返回加密后的数据 * @throws Exception */ public static byte[] encrypt(byte[] src, byte[] key) throws RuntimeException { // DES算法要求有一个可信任的随机数源 try{ SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(src); }catch(Exception e){ throw new RuntimeException(e); } } /** * 解密 * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return 返回解密后的原始数据 * @throws Exception */ public static byte[] decrypt(byte[] src, byte[] key) throws RuntimeException { try{ // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 现在,获取数据并解密 // 正式执行解密操作 return cipher.doFinal(src); }catch(Exception e){ throw new RuntimeException(e); } } /** * 数据解密 * @param data * @param key 密钥 * @return * @throws Exception */ public final static String decrypt(String data, String key) throws Exception{ return new String(decrypt(hex2byte(data.getBytes()),key.getBytes())); } /** * 数据加密 * @param data * @param key 密钥 * @return * @throws Exception */ public final static String encrypt(String data, String key){ if(data!=null) try { return byte2hex(encrypt(data.getBytes(),key.getBytes())); }catch(Exception e) { throw new RuntimeException(e); } return null; } /** * 二行制转字符串 * @param b * @return */ private static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b!=null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); } private static byte[] hex2byte(byte[] b) { if((b.length%2)!=0) throw new IllegalArgumentException(); byte[] b2 = new byte[b.length/2]; for (int n = 0; n < b.length; n+=2) { String item = new String(b,n,2); b2[n/2] = (byte)Integer.parseInt(item,16); } return b2; } }
UlricQin/TBlog
src/my/util/CryptUtils.java
1,066
// 现在,获取数据并解密
line_comment
zh-cn
package my.util; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * 加解密工具类 * @author Winter Lau */ public class CryptUtils { private final static String DES = "DES"; /** * 加密 * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return 返回加密后的数据 * @throws Exception */ public static byte[] encrypt(byte[] src, byte[] key) throws RuntimeException { // DES算法要求有一个可信任的随机数源 try{ SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(src); }catch(Exception e){ throw new RuntimeException(e); } } /** * 解密 * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return 返回解密后的原始数据 * @throws Exception */ public static byte[] decrypt(byte[] src, byte[] key) throws RuntimeException { try{ // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 现在 <SUF> // 正式执行解密操作 return cipher.doFinal(src); }catch(Exception e){ throw new RuntimeException(e); } } /** * 数据解密 * @param data * @param key 密钥 * @return * @throws Exception */ public final static String decrypt(String data, String key) throws Exception{ return new String(decrypt(hex2byte(data.getBytes()),key.getBytes())); } /** * 数据加密 * @param data * @param key 密钥 * @return * @throws Exception */ public final static String encrypt(String data, String key){ if(data!=null) try { return byte2hex(encrypt(data.getBytes(),key.getBytes())); }catch(Exception e) { throw new RuntimeException(e); } return null; } /** * 二行制转字符串 * @param b * @return */ private static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b!=null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); } private static byte[] hex2byte(byte[] b) { if((b.length%2)!=0) throw new IllegalArgumentException(); byte[] b2 = new byte[b.length/2]; for (int n = 0; n < b.length; n+=2) { String item = new String(b,n,2); b2[n/2] = (byte)Integer.parseInt(item,16); } return b2; } }
false
997
11
1,066
9
1,090
8
1,066
9
1,448
12
false
false
false
false
false
true
34617_1
package com.wust.xyz.service; import com.wust.xyz.mapper.DepartmentMapper; import com.wust.xyz.model.Department; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; // DepartmentService.java @Service public class DepartmentService { @Autowired private DepartmentMapper departmentMapper; @Autowired //一定要加这个,臭婊子 private EmployeeService employeeService; public Department getDepartmentById(int id) { return departmentMapper.findById(id); } public List<Department> getAllDepartments() { return departmentMapper.selectAllDepartmentsWithEmployees(); } public int addDepartment(Department newDepartment) { return departmentMapper.insertDept(newDepartment); } public void deleteDepartment(int id) { employeeService.deleteByDepartmentId(id); departmentMapper.deleteDept(id); } }
Ultraman6/WUST-CS-Graduation-Internship-Individual-Assignment
src/main/java/com/wust/xyz/service/DepartmentService.java
224
//一定要加这个,臭婊子
line_comment
zh-cn
package com.wust.xyz.service; import com.wust.xyz.mapper.DepartmentMapper; import com.wust.xyz.model.Department; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; // DepartmentService.java @Service public class DepartmentService { @Autowired private DepartmentMapper departmentMapper; @Autowired //一定 <SUF> private EmployeeService employeeService; public Department getDepartmentById(int id) { return departmentMapper.findById(id); } public List<Department> getAllDepartments() { return departmentMapper.selectAllDepartmentsWithEmployees(); } public int addDepartment(Department newDepartment) { return departmentMapper.insertDept(newDepartment); } public void deleteDepartment(int id) { employeeService.deleteByDepartmentId(id); departmentMapper.deleteDept(id); } }
false
178
8
224
11
232
8
224
11
285
15
false
false
false
false
false
true
42555_1
package io.uouo.wechatbot.domain; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; import java.util.Date; /** * 微信消息接收对象 t_wechat_receive_msg * * @author ruoyi * @date 2021-03-20 */ public class WechatReceiveMsg implements Serializable { private static final long serialVersionUID = 1L; /** 微信消息编号 */ private Long wechatReceiveMsgId; /** 消息id */ private String id; /** 消息内容 */ private String content; /** 群组里消息发送人, 私人对话这个字段为空 */ private String id1; /** 群组里消息为 群组id, 个人的对话 为个人微信id */ private String id2; /** * */ private Long srvid; /** 接收消息时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date time; /** 接收消息类型 */ private Integer type; /** 发送消息得对话框id 个人是个人得微信id,群组是群组得id带 */ private String wxid; public void setWechatReceiveMsgId(Long wechatReceiveMsgId) { this.wechatReceiveMsgId = wechatReceiveMsgId; } public Long getWechatReceiveMsgId() { return wechatReceiveMsgId; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setId1(String id1) { this.id1 = id1; } public String getId1() { return id1; } public void setId2(String id2) { this.id2 = id2; } public String getId2() { return id2; } public void setSrvid(Long srvid) { this.srvid = srvid; } public Long getSrvid() { return srvid; } public void setTime(Date time) { this.time = time; } public Date getTime() { return time; } public void setType(Integer type) { this.type = type; } public Integer getType() { return type; } public void setWxid(String wxid) { this.wxid = wxid; } public String getWxid() { return wxid; } @Override public String toString() { return "WechatReceiveMsg{" + "wechatReceiveMsgId=" + wechatReceiveMsgId + ", id='" + id + '\'' + ", content='" + content + '\'' + ", id1='" + id1 + '\'' + ", id2='" + id2 + '\'' + ", srvid=" + srvid + ", time=" + time + ", type=" + type + ", wxid='" + wxid + '\'' + '}'; } }
UoUoio/WechatBot
src/main/java/io/uouo/wechatbot/domain/WechatReceiveMsg.java
732
/** 微信消息编号 */
block_comment
zh-cn
package io.uouo.wechatbot.domain; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; import java.util.Date; /** * 微信消息接收对象 t_wechat_receive_msg * * @author ruoyi * @date 2021-03-20 */ public class WechatReceiveMsg implements Serializable { private static final long serialVersionUID = 1L; /** 微信消 <SUF>*/ private Long wechatReceiveMsgId; /** 消息id */ private String id; /** 消息内容 */ private String content; /** 群组里消息发送人, 私人对话这个字段为空 */ private String id1; /** 群组里消息为 群组id, 个人的对话 为个人微信id */ private String id2; /** * */ private Long srvid; /** 接收消息时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date time; /** 接收消息类型 */ private Integer type; /** 发送消息得对话框id 个人是个人得微信id,群组是群组得id带 */ private String wxid; public void setWechatReceiveMsgId(Long wechatReceiveMsgId) { this.wechatReceiveMsgId = wechatReceiveMsgId; } public Long getWechatReceiveMsgId() { return wechatReceiveMsgId; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setId1(String id1) { this.id1 = id1; } public String getId1() { return id1; } public void setId2(String id2) { this.id2 = id2; } public String getId2() { return id2; } public void setSrvid(Long srvid) { this.srvid = srvid; } public Long getSrvid() { return srvid; } public void setTime(Date time) { this.time = time; } public Date getTime() { return time; } public void setType(Integer type) { this.type = type; } public Integer getType() { return type; } public void setWxid(String wxid) { this.wxid = wxid; } public String getWxid() { return wxid; } @Override public String toString() { return "WechatReceiveMsg{" + "wechatReceiveMsgId=" + wechatReceiveMsgId + ", id='" + id + '\'' + ", content='" + content + '\'' + ", id1='" + id1 + '\'' + ", id2='" + id2 + '\'' + ", srvid=" + srvid + ", time=" + time + ", type=" + type + ", wxid='" + wxid + '\'' + '}'; } }
false
690
7
732
6
791
5
732
6
920
9
false
false
false
false
false
true
45934_7
import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.util.ArrayList; public class Tank implements TankMethod { Map map; Image img; Image death; public ArrayList<Bullets> bullets=new ArrayList<>(); private final Image player_up; private final Image player_down; private final Image player_left; private final Image player_right; //四幅图片 public int live ; private int fire_internal=0; int x, y,w,h; public Direction Dir; public boolean bL; public boolean bR; public boolean bU; public boolean bD;//方向布尔值 public boolean bF;//射击布尔值 int dir_set=0; public Tank(int x,int y,Direction Dir,Map map) { this.x=x; this.y=y; this.Dir=Dir; this.map=map; this.live=Setting.live; this.bU=false; this.bD=false; this.bF=false; this.bL=false; this.bR=false; death=new ImageIcon("img/boom.jpg").getImage(); img = new ImageIcon("img/player1.gif").getImage(); this.player_up=new ImageIcon("img/player1.gif").getImage(); this.player_down=new ImageIcon("img/player2.gif").getImage(); this.player_left=new ImageIcon("img/player3.gif").getImage(); this.player_right=new ImageIcon("img/player4.gif").getImage(); this.w=player_up.getWidth(null); this.h=player_up.getHeight(null); }//构造方法 public void draw(Graphics g) { if(Setting.mytank_is_alive) { g.drawImage(img, x, y,40,40, null); } g.setColor(Color.RED); g.fillRect(x,y-10,(live*(40/Setting.live)),5); }//画坦克的方法 public void keyPressed(KeyEvent e) { int key =e.getKeyCode(); switch (key) { case KeyEvent.VK_LEFT, KeyEvent.VK_A -> { img = player_left; dir_set=1; this.bL = true; } case KeyEvent.VK_RIGHT, KeyEvent.VK_D -> { img = player_right; dir_set=2; this.bR = true; } case KeyEvent.VK_UP, KeyEvent.VK_W -> { img = player_up; dir_set=3; this.bU = true; } case KeyEvent.VK_DOWN, KeyEvent.VK_S -> { img = player_down; dir_set=4; this.bD = true; } case KeyEvent.VK_SPACE -> bF=true; } SetDir(); }//读取按键 public void keyReleased(KeyEvent e) { int key =e.getKeyCode(); switch (key) { case KeyEvent.VK_LEFT, KeyEvent.VK_A -> this.bL = false; case KeyEvent.VK_RIGHT, KeyEvent.VK_D -> this.bR = false; case KeyEvent.VK_UP, KeyEvent.VK_W -> this.bU = false; case KeyEvent.VK_DOWN, KeyEvent.VK_S -> this.bD = false; case KeyEvent.VK_SPACE -> this.bF = false; } SetDir(); } //键盘响应 public void fire() { if(fire_internal>0) { fire_internal--; } if(bF&&fire_internal==0) { bullets.add(new Bullets(x,y,dir_set)); fire_internal=40*Setting.difficulty; BeginFrame.bgm.attack();//依据难度射出子弹 }//连续射出子弹 for(int i=bullets.size()-1;i>=0;i--) { if(is_bullet_border(bullets.get(i).x,bullets.get(i).y)/*子弹在边界内*/ &&!bullets.get(i).bullet_map_collision(bullets.get(i),map)/*子弹未与地图碰撞*/) { bullets.get(i).bullet_move(); } else { bullets.remove(i); } }//判断子弹与地图的碰撞 } //射出子弹 public boolean is_bullet_border(int x, int y) { return x>0&&y>0&&x+8< Setting.frame_width &&y+8<Setting.frame_height; } //判断子弹是否出边界 public void SetDir() { if(!bR&&!bL&&!bU&&!bD) { Dir=Direction.S; } if(bR&&!bL&&!bU&&!bD) { Dir=Direction.R; } if(!bR&&bL&&!bU&&!bD) { Dir=Direction.L; } if(!bR&&!bL&&bU&&!bD) { Dir=Direction.U; } if(!bR&&!bL&&!bU&&bD) { Dir=Direction.D; } } //方向设置 public void move() { int speed = Setting.TANK_SPEED; switch (this.Dir) { case L -> { if (x != 0&&tank_map_collision(this,map)[0]==0) { x -= speed; } } case R -> { if (x != Setting.frame_width - 45&&tank_map_collision(this,map)[1]==0) { x += speed; } } case U -> { if (y != 25&&tank_map_collision(this,map)[2]==0) { y -= speed; } } case D -> { if (y != Setting.frame_height - 45&&tank_map_collision(this,map)[3]==0) { y += speed; } } }//运动 fire(); }//坦克移动 public int[] tank_map_collision(Tank tank, Map map) { int[] result={0,0,0,0}; for (int i = 0; i < 16; i++) { for (int i1 = 0; i1 < 16; i1++) { if(map.map[i].charAt(i1)=='1'||map.map[i].charAt(i1)=='3'||map.map[i].charAt(i1)=='4') { Rectangle rect_tank_up=new Rectangle(tank.x,tank.y-1,40,1); Rectangle rect_tank_down=new Rectangle(tank.x,tank.y+40,40,1); Rectangle rect_tank_left=new Rectangle(tank.x-1,tank.y,1,40); Rectangle rect_tank_right=new Rectangle(tank.x+40,tank.y,1,40); Rectangle rect_map=new Rectangle(10+i1* Map.interval,25+i* Map.interval, Map.interval, Map.interval); if (rect_tank_left.intersects(rect_map)) { result[0] = 1;//坦克左边与地图右边碰撞,不能向左 } if (rect_tank_right.intersects(rect_map)) { result[1] = 1;//坦克右边与地图左边碰撞,不能向右 } if (rect_tank_up.intersects(rect_map)) { result[2] = 1;//坦克上边与地图下边碰撞,不能向上 } if (rect_tank_down.intersects(rect_map)) { result[3] = 1;//坦克下边与地图上边碰撞,不能向下 } } } } return result; }//坦克与地图的碰撞 }
UselessRoman/ModernTankWar
src/Tank.java
1,971
//依据难度射出子弹
line_comment
zh-cn
import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.util.ArrayList; public class Tank implements TankMethod { Map map; Image img; Image death; public ArrayList<Bullets> bullets=new ArrayList<>(); private final Image player_up; private final Image player_down; private final Image player_left; private final Image player_right; //四幅图片 public int live ; private int fire_internal=0; int x, y,w,h; public Direction Dir; public boolean bL; public boolean bR; public boolean bU; public boolean bD;//方向布尔值 public boolean bF;//射击布尔值 int dir_set=0; public Tank(int x,int y,Direction Dir,Map map) { this.x=x; this.y=y; this.Dir=Dir; this.map=map; this.live=Setting.live; this.bU=false; this.bD=false; this.bF=false; this.bL=false; this.bR=false; death=new ImageIcon("img/boom.jpg").getImage(); img = new ImageIcon("img/player1.gif").getImage(); this.player_up=new ImageIcon("img/player1.gif").getImage(); this.player_down=new ImageIcon("img/player2.gif").getImage(); this.player_left=new ImageIcon("img/player3.gif").getImage(); this.player_right=new ImageIcon("img/player4.gif").getImage(); this.w=player_up.getWidth(null); this.h=player_up.getHeight(null); }//构造方法 public void draw(Graphics g) { if(Setting.mytank_is_alive) { g.drawImage(img, x, y,40,40, null); } g.setColor(Color.RED); g.fillRect(x,y-10,(live*(40/Setting.live)),5); }//画坦克的方法 public void keyPressed(KeyEvent e) { int key =e.getKeyCode(); switch (key) { case KeyEvent.VK_LEFT, KeyEvent.VK_A -> { img = player_left; dir_set=1; this.bL = true; } case KeyEvent.VK_RIGHT, KeyEvent.VK_D -> { img = player_right; dir_set=2; this.bR = true; } case KeyEvent.VK_UP, KeyEvent.VK_W -> { img = player_up; dir_set=3; this.bU = true; } case KeyEvent.VK_DOWN, KeyEvent.VK_S -> { img = player_down; dir_set=4; this.bD = true; } case KeyEvent.VK_SPACE -> bF=true; } SetDir(); }//读取按键 public void keyReleased(KeyEvent e) { int key =e.getKeyCode(); switch (key) { case KeyEvent.VK_LEFT, KeyEvent.VK_A -> this.bL = false; case KeyEvent.VK_RIGHT, KeyEvent.VK_D -> this.bR = false; case KeyEvent.VK_UP, KeyEvent.VK_W -> this.bU = false; case KeyEvent.VK_DOWN, KeyEvent.VK_S -> this.bD = false; case KeyEvent.VK_SPACE -> this.bF = false; } SetDir(); } //键盘响应 public void fire() { if(fire_internal>0) { fire_internal--; } if(bF&&fire_internal==0) { bullets.add(new Bullets(x,y,dir_set)); fire_internal=40*Setting.difficulty; BeginFrame.bgm.attack();//依据 <SUF> }//连续射出子弹 for(int i=bullets.size()-1;i>=0;i--) { if(is_bullet_border(bullets.get(i).x,bullets.get(i).y)/*子弹在边界内*/ &&!bullets.get(i).bullet_map_collision(bullets.get(i),map)/*子弹未与地图碰撞*/) { bullets.get(i).bullet_move(); } else { bullets.remove(i); } }//判断子弹与地图的碰撞 } //射出子弹 public boolean is_bullet_border(int x, int y) { return x>0&&y>0&&x+8< Setting.frame_width &&y+8<Setting.frame_height; } //判断子弹是否出边界 public void SetDir() { if(!bR&&!bL&&!bU&&!bD) { Dir=Direction.S; } if(bR&&!bL&&!bU&&!bD) { Dir=Direction.R; } if(!bR&&bL&&!bU&&!bD) { Dir=Direction.L; } if(!bR&&!bL&&bU&&!bD) { Dir=Direction.U; } if(!bR&&!bL&&!bU&&bD) { Dir=Direction.D; } } //方向设置 public void move() { int speed = Setting.TANK_SPEED; switch (this.Dir) { case L -> { if (x != 0&&tank_map_collision(this,map)[0]==0) { x -= speed; } } case R -> { if (x != Setting.frame_width - 45&&tank_map_collision(this,map)[1]==0) { x += speed; } } case U -> { if (y != 25&&tank_map_collision(this,map)[2]==0) { y -= speed; } } case D -> { if (y != Setting.frame_height - 45&&tank_map_collision(this,map)[3]==0) { y += speed; } } }//运动 fire(); }//坦克移动 public int[] tank_map_collision(Tank tank, Map map) { int[] result={0,0,0,0}; for (int i = 0; i < 16; i++) { for (int i1 = 0; i1 < 16; i1++) { if(map.map[i].charAt(i1)=='1'||map.map[i].charAt(i1)=='3'||map.map[i].charAt(i1)=='4') { Rectangle rect_tank_up=new Rectangle(tank.x,tank.y-1,40,1); Rectangle rect_tank_down=new Rectangle(tank.x,tank.y+40,40,1); Rectangle rect_tank_left=new Rectangle(tank.x-1,tank.y,1,40); Rectangle rect_tank_right=new Rectangle(tank.x+40,tank.y,1,40); Rectangle rect_map=new Rectangle(10+i1* Map.interval,25+i* Map.interval, Map.interval, Map.interval); if (rect_tank_left.intersects(rect_map)) { result[0] = 1;//坦克左边与地图右边碰撞,不能向左 } if (rect_tank_right.intersects(rect_map)) { result[1] = 1;//坦克右边与地图左边碰撞,不能向右 } if (rect_tank_up.intersects(rect_map)) { result[2] = 1;//坦克上边与地图下边碰撞,不能向上 } if (rect_tank_down.intersects(rect_map)) { result[3] = 1;//坦克下边与地图上边碰撞,不能向下 } } } } return result; }//坦克与地图的碰撞 }
false
1,625
6
1,971
9
2,080
6
1,971
9
2,430
17
false
false
false
false
false
true
43360_4
package demo04; /* 有 1000 只水桶,其中有且只有一桶装的含有毒药,其余装的都是水。它们从外观看起来都一样。如果小猪喝了毒药,它会在 15 分钟内死去。 问题来了,如果需要你在一小时内,弄清楚哪只水桶含有毒药,你最少需要多少只猪? 回答这个问题,并为下列的进阶问题编写一个通用算法。 进阶: 假设有 n 只水桶,猪饮水中毒后会在 m 分钟内死亡,你需要多少猪(x)就能在 p 分钟内找出 “有毒” 水桶?这 n 只水桶里有且仅有一只有毒的桶。 提示: 可以允许小猪同时饮用任意数量的桶中的水,并且该过程不需要时间。 小猪喝完水后,必须有 m 分钟的冷却时间。在这段时间里,只允许观察,而不允许继续饮水。 任何给定的桶都可以无限次采样(无限数量的猪)。 * * */ public class PoorPigs { public static void main(String[] args) { System.out.println(poorPigs01(1, 1, 1)); } /* *得到的启示与分析:养成思维导向! *1.由于测试时间给定为minuteToTest,死亡时间为minuteTODie,那么猪就会有minuteToTest/minuteTODie+1种状态 * 分析如下: * 如果minuteToTest为60,minuteTODie为30 * 那么对应一只猪来说,他可能会出现: * 1.30分钟时死亡 * 2.60分钟时死亡 * 3.存活下来 * 那么每一只猪在时间限制内最多可以测试自己维度内的3个桶 * 当有N只M维度的猪,就会在时限内测试出M的N次方个桶,那么只需要被测桶的数量小于可测数量就行了 * */ public static int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int Num = minutesToTest/minutesToDie + 1;//小猪状态数 int PigNum = 0;//小猪数 int Bucket = 1;//可测的最大桶数 while(Bucket<buckets) { Bucket *= Num; PigNum++; } return PigNum; } //标准答案版 public static int poorPigs01(int buckets, int minutesToDie, int minutesToTest) { int states = minutesToTest / minutesToDie + 1; return (int) Math.ceil(Math.log(buckets) / Math.log(states)); } }
User-FrenchFries/java-learning
LeetCodeTest01/src/demo04/PoorPigs.java
754
//可测的最大桶数
line_comment
zh-cn
package demo04; /* 有 1000 只水桶,其中有且只有一桶装的含有毒药,其余装的都是水。它们从外观看起来都一样。如果小猪喝了毒药,它会在 15 分钟内死去。 问题来了,如果需要你在一小时内,弄清楚哪只水桶含有毒药,你最少需要多少只猪? 回答这个问题,并为下列的进阶问题编写一个通用算法。 进阶: 假设有 n 只水桶,猪饮水中毒后会在 m 分钟内死亡,你需要多少猪(x)就能在 p 分钟内找出 “有毒” 水桶?这 n 只水桶里有且仅有一只有毒的桶。 提示: 可以允许小猪同时饮用任意数量的桶中的水,并且该过程不需要时间。 小猪喝完水后,必须有 m 分钟的冷却时间。在这段时间里,只允许观察,而不允许继续饮水。 任何给定的桶都可以无限次采样(无限数量的猪)。 * * */ public class PoorPigs { public static void main(String[] args) { System.out.println(poorPigs01(1, 1, 1)); } /* *得到的启示与分析:养成思维导向! *1.由于测试时间给定为minuteToTest,死亡时间为minuteTODie,那么猪就会有minuteToTest/minuteTODie+1种状态 * 分析如下: * 如果minuteToTest为60,minuteTODie为30 * 那么对应一只猪来说,他可能会出现: * 1.30分钟时死亡 * 2.60分钟时死亡 * 3.存活下来 * 那么每一只猪在时间限制内最多可以测试自己维度内的3个桶 * 当有N只M维度的猪,就会在时限内测试出M的N次方个桶,那么只需要被测桶的数量小于可测数量就行了 * */ public static int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int Num = minutesToTest/minutesToDie + 1;//小猪状态数 int PigNum = 0;//小猪数 int Bucket = 1;//可测 <SUF> while(Bucket<buckets) { Bucket *= Num; PigNum++; } return PigNum; } //标准答案版 public static int poorPigs01(int buckets, int minutesToDie, int minutesToTest) { int states = minutesToTest / minutesToDie + 1; return (int) Math.ceil(Math.log(buckets) / Math.log(states)); } }
false
622
6
754
8
659
6
754
8
1,034
10
false
false
false
false
false
true
19057_4
package cn.neptu.neplog.model.entity; import cn.neptu.neplog.repository.ArticleRepository; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.hibernate.annotations.ColumnDefault; import javax.persistence.*; import java.util.Set; @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(of = "id", callSuper = false) @MappedSuperclass public class BaseArticle extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "article_id") private Long id; @Column(name = "title",length = 255,nullable = false) private String title; @Column(name = "summary",length = 255) @ColumnDefault("''") private String summary; @Column(name = "content",nullable = false) @Lob private String content; @Column(name = "html_content",nullable = false) @Lob private String htmlContent; @Column(name = "cover",length = 1023) @ColumnDefault("''") private String cover; @Column(name = "priority") @ColumnDefault("0") private Integer priority; /** * 0 草稿 * 4 公开 */ @Column(name = "status") @ColumnDefault("0") private Integer status; /** * 只能通过{@link ArticleRepository#updateViews}修改 */ @Column(name = "views", updatable = false) @ColumnDefault("1") private Long views; /** * 只能通过{@link ArticleRepository#updateLikes}修改 */ @Column(name = "likes", updatable = false) @ColumnDefault("0") private Long likes; /** * 只能通过{@link ArticleRepository#updateComments}修改 */ @Column(name = "comments", updatable = false) @ColumnDefault("0") private Long comments; /** * 0 任何人 * 16 关闭(仅限博主) */ @Column(name = "comment_permission") @ColumnDefault("0") private Integer commentPermission; /** * 0 任何人 * 16 私有 */ @Column(name = "view_permission") @ColumnDefault("0") private Integer viewPermission; @Column(name = "deleted") @ColumnDefault("false") private Boolean deleted; @Override public void prePersist(){ if(title == null || "".equals(title)){ title = "Untitled"; } if(content == null){ content = "### Edit now"; } if(htmlContent == null){ htmlContent = "<h3>Edit now</h3>"; } if(summary == null){ summary = "Edit now"; } if(cover == null){ cover = ""; } if(priority == null){ priority = 0; } if(status == null){ status = 0; } if(views == null){ views = 1L; } if(likes == null){ likes = 0L; } if(comments == null){ comments = 0L; } if(viewPermission == null){ viewPermission = 0; } if(commentPermission == null){ commentPermission = 0; } deleted = false; } }
Uzemiu/neplog
src/main/java/cn/neptu/neplog/model/entity/BaseArticle.java
813
/** * 0 任何人 * 16 关闭(仅限博主) */
block_comment
zh-cn
package cn.neptu.neplog.model.entity; import cn.neptu.neplog.repository.ArticleRepository; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.hibernate.annotations.ColumnDefault; import javax.persistence.*; import java.util.Set; @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(of = "id", callSuper = false) @MappedSuperclass public class BaseArticle extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "article_id") private Long id; @Column(name = "title",length = 255,nullable = false) private String title; @Column(name = "summary",length = 255) @ColumnDefault("''") private String summary; @Column(name = "content",nullable = false) @Lob private String content; @Column(name = "html_content",nullable = false) @Lob private String htmlContent; @Column(name = "cover",length = 1023) @ColumnDefault("''") private String cover; @Column(name = "priority") @ColumnDefault("0") private Integer priority; /** * 0 草稿 * 4 公开 */ @Column(name = "status") @ColumnDefault("0") private Integer status; /** * 只能通过{@link ArticleRepository#updateViews}修改 */ @Column(name = "views", updatable = false) @ColumnDefault("1") private Long views; /** * 只能通过{@link ArticleRepository#updateLikes}修改 */ @Column(name = "likes", updatable = false) @ColumnDefault("0") private Long likes; /** * 只能通过{@link ArticleRepository#updateComments}修改 */ @Column(name = "comments", updatable = false) @ColumnDefault("0") private Long comments; /** * 0 任 <SUF>*/ @Column(name = "comment_permission") @ColumnDefault("0") private Integer commentPermission; /** * 0 任何人 * 16 私有 */ @Column(name = "view_permission") @ColumnDefault("0") private Integer viewPermission; @Column(name = "deleted") @ColumnDefault("false") private Boolean deleted; @Override public void prePersist(){ if(title == null || "".equals(title)){ title = "Untitled"; } if(content == null){ content = "### Edit now"; } if(htmlContent == null){ htmlContent = "<h3>Edit now</h3>"; } if(summary == null){ summary = "Edit now"; } if(cover == null){ cover = ""; } if(priority == null){ priority = 0; } if(status == null){ status = 0; } if(views == null){ views = 1L; } if(likes == null){ likes = 0L; } if(comments == null){ comments = 0L; } if(viewPermission == null){ viewPermission = 0; } if(commentPermission == null){ commentPermission = 0; } deleted = false; } }
false
751
22
813
23
892
24
813
23
996
32
false
false
false
false
false
true
52823_9
package com.huawei.classroom.student.h61; public class Person { private Param param; private int id; // 编号 private State state; // 状态 private int latentDays; // 潜伏期 private Family family; // 所属家庭 private Company company; // 所属公司 private boolean isImmune; // 是否获得免疫 private boolean isVaccine; //是否注射疫苗 public Person(int id, Param param) { this.id = id; this.state = State.healthy; this.latentDays = 0; this.isVaccine = false; this.param = param; } public void setFamily(Family family) { this.family = family; } public void setCompany(Company company) { this.company = company; } public State getState() { return this.state; } public void setState(State state) { this.state = state; } public void setVaccine(boolean value) { this.isVaccine = value; } public boolean hasVirus() { return this.state == State.latent || this.state == State.patientAtHome || this.state == State.patientAtHospital; } public boolean isDead() { return this.state == State.dead; } public boolean isCured() { return this.state == State.cured; } /** * 试一下能不能被感染 * */ public void tryInfected(double infectRate) { if(this.isImmune || this.hasVirus()) { return; } if(this.isVaccine) { if(Util.getProbability() < infectRate * (1 - param.getImmuEffect())) { this.setState(State.latent); } } else { if(Util.getProbability() < infectRate) { this.setState(State.latent); } } } /** * 试一下能不能痊愈 * */ public void tryHeal(double healingRate) { if(this.isDead()) { // 都死了还痊愈个锤子 return; } if(Util.getProbability() < healingRate) { this.setState(State.cured); this.isImmune = true; } } /** * 试着去死 * */ public void tryDeath(double deathRate) { if(Util.getProbability() < deathRate) { this.setState(State.dead); } } public void oneDayPass(Hospital hospital) { if(this.state == State.healthy) { if(!this.isImmune) { if(this.company.hasVirusToday()) { // 白天在公司 this.tryInfected(param.getSpreadRateCompany()); } if(this.family.hasVirusToday()) { // 晚上在家 this.tryInfected(param.getSpreadRateFamily()); } } } else if (this.state == State.latent) { this.latentDays++; if(this.latentDays > param.getLatentPeriod()) { hospital.addPatient(this); } } else if (this.state == State.patientAtHome) { this.tryDeath(param.getDeathRateHome()); this.tryHeal(param.getHealingRateHome()); } else if (this.state == State.patientAtHospital) { this.tryDeath(param.getDeathRateHospital()); this.tryHeal(param.getHealingRateHospital()); if(this.isCured() || this.isDead()) { // 死了或者治好了都要从医院里滚蛋 hospital.removePatient(this); } } } }
VMnK-Run/OOP_Junior_Practice
src/com/huawei/classroom/student/h61/Person.java
896
// 白天在公司
line_comment
zh-cn
package com.huawei.classroom.student.h61; public class Person { private Param param; private int id; // 编号 private State state; // 状态 private int latentDays; // 潜伏期 private Family family; // 所属家庭 private Company company; // 所属公司 private boolean isImmune; // 是否获得免疫 private boolean isVaccine; //是否注射疫苗 public Person(int id, Param param) { this.id = id; this.state = State.healthy; this.latentDays = 0; this.isVaccine = false; this.param = param; } public void setFamily(Family family) { this.family = family; } public void setCompany(Company company) { this.company = company; } public State getState() { return this.state; } public void setState(State state) { this.state = state; } public void setVaccine(boolean value) { this.isVaccine = value; } public boolean hasVirus() { return this.state == State.latent || this.state == State.patientAtHome || this.state == State.patientAtHospital; } public boolean isDead() { return this.state == State.dead; } public boolean isCured() { return this.state == State.cured; } /** * 试一下能不能被感染 * */ public void tryInfected(double infectRate) { if(this.isImmune || this.hasVirus()) { return; } if(this.isVaccine) { if(Util.getProbability() < infectRate * (1 - param.getImmuEffect())) { this.setState(State.latent); } } else { if(Util.getProbability() < infectRate) { this.setState(State.latent); } } } /** * 试一下能不能痊愈 * */ public void tryHeal(double healingRate) { if(this.isDead()) { // 都死了还痊愈个锤子 return; } if(Util.getProbability() < healingRate) { this.setState(State.cured); this.isImmune = true; } } /** * 试着去死 * */ public void tryDeath(double deathRate) { if(Util.getProbability() < deathRate) { this.setState(State.dead); } } public void oneDayPass(Hospital hospital) { if(this.state == State.healthy) { if(!this.isImmune) { if(this.company.hasVirusToday()) { // 白天 <SUF> this.tryInfected(param.getSpreadRateCompany()); } if(this.family.hasVirusToday()) { // 晚上在家 this.tryInfected(param.getSpreadRateFamily()); } } } else if (this.state == State.latent) { this.latentDays++; if(this.latentDays > param.getLatentPeriod()) { hospital.addPatient(this); } } else if (this.state == State.patientAtHome) { this.tryDeath(param.getDeathRateHome()); this.tryHeal(param.getHealingRateHome()); } else if (this.state == State.patientAtHospital) { this.tryDeath(param.getDeathRateHospital()); this.tryHeal(param.getHealingRateHospital()); if(this.isCured() || this.isDead()) { // 死了或者治好了都要从医院里滚蛋 hospital.removePatient(this); } } } }
false
777
6
896
6
928
5
896
6
1,112
7
false
false
false
false
false
true
34874_2
package util; /** * Twitter_Snowflake<br> * SnowFlake的结构如下(每部分用-分开):<br> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br> * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> * 10位的数据机器位,可以部署在1024个节点,包括5位dataCenterId和5位workerId<br> * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> * 加起来刚好64位,为一个Long型。<br> * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。 */ @SuppressWarnings({"FieldCanBeLocal", "WeakerAccess"}) public class Snowflake { /** 开始时间截 (2015-01-01) */ private final long start = 1420041600000L; /** 机器id所占的位数 */ private final long workerIdBits = 5L; /** 数据标识id所占的位数 */ private final long dataCenterIdBits = 5L; /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */ private final long maxWorkerId = ~(-1L << workerIdBits); /** 支持的最大数据标识id,结果是31 */ private final long maxDataCenterId = ~(-1L << dataCenterIdBits); /** 序列在id中占的位数 */ private final long sequenceBits = 12L; /** 机器ID向左移12位 */ private final long workerIdShift = sequenceBits; /** 数据标识id向左移17位(12+5) */ private final long dataCenterIdShift = sequenceBits + workerIdBits; /** 时间截向左移22位(5+5+12) */ private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits; /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */ private final long sequenceMask = ~(-1L << sequenceBits); /** 工作机器ID(0~31) */ private long workerId; /** 数据中心ID(0~31) */ private long dataCenterId; /** 毫秒内序列(0~4095) */ private long sequence = 0L; /** 上次生成ID的时间截 */ private long lastTimestamp = -1L; /** * 构造函数 * @param workerId 工作ID (0~31) * @param dataCenterId 数据中心ID (0~31) */ public Snowflake(long workerId, long dataCenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (dataCenterId > maxDataCenterId || dataCenterId < 0) { throw new IllegalArgumentException(String.format("dataCenter Id can't be greater than %d or less than 0", maxDataCenterId)); } this.workerId = workerId; this.dataCenterId = dataCenterId; } public Snowflake() { this(0L, 0L); } /** * 获得下一个ID (该方法是线程安全的) * @return SnowflakeId */ public synchronized long nextId() { long timestamp = timeGen(); //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒内序列溢出 if (sequence == 0) { //阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } } //时间戳改变,毫秒内序列重置 else { sequence = 0L; } //上次生成ID的时间截 lastTimestamp = timestamp; //移位并通过或运算拼到一起组成64位的ID return ((timestamp - start) << timestampLeftShift) // | (dataCenterId << dataCenterIdShift) // | (workerId << workerIdShift) // | sequence; } /** * 阻塞到下一个毫秒,直到获得新的时间戳 * @param lastTimestamp 上次生成ID的时间截 * @return 当前时间戳 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 返回以毫秒为单位的当前时间 * @return 当前时间(毫秒) */ private long timeGen() { return System.currentTimeMillis(); } //==============================Test============================================= /** 测试 */ public static void main(String[] args) { Snowflake idWorker = new Snowflake(); for (int i = 0; i < 10; i++) { long id = idWorker.nextId(); System.out.println(Long.toBinaryString(id)); System.out.println(id); } } }
ValueYouth/reciprocity
code/util/Snowflake.java
1,650
/** 机器id所占的位数 */
block_comment
zh-cn
package util; /** * Twitter_Snowflake<br> * SnowFlake的结构如下(每部分用-分开):<br> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br> * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> * 10位的数据机器位,可以部署在1024个节点,包括5位dataCenterId和5位workerId<br> * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> * 加起来刚好64位,为一个Long型。<br> * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。 */ @SuppressWarnings({"FieldCanBeLocal", "WeakerAccess"}) public class Snowflake { /** 开始时间截 (2015-01-01) */ private final long start = 1420041600000L; /** 机器i <SUF>*/ private final long workerIdBits = 5L; /** 数据标识id所占的位数 */ private final long dataCenterIdBits = 5L; /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */ private final long maxWorkerId = ~(-1L << workerIdBits); /** 支持的最大数据标识id,结果是31 */ private final long maxDataCenterId = ~(-1L << dataCenterIdBits); /** 序列在id中占的位数 */ private final long sequenceBits = 12L; /** 机器ID向左移12位 */ private final long workerIdShift = sequenceBits; /** 数据标识id向左移17位(12+5) */ private final long dataCenterIdShift = sequenceBits + workerIdBits; /** 时间截向左移22位(5+5+12) */ private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits; /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */ private final long sequenceMask = ~(-1L << sequenceBits); /** 工作机器ID(0~31) */ private long workerId; /** 数据中心ID(0~31) */ private long dataCenterId; /** 毫秒内序列(0~4095) */ private long sequence = 0L; /** 上次生成ID的时间截 */ private long lastTimestamp = -1L; /** * 构造函数 * @param workerId 工作ID (0~31) * @param dataCenterId 数据中心ID (0~31) */ public Snowflake(long workerId, long dataCenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (dataCenterId > maxDataCenterId || dataCenterId < 0) { throw new IllegalArgumentException(String.format("dataCenter Id can't be greater than %d or less than 0", maxDataCenterId)); } this.workerId = workerId; this.dataCenterId = dataCenterId; } public Snowflake() { this(0L, 0L); } /** * 获得下一个ID (该方法是线程安全的) * @return SnowflakeId */ public synchronized long nextId() { long timestamp = timeGen(); //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒内序列溢出 if (sequence == 0) { //阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } } //时间戳改变,毫秒内序列重置 else { sequence = 0L; } //上次生成ID的时间截 lastTimestamp = timestamp; //移位并通过或运算拼到一起组成64位的ID return ((timestamp - start) << timestampLeftShift) // | (dataCenterId << dataCenterIdShift) // | (workerId << workerIdShift) // | sequence; } /** * 阻塞到下一个毫秒,直到获得新的时间戳 * @param lastTimestamp 上次生成ID的时间截 * @return 当前时间戳 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 返回以毫秒为单位的当前时间 * @return 当前时间(毫秒) */ private long timeGen() { return System.currentTimeMillis(); } //==============================Test============================================= /** 测试 */ public static void main(String[] args) { Snowflake idWorker = new Snowflake(); for (int i = 0; i < 10; i++) { long id = idWorker.nextId(); System.out.println(Long.toBinaryString(id)); System.out.println(id); } } }
false
1,575
10
1,650
10
1,680
9
1,650
10
2,200
13
false
false
false
false
false
true
20731_15
package com.lqb.ikanalyzer.demo; import com.lqb.ikanalyzer.service.*; import com.lqb.ikanalyzer.Utils.FunctionUtil; import com.lqb.ikanalyzer.Utils.IKAnalyzerUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Scanner; import java.util.Vector; /** * @author: lqb * @Date: 2015-5-20 * @version 1.0 */ public class CheckTheSame { /* 个性化检索: (最好检索一下它的相关问答库,对满意情况排序,个性化推荐;或者对动态进行排序,根据专家讲座的频度排序 ----》在这里新建数据库,加入专家满意度评价情况字段和专家讲座次数,然后自己适当加权定参数排序就可以了) //我想知道/查询/了解xxx专家的信息 模式:查询/了解/知道信息,提取xxx,返回简介/擅长领域/地点/出诊时间/相关时间/博客/地点 //和xxx专家相关的文章 模式:文章,查询文章字段,返回文章名,文章摘要 //我想查找/查看中医xxx领域的相关文章 模式:文章 提取xxx,查询文章字段,返回作者、文章名和摘要(根据时间和引用次数排序) //xxx专家近期动态 模式:动态,提取xxx,查询返回动态字段 //擅长xxx领域的专家 模式:领域,提取xxx与擅长领域字段比较相似度,返回专家列表和所在医院 //XX专家擅长的领域 模式:领域,提取xxx与,返回专家擅长的领域 //能够治疗/诊断xxx的专家 模式:治疗/诊断,提取xxx,同上 //(福州xx)有哪些(糖尿病xxx)医院 模式:医院,提取地点和领域,返回该医院列表 // xxx医院详情 模式:医院,提取地xxx,获取医院详情 //如何预防糖尿病xxx/糖尿病xxx相关知识 模式:预防知识,提取xxx,查询问答数据结构,将xxx与问题进行相似度匹配排序,对相应问答进行生成摘要然后串接 //xxx专家的关联图谱/治疗xxx的相关图谱 模式:关联图谱 查看是否存在“专家”字眼,若有提取xxx,查询xxx专家图谱,若无,根据疾病xxx,筛选出专家在计算图谱 //xxx领域的知识图谱 模式:知识图谱 提取xxx */ //可以将此main函数改生servlet直接运用到系统中 //接受参数为用户搜索内容,String str //返回参数为用户搜索结果,String result public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in , "utf-8"); String str = null; String result = null; System.out.println("请输入您想查询的内容:"); while(true) { str = scan.next(); byte[] b = str.getBytes("gbk"); str = new String(b , "utf-8"); //去掉“的”,因分词能力有限 str = str.replaceAll("[的]","" ); //分词 Vector<String> strs1 = IKAnalyzerUtil.participle(str) ; int type = getFunctionType(strs1); switch (type) { case FunctionUtil.Information: //专家或者疾病信息 result = new Information().getPersonInfo(strs1); break; case FunctionUtil.Article: //相关文章 result = new Article().getArticleDetail(strs1); break; case FunctionUtil.Statu: //最新动态 result = new Statu().getStatus(strs1); break; case FunctionUtil.Field: //擅长领域 result = new Field().getFieldDetail(strs1); break; case FunctionUtil.Consult: //治疗咨询 result = new Consult().getConsults(strs1); break; case FunctionUtil.Hospital: //医院诊所 result = new Hospital().getHospitalInfo(strs1); break; case FunctionUtil.Prevent: //预防知识 result = new Prevent().getPreventKnowleage(strs1); break; case FunctionUtil.D_Graph: //专家图谱 result = new D_Graph().getDoctorGraph(strs1); break; case FunctionUtil.K_Graph: //知识图谱 result = new K_Graph().getKnowleageGraph(strs1); break; default: //匹配不成功,以日常对话形式返回答语 break; } } } //计算相似类型 public static int getFunctionType(Vector<String> strs1) { double max = 0; int type = -1; for(int i = 0;i<FunctionUtil.Function.length ;i++){ for(int j = 0;j<FunctionUtil.Function[i].length;j++) { Vector<String> strs2 = IKAnalyzerUtil.participle(FunctionUtil.Function[i][j]); double same = 0; try { same = IKAnalyzerUtil.getSimilarity(strs1, strs2); } catch (Exception e) { //System.out.println(e.getMessage()); same = 0; } //System.out.println("类型" + String.valueOf(i) + "_" +String.valueOf(j)+"的相似度:" + same); if (max < same) { max = same; type = i; } } } if( max < 0.5){ return -1; } else{ System.out.println( "\n最大关联类型为"+FunctionUtil.Function[type][0]+"\n最大关联度为"+String.valueOf(max)+"\n"); return type; } } }
Vence/IKAnalyzer_Demo
src/com/lqb/ikanalyzer/demo/CheckTheSame.java
1,603
//知识图谱
line_comment
zh-cn
package com.lqb.ikanalyzer.demo; import com.lqb.ikanalyzer.service.*; import com.lqb.ikanalyzer.Utils.FunctionUtil; import com.lqb.ikanalyzer.Utils.IKAnalyzerUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Scanner; import java.util.Vector; /** * @author: lqb * @Date: 2015-5-20 * @version 1.0 */ public class CheckTheSame { /* 个性化检索: (最好检索一下它的相关问答库,对满意情况排序,个性化推荐;或者对动态进行排序,根据专家讲座的频度排序 ----》在这里新建数据库,加入专家满意度评价情况字段和专家讲座次数,然后自己适当加权定参数排序就可以了) //我想知道/查询/了解xxx专家的信息 模式:查询/了解/知道信息,提取xxx,返回简介/擅长领域/地点/出诊时间/相关时间/博客/地点 //和xxx专家相关的文章 模式:文章,查询文章字段,返回文章名,文章摘要 //我想查找/查看中医xxx领域的相关文章 模式:文章 提取xxx,查询文章字段,返回作者、文章名和摘要(根据时间和引用次数排序) //xxx专家近期动态 模式:动态,提取xxx,查询返回动态字段 //擅长xxx领域的专家 模式:领域,提取xxx与擅长领域字段比较相似度,返回专家列表和所在医院 //XX专家擅长的领域 模式:领域,提取xxx与,返回专家擅长的领域 //能够治疗/诊断xxx的专家 模式:治疗/诊断,提取xxx,同上 //(福州xx)有哪些(糖尿病xxx)医院 模式:医院,提取地点和领域,返回该医院列表 // xxx医院详情 模式:医院,提取地xxx,获取医院详情 //如何预防糖尿病xxx/糖尿病xxx相关知识 模式:预防知识,提取xxx,查询问答数据结构,将xxx与问题进行相似度匹配排序,对相应问答进行生成摘要然后串接 //xxx专家的关联图谱/治疗xxx的相关图谱 模式:关联图谱 查看是否存在“专家”字眼,若有提取xxx,查询xxx专家图谱,若无,根据疾病xxx,筛选出专家在计算图谱 //xxx领域的知识图谱 模式:知识图谱 提取xxx */ //可以将此main函数改生servlet直接运用到系统中 //接受参数为用户搜索内容,String str //返回参数为用户搜索结果,String result public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in , "utf-8"); String str = null; String result = null; System.out.println("请输入您想查询的内容:"); while(true) { str = scan.next(); byte[] b = str.getBytes("gbk"); str = new String(b , "utf-8"); //去掉“的”,因分词能力有限 str = str.replaceAll("[的]","" ); //分词 Vector<String> strs1 = IKAnalyzerUtil.participle(str) ; int type = getFunctionType(strs1); switch (type) { case FunctionUtil.Information: //专家或者疾病信息 result = new Information().getPersonInfo(strs1); break; case FunctionUtil.Article: //相关文章 result = new Article().getArticleDetail(strs1); break; case FunctionUtil.Statu: //最新动态 result = new Statu().getStatus(strs1); break; case FunctionUtil.Field: //擅长领域 result = new Field().getFieldDetail(strs1); break; case FunctionUtil.Consult: //治疗咨询 result = new Consult().getConsults(strs1); break; case FunctionUtil.Hospital: //医院诊所 result = new Hospital().getHospitalInfo(strs1); break; case FunctionUtil.Prevent: //预防知识 result = new Prevent().getPreventKnowleage(strs1); break; case FunctionUtil.D_Graph: //专家图谱 result = new D_Graph().getDoctorGraph(strs1); break; case FunctionUtil.K_Graph: //知识 <SUF> result = new K_Graph().getKnowleageGraph(strs1); break; default: //匹配不成功,以日常对话形式返回答语 break; } } } //计算相似类型 public static int getFunctionType(Vector<String> strs1) { double max = 0; int type = -1; for(int i = 0;i<FunctionUtil.Function.length ;i++){ for(int j = 0;j<FunctionUtil.Function[i].length;j++) { Vector<String> strs2 = IKAnalyzerUtil.participle(FunctionUtil.Function[i][j]); double same = 0; try { same = IKAnalyzerUtil.getSimilarity(strs1, strs2); } catch (Exception e) { //System.out.println(e.getMessage()); same = 0; } //System.out.println("类型" + String.valueOf(i) + "_" +String.valueOf(j)+"的相似度:" + same); if (max < same) { max = same; type = i; } } } if( max < 0.5){ return -1; } else{ System.out.println( "\n最大关联类型为"+FunctionUtil.Function[type][0]+"\n最大关联度为"+String.valueOf(max)+"\n"); return type; } } }
false
1,290
5
1,583
6
1,411
5
1,583
6
2,300
10
false
false
false
false
false
true
64285_13
package net.blacklab.lmr.util; import net.blacklab.lmr.LittleMaidReengaged; import net.blacklab.lmr.entity.littlemaid.EntityLittleMaid; import net.blacklab.lmr.util.helper.OwnableEntityHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IEntityOwnable; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityOcelot; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.FMLInjectionData; import java.io.*; import java.util.*; /** * IFFを管理するためのクラス、ほぼマルチ用。 * username : null=ローカルプレイ時、Defaultを使う */ public class IFF { public static final byte iff_Enemy = 0; public static final byte iff_Unknown = 1; public static final byte iff_Friendry = 2; /** * ローカル用、若しくはマルチのデフォルト設定 */ private static Map<String, Byte> DefaultIFF = new TreeMap<>(); /** * ユーザ毎のIFF */ private static Map<UUID, Map<String, Byte>> UserIFF = new HashMap<>(); /** * IFFのゲット */ public static Map<String, Byte> getUserIFF(UUID pUsername) { if (pUsername == null) { return DefaultIFF; } // if (CommonHelper.isLocalPlay()) { // pUsername = EntityPlayer.getOfflineUUID("Player"); // } if (!UserIFF.containsKey(pUsername)) { // IFFがないので作成 Map<String, Byte> lmap = new HashMap<>(); lmap.putAll(DefaultIFF); UserIFF.put(pUsername, lmap); } // 既にある return UserIFF.get(pUsername); } public static void setIFFValue(UUID pUsername, String pName, byte pValue) { Map<String, Byte> lmap = getUserIFF(pUsername); lmap.put(pName, pValue); } public static byte checkEntityStatic(String pName, Entity pEntity, int pIndex, Map<String, Entity> pMap) { byte liff = IFF.iff_Unknown; if (pEntity instanceof EntityLivingBase) { if (pEntity instanceof EntityArmorStand) { liff = iff_Friendry; } if (pEntity instanceof EntityLittleMaid) { switch (pIndex) { case 0: // 野生種 liff = IFF.iff_Unknown; break; case 1: // 自分の契約者 pName = (new StringBuilder()).append(pName).append(":Contract").toString(); ((EntityLittleMaid) pEntity).setContract(true); liff = IFF.iff_Friendry; break; case 2: // 他人の契約者 pName = (new StringBuilder()).append(pName).append(":Others").toString(); ((EntityLittleMaid) pEntity).setContract(true); liff = IFF.iff_Friendry; break; } } else if (pEntity instanceof IEntityOwnable) { switch (pIndex) { case 0: // 野生種 break; case 1: // 自分の家畜 pName = (new StringBuilder()).append(pName).append(":Tame").toString(); if (pEntity instanceof EntityTameable) { ((EntityTameable) pEntity).setTamed(true); } liff = IFF.iff_Friendry; break; case 2: // 他人の家畜 pName = (new StringBuilder()).append(pName).append(":Others").toString(); if (pEntity instanceof EntityTameable) { ((EntityTameable) pEntity).setTamed(true); } liff = IFF.iff_Unknown; break; } if (pIndex != 0) { if (pEntity instanceof EntityOcelot) { ((EntityOcelot) pEntity).setTameSkin(1 + (new Random()).nextInt(3)); } } } if (pMap != null) { // 表示用Entityの追加 pMap.put(pName, pEntity); LittleMaidReengaged.Debug(pName + " added."); } // IFFの初期値 if (!DefaultIFF.containsKey(pName)) { if (pEntity instanceof IMob) { liff = IFF.iff_Enemy; } DefaultIFF.put(pName, liff); } } return liff; } /** * 敵味方識別判定 */ public static byte getIFF(UUID pUsername, String entityname, World world) { if (entityname == null) { return iff_Friendry; } byte lt = iff_Enemy; Map<String, Byte> lmap = getUserIFF(pUsername); if (lmap.containsKey(entityname)) { lt = lmap.get(entityname); } else if (lmap != DefaultIFF && DefaultIFF.containsKey(entityname)) { // 未登録だけどDefaultには設定がある時は値をコピー lt = DefaultIFF.get(entityname); lmap.put(entityname, lt); } else { // 未登録Entityの場合は登録動作 int li = entityname.indexOf(":"); String ls; if (li > -1) { ls = entityname.substring(0, li); } else { ls = entityname; } Entity lentity = EntityList.createEntityByName(ls, world); li = 0; if (entityname.indexOf(":Contract") > -1) { li = 1; } else if (entityname.indexOf(":Tame") > -1) { li = 1; } else if (entityname.indexOf(":Others") > -1) { li = 2; } lt = checkEntityStatic(ls, lentity, li, null); lmap.put(entityname, lt); } return lt; } /** * 敵味方識別判定 */ public static int getIFF(UUID pUsername, Entity entity) { if (entity == null || !(entity instanceof EntityLivingBase)) { return iff_Friendry; } String lename = EntityList.getEntityString(entity); String lcname = lename; if (lename == null) { // 名称未定義MOB、プレーヤーとか? return iff_Friendry; // return mod_LMM_littleMaidMob.Aggressive ? iff_Unknown : // iff_Friendry; } int li = 0; if (entity instanceof EntityLittleMaid) { if (((EntityLittleMaid) entity).isContract()) { if (((EntityLittleMaid) entity).getMaidMasterUUID().equals(pUsername)) { // 自分の lcname = (new StringBuilder()).append(lename).append(":Contract").toString(); li = 1; } else { // 他人の lcname = (new StringBuilder()).append(lename).append(":Others").toString(); li = 2; } } } else if (entity instanceof IEntityOwnable) { UUID loname = OwnableEntityHelper.getOwner((IEntityOwnable)entity); if (loname.equals(pUsername)) { // 自分の lcname = (new StringBuilder()).append(lename).append(":Tame").toString(); li = 1; } else { // 他人の lcname = (new StringBuilder()).append(lename).append(":Others").toString(); li = 2; } } if (!getUserIFF(pUsername).containsKey(lcname)) { checkEntityStatic(lename, entity, li, null); } return getIFF(pUsername, lcname, entity.worldObj); } public static void loadIFFs() { // 1.10.2対策(#108) // loadIFF(""); // 初期値 loadIFF(null); // UUID別のデータを読み込む File lfile = new File((File) FMLInjectionData.data()[6], "config"); if (!lfile.exists()) { lfile.mkdir(); } for (File lf : lfile.listFiles()) { LittleMaidReengaged.Debug("FIND FILE %s", lf.getName()); if (lf.getName().startsWith("littleMaidMob_")&&lf.getName().endsWith(".iff")) { String ls = lf.getName().substring(14, lf.getName().length() - 4); LittleMaidReengaged.Debug(ls); loadIFF(UUID.fromString(ls)); } } } protected static File getFile(UUID pUsername) { LittleMaidReengaged.Debug("GetFile."); File lfile; if (pUsername == null) { lfile = new File("config/littleMaidMob.iff"); } else { String lfilename; lfilename = "./config/littleMaidMob_".concat(pUsername.toString()).concat(".iff"); lfile = new File(lfilename); } LittleMaidReengaged.Debug(lfile.getAbsolutePath()); return lfile; } public static void loadIFF(UUID pUsername) { // IFF ファイルの読込み // 動作はサーバー側で想定 File lfile = getFile(pUsername); if (!(lfile.exists() && lfile.canRead())) { return; } Map<String, Byte> lmap = getUserIFF(pUsername); try { FileReader fr = new FileReader(lfile); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { String t[] = s.split("="); if (t.length > 1) { byte i = Byte.valueOf(t[1]); if (i > 2) { i = iff_Unknown; } lmap.put(t[0], i); } } br.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static void saveIFF(UUID pUsername) { // IFF ファイルの書込み LittleMaidReengaged.Debug("Save IFF, %s", pUsername.toString()); File lfile = getFile(pUsername); Map<String, Byte> lmap = getUserIFF(pUsername); try { if ((lfile.exists() || lfile.createNewFile()) && lfile.canWrite()) { FileWriter fw = new FileWriter(lfile); BufferedWriter bw = new BufferedWriter(fw); for (Map.Entry<String, Byte> me : lmap.entrySet()) { bw.write(String.format("%s=%d\r\n", me.getKey(), me.getValue())); } bw.close(); fw.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Verclene/LittleMaidReengaged
src/main/java/net/blacklab/lmr/util/IFF.java
2,949
// 他人の家畜
line_comment
zh-cn
package net.blacklab.lmr.util; import net.blacklab.lmr.LittleMaidReengaged; import net.blacklab.lmr.entity.littlemaid.EntityLittleMaid; import net.blacklab.lmr.util.helper.OwnableEntityHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IEntityOwnable; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityOcelot; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.FMLInjectionData; import java.io.*; import java.util.*; /** * IFFを管理するためのクラス、ほぼマルチ用。 * username : null=ローカルプレイ時、Defaultを使う */ public class IFF { public static final byte iff_Enemy = 0; public static final byte iff_Unknown = 1; public static final byte iff_Friendry = 2; /** * ローカル用、若しくはマルチのデフォルト設定 */ private static Map<String, Byte> DefaultIFF = new TreeMap<>(); /** * ユーザ毎のIFF */ private static Map<UUID, Map<String, Byte>> UserIFF = new HashMap<>(); /** * IFFのゲット */ public static Map<String, Byte> getUserIFF(UUID pUsername) { if (pUsername == null) { return DefaultIFF; } // if (CommonHelper.isLocalPlay()) { // pUsername = EntityPlayer.getOfflineUUID("Player"); // } if (!UserIFF.containsKey(pUsername)) { // IFFがないので作成 Map<String, Byte> lmap = new HashMap<>(); lmap.putAll(DefaultIFF); UserIFF.put(pUsername, lmap); } // 既にある return UserIFF.get(pUsername); } public static void setIFFValue(UUID pUsername, String pName, byte pValue) { Map<String, Byte> lmap = getUserIFF(pUsername); lmap.put(pName, pValue); } public static byte checkEntityStatic(String pName, Entity pEntity, int pIndex, Map<String, Entity> pMap) { byte liff = IFF.iff_Unknown; if (pEntity instanceof EntityLivingBase) { if (pEntity instanceof EntityArmorStand) { liff = iff_Friendry; } if (pEntity instanceof EntityLittleMaid) { switch (pIndex) { case 0: // 野生種 liff = IFF.iff_Unknown; break; case 1: // 自分の契約者 pName = (new StringBuilder()).append(pName).append(":Contract").toString(); ((EntityLittleMaid) pEntity).setContract(true); liff = IFF.iff_Friendry; break; case 2: // 他人の契約者 pName = (new StringBuilder()).append(pName).append(":Others").toString(); ((EntityLittleMaid) pEntity).setContract(true); liff = IFF.iff_Friendry; break; } } else if (pEntity instanceof IEntityOwnable) { switch (pIndex) { case 0: // 野生種 break; case 1: // 自分の家畜 pName = (new StringBuilder()).append(pName).append(":Tame").toString(); if (pEntity instanceof EntityTameable) { ((EntityTameable) pEntity).setTamed(true); } liff = IFF.iff_Friendry; break; case 2: // 他人 <SUF> pName = (new StringBuilder()).append(pName).append(":Others").toString(); if (pEntity instanceof EntityTameable) { ((EntityTameable) pEntity).setTamed(true); } liff = IFF.iff_Unknown; break; } if (pIndex != 0) { if (pEntity instanceof EntityOcelot) { ((EntityOcelot) pEntity).setTameSkin(1 + (new Random()).nextInt(3)); } } } if (pMap != null) { // 表示用Entityの追加 pMap.put(pName, pEntity); LittleMaidReengaged.Debug(pName + " added."); } // IFFの初期値 if (!DefaultIFF.containsKey(pName)) { if (pEntity instanceof IMob) { liff = IFF.iff_Enemy; } DefaultIFF.put(pName, liff); } } return liff; } /** * 敵味方識別判定 */ public static byte getIFF(UUID pUsername, String entityname, World world) { if (entityname == null) { return iff_Friendry; } byte lt = iff_Enemy; Map<String, Byte> lmap = getUserIFF(pUsername); if (lmap.containsKey(entityname)) { lt = lmap.get(entityname); } else if (lmap != DefaultIFF && DefaultIFF.containsKey(entityname)) { // 未登録だけどDefaultには設定がある時は値をコピー lt = DefaultIFF.get(entityname); lmap.put(entityname, lt); } else { // 未登録Entityの場合は登録動作 int li = entityname.indexOf(":"); String ls; if (li > -1) { ls = entityname.substring(0, li); } else { ls = entityname; } Entity lentity = EntityList.createEntityByName(ls, world); li = 0; if (entityname.indexOf(":Contract") > -1) { li = 1; } else if (entityname.indexOf(":Tame") > -1) { li = 1; } else if (entityname.indexOf(":Others") > -1) { li = 2; } lt = checkEntityStatic(ls, lentity, li, null); lmap.put(entityname, lt); } return lt; } /** * 敵味方識別判定 */ public static int getIFF(UUID pUsername, Entity entity) { if (entity == null || !(entity instanceof EntityLivingBase)) { return iff_Friendry; } String lename = EntityList.getEntityString(entity); String lcname = lename; if (lename == null) { // 名称未定義MOB、プレーヤーとか? return iff_Friendry; // return mod_LMM_littleMaidMob.Aggressive ? iff_Unknown : // iff_Friendry; } int li = 0; if (entity instanceof EntityLittleMaid) { if (((EntityLittleMaid) entity).isContract()) { if (((EntityLittleMaid) entity).getMaidMasterUUID().equals(pUsername)) { // 自分の lcname = (new StringBuilder()).append(lename).append(":Contract").toString(); li = 1; } else { // 他人の lcname = (new StringBuilder()).append(lename).append(":Others").toString(); li = 2; } } } else if (entity instanceof IEntityOwnable) { UUID loname = OwnableEntityHelper.getOwner((IEntityOwnable)entity); if (loname.equals(pUsername)) { // 自分の lcname = (new StringBuilder()).append(lename).append(":Tame").toString(); li = 1; } else { // 他人の lcname = (new StringBuilder()).append(lename).append(":Others").toString(); li = 2; } } if (!getUserIFF(pUsername).containsKey(lcname)) { checkEntityStatic(lename, entity, li, null); } return getIFF(pUsername, lcname, entity.worldObj); } public static void loadIFFs() { // 1.10.2対策(#108) // loadIFF(""); // 初期値 loadIFF(null); // UUID別のデータを読み込む File lfile = new File((File) FMLInjectionData.data()[6], "config"); if (!lfile.exists()) { lfile.mkdir(); } for (File lf : lfile.listFiles()) { LittleMaidReengaged.Debug("FIND FILE %s", lf.getName()); if (lf.getName().startsWith("littleMaidMob_")&&lf.getName().endsWith(".iff")) { String ls = lf.getName().substring(14, lf.getName().length() - 4); LittleMaidReengaged.Debug(ls); loadIFF(UUID.fromString(ls)); } } } protected static File getFile(UUID pUsername) { LittleMaidReengaged.Debug("GetFile."); File lfile; if (pUsername == null) { lfile = new File("config/littleMaidMob.iff"); } else { String lfilename; lfilename = "./config/littleMaidMob_".concat(pUsername.toString()).concat(".iff"); lfile = new File(lfilename); } LittleMaidReengaged.Debug(lfile.getAbsolutePath()); return lfile; } public static void loadIFF(UUID pUsername) { // IFF ファイルの読込み // 動作はサーバー側で想定 File lfile = getFile(pUsername); if (!(lfile.exists() && lfile.canRead())) { return; } Map<String, Byte> lmap = getUserIFF(pUsername); try { FileReader fr = new FileReader(lfile); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { String t[] = s.split("="); if (t.length > 1) { byte i = Byte.valueOf(t[1]); if (i > 2) { i = iff_Unknown; } lmap.put(t[0], i); } } br.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static void saveIFF(UUID pUsername) { // IFF ファイルの書込み LittleMaidReengaged.Debug("Save IFF, %s", pUsername.toString()); File lfile = getFile(pUsername); Map<String, Byte> lmap = getUserIFF(pUsername); try { if ((lfile.exists() || lfile.createNewFile()) && lfile.canWrite()) { FileWriter fw = new FileWriter(lfile); BufferedWriter bw = new BufferedWriter(fw); for (Map.Entry<String, Byte> me : lmap.entrySet()) { bw.write(String.format("%s=%d\r\n", me.getKey(), me.getValue())); } bw.close(); fw.close(); } } catch (Exception e) { e.printStackTrace(); } } }
false
2,564
7
2,933
9
2,801
6
2,931
9
3,810
10
false
false
false
false
false
true
43478_2
package mode.victor.com; import model.victor.com.WangPo; /** * 代理模式 * Created by victor on 2016/3/23 0023. * 为其他对象提供一种代理以控制对这个对象的访问。 * * 水浒传是这样写的:西门庆被潘金莲用竹竿敲了一下,西门庆看痴迷了,被王婆看到了,就开始撮合两人好事,王婆作为潘金莲的代理人收了不少好处费,那我们假设一下: * 如果没有王婆在中间牵线,这两个不要脸的能成事吗?难说得很! */ public class PoxyMode { public static void main(String[] args) { test(); } public static void test () { WangPo wangPo; //把王婆叫出来 wangPo = new WangPo(); //然后西门庆说,我要和潘金莲Happy,然后王婆就安排了西门庆丢筷子哪出戏: wangPo.makeEyesWithMan(); //看到没有表面是王婆在做,其实爽的是潘金莲 wangPo.happyWithMan(); } }
Victor2018/FlowFunny
app/src/main/java/mode/victor/com/PoxyMode.java
329
//然后西门庆说,我要和潘金莲Happy,然后王婆就安排了西门庆丢筷子哪出戏:
line_comment
zh-cn
package mode.victor.com; import model.victor.com.WangPo; /** * 代理模式 * Created by victor on 2016/3/23 0023. * 为其他对象提供一种代理以控制对这个对象的访问。 * * 水浒传是这样写的:西门庆被潘金莲用竹竿敲了一下,西门庆看痴迷了,被王婆看到了,就开始撮合两人好事,王婆作为潘金莲的代理人收了不少好处费,那我们假设一下: * 如果没有王婆在中间牵线,这两个不要脸的能成事吗?难说得很! */ public class PoxyMode { public static void main(String[] args) { test(); } public static void test () { WangPo wangPo; //把王婆叫出来 wangPo = new WangPo(); //然后 <SUF> wangPo.makeEyesWithMan(); //看到没有表面是王婆在做,其实爽的是潘金莲 wangPo.happyWithMan(); } }
false
264
29
329
39
280
29
329
39
435
55
false
false
false
false
false
true
5545_0
package com.fanneng.android.web.utils; import android.os.Parcel; import android.os.Parcelable; /** * 默认消息配置 */ public final class DefaultMsgConfig { private DownLoadMsgConfig mDownLoadMsgConfig = null; private ChromeClientMsgCfg mChromeClientMsgCfg = new ChromeClientMsgCfg(); public ChromeClientMsgCfg getChromeClientMsgCfg() { return mChromeClientMsgCfg; } private WebViewClientMsgCfg mWebViewClientMsgCfg=new WebViewClientMsgCfg(); public WebViewClientMsgCfg getWebViewClientMsgCfg() { return mWebViewClientMsgCfg; } public DefaultMsgConfig() { mDownLoadMsgConfig = new DownLoadMsgConfig(); } public DownLoadMsgConfig getDownLoadMsgConfig() { return mDownLoadMsgConfig; } public static class DownLoadMsgConfig implements Parcelable { private String mTaskHasBeenExist = "该任务已经存在 , 请勿重复点击下载!"; private String mTips = "提示"; private String mHoneycomblow = "您正在使用手机流量 , 继续下载该文件吗?"; private String mDownLoad = "下载"; private String mCancel = "取消"; private String mDownLoadFail = "下载失败!"; private String mLoading = "当前进度:%s"; private String mTrickter = "您有一条新通知"; private String mFileDownLoad = "文件下载"; private String mClickOpen = "点击打开"; private String preLoading = "即将开始下载文件"; public String getPreLoading() { return preLoading; } public void setPreLoading(String preLoading) { this.preLoading = preLoading; } DownLoadMsgConfig() { } protected DownLoadMsgConfig(Parcel in) { mTaskHasBeenExist = in.readString(); mTips = in.readString(); mHoneycomblow = in.readString(); mDownLoad = in.readString(); mCancel = in.readString(); mDownLoadFail = in.readString(); mLoading = in.readString(); mTrickter = in.readString(); mFileDownLoad = in.readString(); mClickOpen = in.readString(); } public static final Creator<DownLoadMsgConfig> CREATOR = new Creator<DownLoadMsgConfig>() { @Override public DownLoadMsgConfig createFromParcel(Parcel in) { return new DownLoadMsgConfig(in); } @Override public DownLoadMsgConfig[] newArray(int size) { return new DownLoadMsgConfig[size]; } }; public String getTaskHasBeenExist() { return mTaskHasBeenExist; } public void setTaskHasBeenExist(String taskHasBeenExist) { mTaskHasBeenExist = taskHasBeenExist; } public String getTips() { return mTips; } public void setTips(String tips) { mTips = tips; } public String getHoneycomblow() { return mHoneycomblow; } public void setHoneycomblow(String honeycomblow) { mHoneycomblow = honeycomblow; } public String getDownLoad() { return mDownLoad; } public void setDownLoad(String downLoad) { mDownLoad = downLoad; } public String getCancel() { return mCancel; } public void setCancel(String cancel) { mCancel = cancel; } public String getDownLoadFail() { return mDownLoadFail; } public void setDownLoadFail(String downLoadFail) { mDownLoadFail = downLoadFail; } public String getLoading() { return mLoading; } public void setLoading(String loading) { mLoading = loading; } public String getTrickter() { return mTrickter; } public void setTrickter(String trickter) { mTrickter = trickter; } public String getFileDownLoad() { return mFileDownLoad; } public void setFileDownLoad(String fileDownLoad) { mFileDownLoad = fileDownLoad; } public String getClickOpen() { return mClickOpen; } public void setClickOpen(String clickOpen) { mClickOpen = clickOpen; } @Override public boolean equals(Object mo) { if (this == mo) return true; if (!(mo instanceof DownLoadMsgConfig)) return false; DownLoadMsgConfig mthat = (DownLoadMsgConfig) mo; if (!getTaskHasBeenExist().equals(mthat.getTaskHasBeenExist())) return false; if (!getTips().equals(mthat.getTips())) return false; if (!getHoneycomblow().equals(mthat.getHoneycomblow())) return false; if (!getDownLoad().equals(mthat.getDownLoad())) return false; if (!getCancel().equals(mthat.getCancel())) return false; if (!getDownLoadFail().equals(mthat.getDownLoadFail())) return false; if (!getLoading().equals(mthat.getLoading())) return false; if (!getTrickter().equals(mthat.getTrickter())) return false; if (!getFileDownLoad().equals(mthat.getFileDownLoad())) return false; return getClickOpen().equals(mthat.getClickOpen()); } @Override public int hashCode() { int mresult = getTaskHasBeenExist().hashCode(); mresult = 31 * mresult + getTips().hashCode(); mresult = 31 * mresult + getHoneycomblow().hashCode(); mresult = 31 * mresult + getDownLoad().hashCode(); mresult = 31 * mresult + getCancel().hashCode(); mresult = 31 * mresult + getDownLoadFail().hashCode(); mresult = 31 * mresult + getLoading().hashCode(); mresult = 31 * mresult + getTrickter().hashCode(); mresult = 31 * mresult + getFileDownLoad().hashCode(); mresult = 31 * mresult + getClickOpen().hashCode(); return mresult; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mTaskHasBeenExist); dest.writeString(mTips); dest.writeString(mHoneycomblow); dest.writeString(mDownLoad); dest.writeString(mCancel); dest.writeString(mDownLoadFail); dest.writeString(mLoading); dest.writeString(mTrickter); dest.writeString(mFileDownLoad); dest.writeString(mClickOpen); } } public static final class ChromeClientMsgCfg { private FileUploadMsgConfig mFileUploadMsgConfig = new FileUploadMsgConfig(); public FileUploadMsgConfig getFileUploadMsgConfig() { return mFileUploadMsgConfig; } public static final class FileUploadMsgConfig implements Parcelable { private String[] medias = new String[]{"相机", "文件选择器"}; FileUploadMsgConfig() { } protected FileUploadMsgConfig(Parcel in) { medias = in.createStringArray(); } public static final Creator<FileUploadMsgConfig> CREATOR = new Creator<FileUploadMsgConfig>() { @Override public FileUploadMsgConfig createFromParcel(Parcel in) { return new FileUploadMsgConfig(in); } @Override public FileUploadMsgConfig[] newArray(int size) { return new FileUploadMsgConfig[size]; } }; public void setMedias(String[] medias) { this.medias = medias; } public String[] getMedias() { return medias; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(medias); } } } public static final class WebViewClientMsgCfg implements Parcelable { private String leaveApp = "您需要离开%s前往其他应用吗?"; private String confirm = "离开"; private String cancel = "取消"; private String title="提示"; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } protected WebViewClientMsgCfg(Parcel in) { leaveApp = in.readString(); confirm = in.readString(); cancel = in.readString(); title=in.readString(); } public String getLeaveApp() { return leaveApp; } public void setLeaveApp(String leaveApp) { this.leaveApp = leaveApp; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } public String getCancel() { return cancel; } public void setCancel(String cancel) { this.cancel = cancel; } public static final Creator<WebViewClientMsgCfg> CREATOR = new Creator<WebViewClientMsgCfg>() { @Override public WebViewClientMsgCfg createFromParcel(Parcel in) { return new WebViewClientMsgCfg(in); } @Override public WebViewClientMsgCfg[] newArray(int size) { return new WebViewClientMsgCfg[size]; } }; public WebViewClientMsgCfg() { } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(leaveApp); dest.writeString(confirm); dest.writeString(cancel); dest.writeString(title); } } }
Victory-Over/SuperWeb
superweb/src/main/java/com/fanneng/android/web/utils/DefaultMsgConfig.java
2,214
/** * 默认消息配置 */
block_comment
zh-cn
package com.fanneng.android.web.utils; import android.os.Parcel; import android.os.Parcelable; /** * 默认消 <SUF>*/ public final class DefaultMsgConfig { private DownLoadMsgConfig mDownLoadMsgConfig = null; private ChromeClientMsgCfg mChromeClientMsgCfg = new ChromeClientMsgCfg(); public ChromeClientMsgCfg getChromeClientMsgCfg() { return mChromeClientMsgCfg; } private WebViewClientMsgCfg mWebViewClientMsgCfg=new WebViewClientMsgCfg(); public WebViewClientMsgCfg getWebViewClientMsgCfg() { return mWebViewClientMsgCfg; } public DefaultMsgConfig() { mDownLoadMsgConfig = new DownLoadMsgConfig(); } public DownLoadMsgConfig getDownLoadMsgConfig() { return mDownLoadMsgConfig; } public static class DownLoadMsgConfig implements Parcelable { private String mTaskHasBeenExist = "该任务已经存在 , 请勿重复点击下载!"; private String mTips = "提示"; private String mHoneycomblow = "您正在使用手机流量 , 继续下载该文件吗?"; private String mDownLoad = "下载"; private String mCancel = "取消"; private String mDownLoadFail = "下载失败!"; private String mLoading = "当前进度:%s"; private String mTrickter = "您有一条新通知"; private String mFileDownLoad = "文件下载"; private String mClickOpen = "点击打开"; private String preLoading = "即将开始下载文件"; public String getPreLoading() { return preLoading; } public void setPreLoading(String preLoading) { this.preLoading = preLoading; } DownLoadMsgConfig() { } protected DownLoadMsgConfig(Parcel in) { mTaskHasBeenExist = in.readString(); mTips = in.readString(); mHoneycomblow = in.readString(); mDownLoad = in.readString(); mCancel = in.readString(); mDownLoadFail = in.readString(); mLoading = in.readString(); mTrickter = in.readString(); mFileDownLoad = in.readString(); mClickOpen = in.readString(); } public static final Creator<DownLoadMsgConfig> CREATOR = new Creator<DownLoadMsgConfig>() { @Override public DownLoadMsgConfig createFromParcel(Parcel in) { return new DownLoadMsgConfig(in); } @Override public DownLoadMsgConfig[] newArray(int size) { return new DownLoadMsgConfig[size]; } }; public String getTaskHasBeenExist() { return mTaskHasBeenExist; } public void setTaskHasBeenExist(String taskHasBeenExist) { mTaskHasBeenExist = taskHasBeenExist; } public String getTips() { return mTips; } public void setTips(String tips) { mTips = tips; } public String getHoneycomblow() { return mHoneycomblow; } public void setHoneycomblow(String honeycomblow) { mHoneycomblow = honeycomblow; } public String getDownLoad() { return mDownLoad; } public void setDownLoad(String downLoad) { mDownLoad = downLoad; } public String getCancel() { return mCancel; } public void setCancel(String cancel) { mCancel = cancel; } public String getDownLoadFail() { return mDownLoadFail; } public void setDownLoadFail(String downLoadFail) { mDownLoadFail = downLoadFail; } public String getLoading() { return mLoading; } public void setLoading(String loading) { mLoading = loading; } public String getTrickter() { return mTrickter; } public void setTrickter(String trickter) { mTrickter = trickter; } public String getFileDownLoad() { return mFileDownLoad; } public void setFileDownLoad(String fileDownLoad) { mFileDownLoad = fileDownLoad; } public String getClickOpen() { return mClickOpen; } public void setClickOpen(String clickOpen) { mClickOpen = clickOpen; } @Override public boolean equals(Object mo) { if (this == mo) return true; if (!(mo instanceof DownLoadMsgConfig)) return false; DownLoadMsgConfig mthat = (DownLoadMsgConfig) mo; if (!getTaskHasBeenExist().equals(mthat.getTaskHasBeenExist())) return false; if (!getTips().equals(mthat.getTips())) return false; if (!getHoneycomblow().equals(mthat.getHoneycomblow())) return false; if (!getDownLoad().equals(mthat.getDownLoad())) return false; if (!getCancel().equals(mthat.getCancel())) return false; if (!getDownLoadFail().equals(mthat.getDownLoadFail())) return false; if (!getLoading().equals(mthat.getLoading())) return false; if (!getTrickter().equals(mthat.getTrickter())) return false; if (!getFileDownLoad().equals(mthat.getFileDownLoad())) return false; return getClickOpen().equals(mthat.getClickOpen()); } @Override public int hashCode() { int mresult = getTaskHasBeenExist().hashCode(); mresult = 31 * mresult + getTips().hashCode(); mresult = 31 * mresult + getHoneycomblow().hashCode(); mresult = 31 * mresult + getDownLoad().hashCode(); mresult = 31 * mresult + getCancel().hashCode(); mresult = 31 * mresult + getDownLoadFail().hashCode(); mresult = 31 * mresult + getLoading().hashCode(); mresult = 31 * mresult + getTrickter().hashCode(); mresult = 31 * mresult + getFileDownLoad().hashCode(); mresult = 31 * mresult + getClickOpen().hashCode(); return mresult; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mTaskHasBeenExist); dest.writeString(mTips); dest.writeString(mHoneycomblow); dest.writeString(mDownLoad); dest.writeString(mCancel); dest.writeString(mDownLoadFail); dest.writeString(mLoading); dest.writeString(mTrickter); dest.writeString(mFileDownLoad); dest.writeString(mClickOpen); } } public static final class ChromeClientMsgCfg { private FileUploadMsgConfig mFileUploadMsgConfig = new FileUploadMsgConfig(); public FileUploadMsgConfig getFileUploadMsgConfig() { return mFileUploadMsgConfig; } public static final class FileUploadMsgConfig implements Parcelable { private String[] medias = new String[]{"相机", "文件选择器"}; FileUploadMsgConfig() { } protected FileUploadMsgConfig(Parcel in) { medias = in.createStringArray(); } public static final Creator<FileUploadMsgConfig> CREATOR = new Creator<FileUploadMsgConfig>() { @Override public FileUploadMsgConfig createFromParcel(Parcel in) { return new FileUploadMsgConfig(in); } @Override public FileUploadMsgConfig[] newArray(int size) { return new FileUploadMsgConfig[size]; } }; public void setMedias(String[] medias) { this.medias = medias; } public String[] getMedias() { return medias; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(medias); } } } public static final class WebViewClientMsgCfg implements Parcelable { private String leaveApp = "您需要离开%s前往其他应用吗?"; private String confirm = "离开"; private String cancel = "取消"; private String title="提示"; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } protected WebViewClientMsgCfg(Parcel in) { leaveApp = in.readString(); confirm = in.readString(); cancel = in.readString(); title=in.readString(); } public String getLeaveApp() { return leaveApp; } public void setLeaveApp(String leaveApp) { this.leaveApp = leaveApp; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } public String getCancel() { return cancel; } public void setCancel(String cancel) { this.cancel = cancel; } public static final Creator<WebViewClientMsgCfg> CREATOR = new Creator<WebViewClientMsgCfg>() { @Override public WebViewClientMsgCfg createFromParcel(Parcel in) { return new WebViewClientMsgCfg(in); } @Override public WebViewClientMsgCfg[] newArray(int size) { return new WebViewClientMsgCfg[size]; } }; public WebViewClientMsgCfg() { } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(leaveApp); dest.writeString(confirm); dest.writeString(cancel); dest.writeString(title); } } }
false
2,102
7
2,214
8
2,420
8
2,214
8
2,822
12
false
false
false
false
false
true
8370_7
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.view.adapter; import android.support.v4.view.PagerAdapter; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import com.taobao.luaview.userdata.base.UDLuaTable; import com.taobao.luaview.userdata.ui.UDView; import com.taobao.luaview.userdata.ui.UDViewGroup; import com.taobao.luaview.userdata.ui.UDViewPager; import com.taobao.luaview.view.LVViewGroup; import org.luaj.vm2.Globals; import java.lang.ref.WeakReference; /** * Pager Adapter * * @author song * @date 15/9/17 */ public class LVPagerAdapter extends PagerAdapter { UDViewPager mInitProps; Globals mGlobals; SparseArray<WeakReference<View>> mViews; public LVPagerAdapter(Globals globals, UDViewPager udListView) { this.mGlobals = globals; this.mInitProps = udListView; this.mViews = new SparseArray<>(); } @Override public int getCount() { return this.mInitProps.getPageCount(); } @Override public CharSequence getPageTitle(int position) { return this.mInitProps.getPageTitle(position); } @Override public Object instantiateItem(ViewGroup container, int position) { return newItem(container, position); } public Object newItem(ViewGroup container, int position) { //View封装 UDView page = new UDViewGroup(createPageLayout(), mGlobals, null);//TODO 为什么用mLuaUserData.getmetatable()不行 //对外数据封装,必须使用LuaTable UDLuaTable pageData = new UDLuaTable(page); View pageView = pageData.getView(); //添加view if(container != null && pageView != null) { container.addView(pageView); } //初始化View initView(pageData, position); //绘制数据 renderView(pageData, position); //add to list mViews.put(position, new WeakReference<View>(pageView)); return pageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { removeItem(container, position, object); } /** * remove item from container * * @param container * @param position * @param object */ void removeItem(ViewGroup container, int position, Object object) { if (container != null && object instanceof View) { container.removeView((View) object); } } /** * 调用LuaView的Init方法进行Cell的初始化 * * @param position * @return */ void initView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageInit(page, position); this.mGlobals.restoreContainer(); } /** * 调用LuaView的Layout方法进行数据填充 * * @param page * @param position */ void renderView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageLayout(page, position); this.mGlobals.restoreContainer(); } /** * 创建 cell 的布局 * * @return */ LVViewGroup createPageLayout() { return new LVViewGroup(mGlobals, mInitProps.getmetatable(), null); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }
VideoOS/VideoOS-Android-SDK
VideoOS/LuaViewSDK/src/com/taobao/luaview/view/adapter/LVPagerAdapter.java
946
//绘制数据
line_comment
zh-cn
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.view.adapter; import android.support.v4.view.PagerAdapter; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import com.taobao.luaview.userdata.base.UDLuaTable; import com.taobao.luaview.userdata.ui.UDView; import com.taobao.luaview.userdata.ui.UDViewGroup; import com.taobao.luaview.userdata.ui.UDViewPager; import com.taobao.luaview.view.LVViewGroup; import org.luaj.vm2.Globals; import java.lang.ref.WeakReference; /** * Pager Adapter * * @author song * @date 15/9/17 */ public class LVPagerAdapter extends PagerAdapter { UDViewPager mInitProps; Globals mGlobals; SparseArray<WeakReference<View>> mViews; public LVPagerAdapter(Globals globals, UDViewPager udListView) { this.mGlobals = globals; this.mInitProps = udListView; this.mViews = new SparseArray<>(); } @Override public int getCount() { return this.mInitProps.getPageCount(); } @Override public CharSequence getPageTitle(int position) { return this.mInitProps.getPageTitle(position); } @Override public Object instantiateItem(ViewGroup container, int position) { return newItem(container, position); } public Object newItem(ViewGroup container, int position) { //View封装 UDView page = new UDViewGroup(createPageLayout(), mGlobals, null);//TODO 为什么用mLuaUserData.getmetatable()不行 //对外数据封装,必须使用LuaTable UDLuaTable pageData = new UDLuaTable(page); View pageView = pageData.getView(); //添加view if(container != null && pageView != null) { container.addView(pageView); } //初始化View initView(pageData, position); //绘制 <SUF> renderView(pageData, position); //add to list mViews.put(position, new WeakReference<View>(pageView)); return pageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { removeItem(container, position, object); } /** * remove item from container * * @param container * @param position * @param object */ void removeItem(ViewGroup container, int position, Object object) { if (container != null && object instanceof View) { container.removeView((View) object); } } /** * 调用LuaView的Init方法进行Cell的初始化 * * @param position * @return */ void initView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageInit(page, position); this.mGlobals.restoreContainer(); } /** * 调用LuaView的Layout方法进行数据填充 * * @param page * @param position */ void renderView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageLayout(page, position); this.mGlobals.restoreContainer(); } /** * 创建 cell 的布局 * * @return */ LVViewGroup createPageLayout() { return new LVViewGroup(mGlobals, mInitProps.getmetatable(), null); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }
false
846
3
946
4
994
3
946
4
1,169
7
false
false
false
false
false
true
47841_4
package com.vinctor.vcharts; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.vinctor.vchartviews.radar.RadarChart; import com.vinctor.vchartviews.radar.RadarData; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.OnClick; public class RadarActivity extends BaseActivity { RadarChart radarView; public static void start(Context context) { Intent starter = new Intent(context, RadarActivity.class); context.startActivity(starter); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_radar); ButterKnife.bind(this); radarView = (RadarChart) findViewById(R.id.radarview); List<RadarData> list = new ArrayList<>(); RadarData data = new RadarData(); data.setColor(0x44F594A0); data.setDatas(new float[]{80, 70, 30, 70, 80, 100}); list.add(data); RadarData data2 = new RadarData(); data2.setColor(0x44317AA4); data2.setDatas(new float[]{92, 880, 84, 67, 88, 78}); list.add(data2); setSetting(); radarView // .setShowShadow(false) .setList(list)//设置数据 .setTitles(new String[]{"语文", "数学", "英语", "物理", "化学", "生物"})//边角文字 .commit();//以上设置需要此方法才能生效 } private void setSetting() { radarView.setCount(6)//多边形几条边 .setDensity(6)//雷达图蜘蛛网密度 .setMinAndMax(0, 100)//最小与最大值 .setTitleTextSize(30)//雷达边角标题文字大小(px)默认30 .setTagTextSize(30)//雷达刻度文字大小 .commit(); } @OnClick(R.id.auto) public void onViewClicked() { radarView.setAuto(!radarView.isAuto()); setSetting(); } }
Vinctor/VCharts
app/src/main/java/com/vinctor/vcharts/RadarActivity.java
581
//多边形几条边
line_comment
zh-cn
package com.vinctor.vcharts; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.vinctor.vchartviews.radar.RadarChart; import com.vinctor.vchartviews.radar.RadarData; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.OnClick; public class RadarActivity extends BaseActivity { RadarChart radarView; public static void start(Context context) { Intent starter = new Intent(context, RadarActivity.class); context.startActivity(starter); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_radar); ButterKnife.bind(this); radarView = (RadarChart) findViewById(R.id.radarview); List<RadarData> list = new ArrayList<>(); RadarData data = new RadarData(); data.setColor(0x44F594A0); data.setDatas(new float[]{80, 70, 30, 70, 80, 100}); list.add(data); RadarData data2 = new RadarData(); data2.setColor(0x44317AA4); data2.setDatas(new float[]{92, 880, 84, 67, 88, 78}); list.add(data2); setSetting(); radarView // .setShowShadow(false) .setList(list)//设置数据 .setTitles(new String[]{"语文", "数学", "英语", "物理", "化学", "生物"})//边角文字 .commit();//以上设置需要此方法才能生效 } private void setSetting() { radarView.setCount(6)//多边 <SUF> .setDensity(6)//雷达图蜘蛛网密度 .setMinAndMax(0, 100)//最小与最大值 .setTitleTextSize(30)//雷达边角标题文字大小(px)默认30 .setTagTextSize(30)//雷达刻度文字大小 .commit(); } @OnClick(R.id.auto) public void onViewClicked() { radarView.setAuto(!radarView.isAuto()); setSetting(); } }
false
490
7
581
7
575
7
581
7
697
9
false
false
false
false
false
true
9388_0
/* 授权声明: 本源码系《Java多线程编程实战指南(核心篇)》一书(ISBN:978-7-121-31065-2,以下称之为“原书”)的配套源码, 欲了解本代码的更多细节,请参考原书。 本代码仅为原书的配套说明之用,并不附带任何承诺(如质量保证和收益)。 以任何形式将本代码之部分或者全部用于营利性用途需经版权人书面同意。 将本代码之部分或者全部用于非营利性用途需要在代码中保留本声明。 任何对本代码的修改需在代码中以注释的形式注明修改人、修改时间以及修改内容。 本代码可以从以下网址下载: https://github.com/Viscent/javamtia http://www.broadview.com.cn/31065 */ package io.github.viscent.mtia.ch7; import io.github.viscent.mtia.util.Tools; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * 本程序演示嵌套监视器锁死(线程活性故障)现象。 * * @author Viscent Huang */ public class NestedMonitorLockoutDemo { private final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10); private int processed = 0; private int accepted = 0; public static void main(String[] args) throws InterruptedException { NestedMonitorLockoutDemo demo = new NestedMonitorLockoutDemo(); demo.start(); int i = 0; while (i-- < 100000) { demo.accept("message" + i); Tools.randomPause(100); } } public synchronized void accept(String message) throws InterruptedException { // 不要在临界区内调用BlockingQueue的阻塞方法!那样会导致嵌套监视器锁死 queue.put(message); accepted++; } protected synchronized void doProcess() throws InterruptedException { // 不要在临界区内调用BlockingQueue的阻塞方法!那样会导致嵌套监视器锁死 String msg = queue.take(); System.out.println("Process:" + msg); processed++; } public void start() { new WorkerThread().start(); } public synchronized int[] getStat() { return new int[] { accepted, processed }; } class WorkerThread extends Thread { @Override public void run() { try { while (true) { doProcess(); } } catch (InterruptedException e) { ; } } } }
Viscent/javamtia
JavaMultiThreadInAction/src/io/github/viscent/mtia/ch7/NestedMonitorLockoutDemo.java
645
/* 授权声明: 本源码系《Java多线程编程实战指南(核心篇)》一书(ISBN:978-7-121-31065-2,以下称之为“原书”)的配套源码, 欲了解本代码的更多细节,请参考原书。 本代码仅为原书的配套说明之用,并不附带任何承诺(如质量保证和收益)。 以任何形式将本代码之部分或者全部用于营利性用途需经版权人书面同意。 将本代码之部分或者全部用于非营利性用途需要在代码中保留本声明。 任何对本代码的修改需在代码中以注释的形式注明修改人、修改时间以及修改内容。 本代码可以从以下网址下载: https://github.com/Viscent/javamtia http://www.broadview.com.cn/31065 */
block_comment
zh-cn
/* 授权声 <SUF>*/ package io.github.viscent.mtia.ch7; import io.github.viscent.mtia.util.Tools; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * 本程序演示嵌套监视器锁死(线程活性故障)现象。 * * @author Viscent Huang */ public class NestedMonitorLockoutDemo { private final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10); private int processed = 0; private int accepted = 0; public static void main(String[] args) throws InterruptedException { NestedMonitorLockoutDemo demo = new NestedMonitorLockoutDemo(); demo.start(); int i = 0; while (i-- < 100000) { demo.accept("message" + i); Tools.randomPause(100); } } public synchronized void accept(String message) throws InterruptedException { // 不要在临界区内调用BlockingQueue的阻塞方法!那样会导致嵌套监视器锁死 queue.put(message); accepted++; } protected synchronized void doProcess() throws InterruptedException { // 不要在临界区内调用BlockingQueue的阻塞方法!那样会导致嵌套监视器锁死 String msg = queue.take(); System.out.println("Process:" + msg); processed++; } public void start() { new WorkerThread().start(); } public synchronized int[] getStat() { return new int[] { accepted, processed }; } class WorkerThread extends Thread { @Override public void run() { try { while (true) { doProcess(); } } catch (InterruptedException e) { ; } } } }
false
563
190
645
228
649
206
645
228
875
327
false
false
false
false
false
true
59245_0
/* 授权声明: 本源码系《Java多线程编程实战指南(设计模式篇)第2版》一书(ISBN:978-7-121-38245-1,以下称之为“原书”)的配套源码, 欲了解本代码的更多细节,请参考原书。 本代码仅为原书的配套说明之用,并不附带任何承诺(如质量保证和收益)。 以任何形式将本代码之部分或者全部用于营利性用途需经版权人书面同意。 将本代码之部分或者全部用于非营利性用途需要在代码中保留本声明。 任何对本代码的修改需在代码中以注释的形式注明修改人、修改时间以及修改内容。 本代码可以从以下网址下载: https://github.com/Viscent/javamtp http://www.broadview.com.cn/38245 */ package io.github.viscent.util; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date; public class Debug { private static ThreadLocal<SimpleDateFormat> sdfWrapper = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } }; enum Label { INFO("INFO"), ERR("ERROR"); String name; Label(String name) { this.name = name; } public String getName() { return name; } } // public static void info(String message) { // printf(Label.INFO, "%s", message); // } public static void info(String format, Object... args) { printf(Label.INFO, format, args); } public static void info(boolean message) { info("%s", message); } public static void info(int message) { info("%d", message); } public static void error(String message, Object... args) { printf(Label.ERR, message, args); } public static void printf(Label label, String format, Object... args) { SimpleDateFormat sdf = sdfWrapper.get(); @SuppressWarnings("resource") final PrintStream ps = label == Label.INFO ? System.out : System.err; ps.printf('[' + sdf.format(new Date()) + "][" + label.getName() + "][" + Thread.currentThread().getName() + "]:" + format + " %n", args); } }
Viscent/javamtp
JavaConcurrencyPatternInAction/src/io/github/viscent/util/Debug.java
596
/* 授权声明: 本源码系《Java多线程编程实战指南(设计模式篇)第2版》一书(ISBN:978-7-121-38245-1,以下称之为“原书”)的配套源码, 欲了解本代码的更多细节,请参考原书。 本代码仅为原书的配套说明之用,并不附带任何承诺(如质量保证和收益)。 以任何形式将本代码之部分或者全部用于营利性用途需经版权人书面同意。 将本代码之部分或者全部用于非营利性用途需要在代码中保留本声明。 任何对本代码的修改需在代码中以注释的形式注明修改人、修改时间以及修改内容。 本代码可以从以下网址下载: https://github.com/Viscent/javamtp http://www.broadview.com.cn/38245 */
block_comment
zh-cn
/* 授权声 <SUF>*/ package io.github.viscent.util; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date; public class Debug { private static ThreadLocal<SimpleDateFormat> sdfWrapper = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } }; enum Label { INFO("INFO"), ERR("ERROR"); String name; Label(String name) { this.name = name; } public String getName() { return name; } } // public static void info(String message) { // printf(Label.INFO, "%s", message); // } public static void info(String format, Object... args) { printf(Label.INFO, format, args); } public static void info(boolean message) { info("%s", message); } public static void info(int message) { info("%d", message); } public static void error(String message, Object... args) { printf(Label.ERR, message, args); } public static void printf(Label label, String format, Object... args) { SimpleDateFormat sdf = sdfWrapper.get(); @SuppressWarnings("resource") final PrintStream ps = label == Label.INFO ? System.out : System.err; ps.printf('[' + sdf.format(new Date()) + "][" + label.getName() + "][" + Thread.currentThread().getName() + "]:" + format + " %n", args); } }
false
515
194
596
232
612
210
596
232
764
330
false
false
false
false
false
true
38340_11
package getTicket; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.swing.JOptionPane; public class Mail { private MimeMessage mimeMsg; //MIME邮件对象 private Session session; //邮件会话对象 private Properties props; //系统属性 private boolean needAuth = false; //smtp是否需要认证 //smtp认证用户名和密码 private String username; private String password; private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 /** * Constructor * @param smtp 邮件发送服务器 */ public Mail(String smtp){ setSmtpHost(smtp); createMimeMessage(); } /** * 设置邮件发送服务器 * @param hostName String */ public void setSmtpHost(String hostName) { System.out.println("设置系统属性:mail.smtp.host = "+hostName); if(props == null) props = System.getProperties(); //获得系统属性对象 props.put("mail.smtp.host",hostName); //设置SMTP主机 } /** * 创建MIME邮件对象 * @return */ public boolean createMimeMessage() { try { System.out.println("准备获取邮件会话对象!"); session = Session.getDefaultInstance(props,null); //获得邮件会话对象 } catch(Exception e){ System.err.println("获取邮件会话对象时发生错误!"+e); return false; } System.out.println("准备创建MIME邮件对象!"); try { mimeMsg = new MimeMessage(session); //创建MIME邮件对象 mp = new MimeMultipart(); return true; } catch(Exception e){ System.err.println("创建MIME邮件对象失败!"+e); return false; } } /** * 设置SMTP是否需要验证 * @param need */ public void setNeedAuth(boolean need) { System.out.println("设置smtp身份认证:mail.smtp.auth = "+need); if(props == null) props = System.getProperties(); if(need){ props.put("mail.smtp.auth","true"); }else{ props.put("mail.smtp.auth","false"); } } /** * 设置用户名和密码 * @param name * @param pass */ public void setNamePass(String name,String pass) { username = name; password = pass; } /** * 设置邮件主题 * @param mailSubject * @return */ public boolean setSubject(String mailSubject) { System.out.println("设置邮件主题!"); try{ mimeMsg.setSubject(mailSubject); return true; } catch(Exception e) { System.err.println("设置邮件主题发生错误!"); return false; } } /** * 设置邮件正文 * @param mailBody String */ public boolean setBody(String mailBody) { try{ BodyPart bp = new MimeBodyPart(); bp.setContent(""+mailBody,"text/html;charset=GBK"); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println("设置邮件正文时发生错误!"+e); return false; } } /** * 添加附件 * @param filename String */ public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:"+filename); try{ BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println("增加邮件附件:"+filename+"发生错误!"+e); return false; } } /** * 设置发信人 * @param from String */ public boolean setFrom(String from) { System.out.println("设置发信人!"); try{ mimeMsg.setFrom(new InternetAddress(from)); //设置发信人 return true; } catch(Exception e) { return false; } } /** * 设置收信人 * @param to String */ public boolean setTo(String to){ if(to == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to)); return true; } catch(Exception e) { return false; } } /** * 设置抄送人 * @param copyto String */ public boolean setCopyTo(String copyto) { if(copyto == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); return true; } catch(Exception e) { return false; } } /** * 发送邮件 */ public boolean sendOut() { try{ mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println("正在发送邮件...."); Session mailSession = Session.getInstance(props,null); Transport transport = mailSession.getTransport("smtp"); transport.connect((String)props.get("mail.smtp.host"),username,password); transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO)); //JOptionPane.showMessageDialog(null,"邮件发送成功!请检查邮箱确认!");//调用发送邮件接口 TicketMonitor.working = false; TicketMonitor.bt4.setSelected(true); //TicketMonitor.bt3.setSelected(false); System.out.println("success"); //transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC)); //transport.send(mimeMsg); transport.close(); return true; } catch(Exception e) { e.printStackTrace(); if (e instanceof AuthenticationFailedException) JOptionPane.showMessageDialog(null,"邮件发送失败:请确认密码信息无误");//调用发送邮件接口 return false; } } /** * 调用sendOut方法完成邮件发送 * @param smtp * @param from * @param to * @param subject * @param content * @param username * @param password * @return boolean */ public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带抄送 * @param smtp * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @return boolean */ public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setCopyTo(copyto)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带附件 * @param smtp * @param from * @param to * @param subject * @param content * @param username * @param password * @param filename 附件路径 * @return */ public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.addFileAffix(filename)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带附件和抄送 * @param smtp * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @param filename * @return */ public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.addFileAffix(filename)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setCopyTo(copyto)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } }
VisturalLiu/12306-1
Mail.java
2,580
//获得邮件会话对象
line_comment
zh-cn
package getTicket; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.swing.JOptionPane; public class Mail { private MimeMessage mimeMsg; //MIME邮件对象 private Session session; //邮件会话对象 private Properties props; //系统属性 private boolean needAuth = false; //smtp是否需要认证 //smtp认证用户名和密码 private String username; private String password; private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 /** * Constructor * @param smtp 邮件发送服务器 */ public Mail(String smtp){ setSmtpHost(smtp); createMimeMessage(); } /** * 设置邮件发送服务器 * @param hostName String */ public void setSmtpHost(String hostName) { System.out.println("设置系统属性:mail.smtp.host = "+hostName); if(props == null) props = System.getProperties(); //获得系统属性对象 props.put("mail.smtp.host",hostName); //设置SMTP主机 } /** * 创建MIME邮件对象 * @return */ public boolean createMimeMessage() { try { System.out.println("准备获取邮件会话对象!"); session = Session.getDefaultInstance(props,null); //获得 <SUF> } catch(Exception e){ System.err.println("获取邮件会话对象时发生错误!"+e); return false; } System.out.println("准备创建MIME邮件对象!"); try { mimeMsg = new MimeMessage(session); //创建MIME邮件对象 mp = new MimeMultipart(); return true; } catch(Exception e){ System.err.println("创建MIME邮件对象失败!"+e); return false; } } /** * 设置SMTP是否需要验证 * @param need */ public void setNeedAuth(boolean need) { System.out.println("设置smtp身份认证:mail.smtp.auth = "+need); if(props == null) props = System.getProperties(); if(need){ props.put("mail.smtp.auth","true"); }else{ props.put("mail.smtp.auth","false"); } } /** * 设置用户名和密码 * @param name * @param pass */ public void setNamePass(String name,String pass) { username = name; password = pass; } /** * 设置邮件主题 * @param mailSubject * @return */ public boolean setSubject(String mailSubject) { System.out.println("设置邮件主题!"); try{ mimeMsg.setSubject(mailSubject); return true; } catch(Exception e) { System.err.println("设置邮件主题发生错误!"); return false; } } /** * 设置邮件正文 * @param mailBody String */ public boolean setBody(String mailBody) { try{ BodyPart bp = new MimeBodyPart(); bp.setContent(""+mailBody,"text/html;charset=GBK"); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println("设置邮件正文时发生错误!"+e); return false; } } /** * 添加附件 * @param filename String */ public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:"+filename); try{ BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println("增加邮件附件:"+filename+"发生错误!"+e); return false; } } /** * 设置发信人 * @param from String */ public boolean setFrom(String from) { System.out.println("设置发信人!"); try{ mimeMsg.setFrom(new InternetAddress(from)); //设置发信人 return true; } catch(Exception e) { return false; } } /** * 设置收信人 * @param to String */ public boolean setTo(String to){ if(to == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to)); return true; } catch(Exception e) { return false; } } /** * 设置抄送人 * @param copyto String */ public boolean setCopyTo(String copyto) { if(copyto == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); return true; } catch(Exception e) { return false; } } /** * 发送邮件 */ public boolean sendOut() { try{ mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println("正在发送邮件...."); Session mailSession = Session.getInstance(props,null); Transport transport = mailSession.getTransport("smtp"); transport.connect((String)props.get("mail.smtp.host"),username,password); transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO)); //JOptionPane.showMessageDialog(null,"邮件发送成功!请检查邮箱确认!");//调用发送邮件接口 TicketMonitor.working = false; TicketMonitor.bt4.setSelected(true); //TicketMonitor.bt3.setSelected(false); System.out.println("success"); //transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC)); //transport.send(mimeMsg); transport.close(); return true; } catch(Exception e) { e.printStackTrace(); if (e instanceof AuthenticationFailedException) JOptionPane.showMessageDialog(null,"邮件发送失败:请确认密码信息无误");//调用发送邮件接口 return false; } } /** * 调用sendOut方法完成邮件发送 * @param smtp * @param from * @param to * @param subject * @param content * @param username * @param password * @return boolean */ public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带抄送 * @param smtp * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @return boolean */ public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setCopyTo(copyto)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带附件 * @param smtp * @param from * @param to * @param subject * @param content * @param username * @param password * @param filename 附件路径 * @return */ public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.addFileAffix(filename)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带附件和抄送 * @param smtp * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @param filename * @return */ public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) { Mail theMail = new Mail(smtp); theMail.setNeedAuth(true); //需要验证 if(!theMail.setSubject(subject)) return false; if(!theMail.setBody(content)) return false; if(!theMail.addFileAffix(filename)) return false; if(!theMail.setTo(to)) return false; if(!theMail.setCopyTo(copyto)) return false; if(!theMail.setFrom(from)) return false; theMail.setNamePass(username,password); if(!theMail.sendOut()) return false; return true; } }
false
2,358
7
2,580
7
2,795
6
2,580
7
3,515
12
false
false
false
false
false
true
57036_1
package com.visualwallet.net; import java.util.HashMap; import java.util.Map; public class DownloadRequest extends NetRequest { private static final String subUrl = "/download"; private static final String reqFlag = "fileDownload"; private int id; private String type; public DownloadRequest(int id, String type) { this.id = id; this.type = type; } @Override public void run() { Map<String, Object> args = new HashMap<String, Object>(); args.put("reqFlag", reqFlag); // 傻逼后台,这里的id都是数字,其他API的id也都是int,就这个接口要我传string // 这个地方坑我半天,老是http500,而且完全没有response,浪费我两三个小时 args.put("id", String.valueOf(id)); args.put("type", type); Map response = NetUtil.filePost(NetUtil.getUrlBase() + subUrl, args, true, "g_" + id + ".wav"); callBack(response); } }
VisualDigitalWallet/VisualDigitalWallet
VisualWallet/app/src/main/java/com/visualwallet/net/DownloadRequest.java
259
// 这个地方坑我半天,老是http500,而且完全没有response,浪费我两三个小时
line_comment
zh-cn
package com.visualwallet.net; import java.util.HashMap; import java.util.Map; public class DownloadRequest extends NetRequest { private static final String subUrl = "/download"; private static final String reqFlag = "fileDownload"; private int id; private String type; public DownloadRequest(int id, String type) { this.id = id; this.type = type; } @Override public void run() { Map<String, Object> args = new HashMap<String, Object>(); args.put("reqFlag", reqFlag); // 傻逼后台,这里的id都是数字,其他API的id也都是int,就这个接口要我传string // 这个 <SUF> args.put("id", String.valueOf(id)); args.put("type", type); Map response = NetUtil.filePost(NetUtil.getUrlBase() + subUrl, args, true, "g_" + id + ".wav"); callBack(response); } }
false
228
25
259
30
266
24
259
30
310
44
false
false
false
false
false
true
36585_4
package com.wanzhk; import java.util.HashMap; /** * RESTFul 统一返回格式 * * @author Wanzhk * <p> * 2020-05-06 */ public class AjaxResult extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public static final String CODE_TAG = "code"; public static final String MSG_TAG = "msg"; public static final String DATA_TAG = "data"; /** * 状态类型 */ public enum Type { /** * 成功 */ SUCCESS(0), /** * 失败 */ FAIL(-1), /** * 警告 */ WARN(301), /** * 错误 */ ERROR(500); private final int value; Type(int value) { this.value = value; } public int value() { return this.value; } } /** * 状态类型 */ private Type type; /** * 状态码 */ private int code; /** * 返回内容 */ private String msg; /** * 数据对象 */ private Object data; /** * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 */ public AjaxResult() { } /** * 初始化一个新创建的 AjaxResult 对象 * * @param type 状态类型 * @param msg 返回内容 */ public AjaxResult(Type type, String msg) { super.put(CODE_TAG, type.value); super.put(MSG_TAG, msg); } /** * 初始化一个新创建的 AjaxResult 对象 * * @param type 状态类型 * @param msg 返回内容 * @param data 数据对象 */ public AjaxResult(Type type, String msg, Object data) { super.put(CODE_TAG, type.value); super.put(MSG_TAG, msg); super.put(DATA_TAG, data); } /** * 返回成功消息 * * @return 成功消息 */ public static AjaxResult success() { return AjaxResult.success("操作成功"); } /** * 返回成功消息 * * @param msg 返回内容 * @return 成功消息 */ public static AjaxResult success(String msg) { return AjaxResult.success(msg, null); } /** * 返回成功消息 * * @param msg 返回内容 * @param data 数据对象 * @return 成功消息 */ public static AjaxResult success(String msg, Object data) { return new AjaxResult(Type.SUCCESS, msg, data); } /** * 返回失败消息 * * @return 成功消息 */ public static AjaxResult fail() { return AjaxResult.fail("操作失败"); } /** * 返回失败消息 * * @param msg 返回内容 * @return 成功消息 */ public static AjaxResult fail(String msg) { return AjaxResult.fail(msg, null); } /** * 返回失败消息 * * @param msg 返回内容 * @param data 数据对象 * @return 成功消息 */ public static AjaxResult fail(String msg, Object data) { return new AjaxResult(Type.FAIL, msg, data); } /** * 返回警告消息 * * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult warn(String msg) { return AjaxResult.warn(msg, null); } /** * 返回警告消息 * * @param msg 返回内容 * @param data 数据对象 * @return 警告消息 */ public static AjaxResult warn(String msg, Object data) { return new AjaxResult(Type.WARN, msg, data); } /** * 返回错误消息 * * @return */ public static AjaxResult error() { return AjaxResult.error("操作失败"); } /** * 返回错误消息 * * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult error(String msg) { return AjaxResult.error(msg, null); } /** * 返回错误消息 * * @param msg 返回内容 * @param data 数据对象 * @return 警告消息 */ public static AjaxResult error(String msg, Object data) { return new AjaxResult(Type.ERROR, msg, data); } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
VolzK/grid-trading-platform
src/main/java/com/wanzhk/AjaxResult.java
1,164
/** * 警告 */
block_comment
zh-cn
package com.wanzhk; import java.util.HashMap; /** * RESTFul 统一返回格式 * * @author Wanzhk * <p> * 2020-05-06 */ public class AjaxResult extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public static final String CODE_TAG = "code"; public static final String MSG_TAG = "msg"; public static final String DATA_TAG = "data"; /** * 状态类型 */ public enum Type { /** * 成功 */ SUCCESS(0), /** * 失败 */ FAIL(-1), /** * 警告 <SUF>*/ WARN(301), /** * 错误 */ ERROR(500); private final int value; Type(int value) { this.value = value; } public int value() { return this.value; } } /** * 状态类型 */ private Type type; /** * 状态码 */ private int code; /** * 返回内容 */ private String msg; /** * 数据对象 */ private Object data; /** * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 */ public AjaxResult() { } /** * 初始化一个新创建的 AjaxResult 对象 * * @param type 状态类型 * @param msg 返回内容 */ public AjaxResult(Type type, String msg) { super.put(CODE_TAG, type.value); super.put(MSG_TAG, msg); } /** * 初始化一个新创建的 AjaxResult 对象 * * @param type 状态类型 * @param msg 返回内容 * @param data 数据对象 */ public AjaxResult(Type type, String msg, Object data) { super.put(CODE_TAG, type.value); super.put(MSG_TAG, msg); super.put(DATA_TAG, data); } /** * 返回成功消息 * * @return 成功消息 */ public static AjaxResult success() { return AjaxResult.success("操作成功"); } /** * 返回成功消息 * * @param msg 返回内容 * @return 成功消息 */ public static AjaxResult success(String msg) { return AjaxResult.success(msg, null); } /** * 返回成功消息 * * @param msg 返回内容 * @param data 数据对象 * @return 成功消息 */ public static AjaxResult success(String msg, Object data) { return new AjaxResult(Type.SUCCESS, msg, data); } /** * 返回失败消息 * * @return 成功消息 */ public static AjaxResult fail() { return AjaxResult.fail("操作失败"); } /** * 返回失败消息 * * @param msg 返回内容 * @return 成功消息 */ public static AjaxResult fail(String msg) { return AjaxResult.fail(msg, null); } /** * 返回失败消息 * * @param msg 返回内容 * @param data 数据对象 * @return 成功消息 */ public static AjaxResult fail(String msg, Object data) { return new AjaxResult(Type.FAIL, msg, data); } /** * 返回警告消息 * * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult warn(String msg) { return AjaxResult.warn(msg, null); } /** * 返回警告消息 * * @param msg 返回内容 * @param data 数据对象 * @return 警告消息 */ public static AjaxResult warn(String msg, Object data) { return new AjaxResult(Type.WARN, msg, data); } /** * 返回错误消息 * * @return */ public static AjaxResult error() { return AjaxResult.error("操作失败"); } /** * 返回错误消息 * * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult error(String msg) { return AjaxResult.error(msg, null); } /** * 返回错误消息 * * @param msg 返回内容 * @param data 数据对象 * @return 警告消息 */ public static AjaxResult error(String msg, Object data) { return new AjaxResult(Type.ERROR, msg, data); } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
false
1,149
10
1,164
8
1,337
9
1,164
8
1,583
12
false
false
false
false
false
true
41217_2
package project; import java.util.Arrays; import java.util.Random; //快速排序优化之三路快速排序 //将数组分为大于v、等于v、小于v三部分 //然后对数组进行排序 public class QuickSort3 { public static void main(String[] args) { int[] arr = {8,6,2,3,1,5,7,4,56,100,80}; quickSort(arr,arr.length); System.out.println(Arrays.toString(arr)); } public static void quickSort(int[] arr, int n) { __quickSort(arr, 0, n-1); } public static void __quickSort(int[] arr,int l, int r) { // if(l >= r) { // return; // } //配合插入排序进行优化 if(r -l <= 15){ InsertSort.sortByAsc(arr); return; } Random random = new Random(); SwapUtil.swap(arr, l, random.nextInt()%(r-l+1)); int v = arr[l]; //目的:将数组分为三部分 //arr[l+1...lt] < v //arr[gt...r] > v //arr[lt+1...i] == v int lt = l; int gt = r + 1; int i = l + 1; while(i < gt) { if(arr[i] < v) { SwapUtil.swap(arr, i, lt + 1); i++; lt++; }else if(arr[i] > v) { SwapUtil.swap(arr, i, gt-1); gt--; }else { i++; } } SwapUtil.swap(arr,l,lt); __quickSort(arr, l, lt-1); __quickSort(arr, gt, r); } }
Vtrily/Algorithm
QuickSort3.java
501
//然后对数组进行排序
line_comment
zh-cn
package project; import java.util.Arrays; import java.util.Random; //快速排序优化之三路快速排序 //将数组分为大于v、等于v、小于v三部分 //然后 <SUF> public class QuickSort3 { public static void main(String[] args) { int[] arr = {8,6,2,3,1,5,7,4,56,100,80}; quickSort(arr,arr.length); System.out.println(Arrays.toString(arr)); } public static void quickSort(int[] arr, int n) { __quickSort(arr, 0, n-1); } public static void __quickSort(int[] arr,int l, int r) { // if(l >= r) { // return; // } //配合插入排序进行优化 if(r -l <= 15){ InsertSort.sortByAsc(arr); return; } Random random = new Random(); SwapUtil.swap(arr, l, random.nextInt()%(r-l+1)); int v = arr[l]; //目的:将数组分为三部分 //arr[l+1...lt] < v //arr[gt...r] > v //arr[lt+1...i] == v int lt = l; int gt = r + 1; int i = l + 1; while(i < gt) { if(arr[i] < v) { SwapUtil.swap(arr, i, lt + 1); i++; lt++; }else if(arr[i] > v) { SwapUtil.swap(arr, i, gt-1); gt--; }else { i++; } } SwapUtil.swap(arr,l,lt); __quickSort(arr, l, lt-1); __quickSort(arr, gt, r); } }
false
427
6
501
6
497
6
501
6
617
12
false
false
false
false
false
true
57758_15
package note.util; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import note.vo.user; /**\ * * 使用JavaMail发送邮件 * */ public class Mail1 { public Mail1(user user) { try { // 获得属性,并生成Session对象 Properties props = new Properties(); Session sendsession; Transport transport; sendsession = Session.getInstance(props, null); // 向属性中写入SMTP服务器的地址 props.put("mail.smtp.host", "smtp.qq.com"); // 设置SMTP服务器需要权限认证 props.put("mail.smtp.auth", "true"); //MyAuthenticator myauth = new MyAuthenticator("[email protected]", "99081035c"); // 设置输出调试信息 sendsession.setDebug(true); // 根据Session生成Message对象 Message message = new MimeMessage(sendsession); // 设置发信人地址 message.setFrom(new InternetAddress("[email protected]")); // 设置收信人地址 message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); // 设置e-mail标题 message.setSubject("您好!请绑定你的账户--OnlineCourse!"); // 设置e-mail发送时间 message.setSentDate(new Date()); // 设置e-mail内容 message.setContent(user.getName()+":请经常访问本网站!" + " <br><a href='http://localhost:8086/OnlineCourse/EmailServlet1?email="+user.getEmail()+"&name="+user.getName()+"'>请点击绑定帐号</a>", "text/html;charset=UTF-8"); // 保存对于Email.的修改 message.saveChanges(); // 根据Session生成Transport对象 transport = sendsession.getTransport("smtp"); // 连接到SMTP服务器 transport.connect("smtp.qq.com", "1647088054", "doitmcanmjbqbffg");// !!!!!******注意修改************ // 发送e-mail transport.sendMessage(message, message.getAllRecipients()); // 关闭Transport连接 transport.close(); } catch (MessagingException me) { me.printStackTrace(); } } }
WANG1020/OnlineCourseSys
src/note/util/Mail1.java
640
// 连接到SMTP服务器
line_comment
zh-cn
package note.util; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import note.vo.user; /**\ * * 使用JavaMail发送邮件 * */ public class Mail1 { public Mail1(user user) { try { // 获得属性,并生成Session对象 Properties props = new Properties(); Session sendsession; Transport transport; sendsession = Session.getInstance(props, null); // 向属性中写入SMTP服务器的地址 props.put("mail.smtp.host", "smtp.qq.com"); // 设置SMTP服务器需要权限认证 props.put("mail.smtp.auth", "true"); //MyAuthenticator myauth = new MyAuthenticator("[email protected]", "99081035c"); // 设置输出调试信息 sendsession.setDebug(true); // 根据Session生成Message对象 Message message = new MimeMessage(sendsession); // 设置发信人地址 message.setFrom(new InternetAddress("[email protected]")); // 设置收信人地址 message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); // 设置e-mail标题 message.setSubject("您好!请绑定你的账户--OnlineCourse!"); // 设置e-mail发送时间 message.setSentDate(new Date()); // 设置e-mail内容 message.setContent(user.getName()+":请经常访问本网站!" + " <br><a href='http://localhost:8086/OnlineCourse/EmailServlet1?email="+user.getEmail()+"&name="+user.getName()+"'>请点击绑定帐号</a>", "text/html;charset=UTF-8"); // 保存对于Email.的修改 message.saveChanges(); // 根据Session生成Transport对象 transport = sendsession.getTransport("smtp"); // 连接 <SUF> transport.connect("smtp.qq.com", "1647088054", "doitmcanmjbqbffg");// !!!!!******注意修改************ // 发送e-mail transport.sendMessage(message, message.getAllRecipients()); // 关闭Transport连接 transport.close(); } catch (MessagingException me) { me.printStackTrace(); } } }
false
552
6
640
6
623
5
640
6
857
10
false
false
false
false
false
true
60839_2
//使用Scanner收集你的身高体重,并计算出你的BMI值是多少 // //BMI的计算公式是 体重(kg) / (身高*身高) // //比如邱阳波的体重是72kg, 身高是1.69,那么这位同学的BMI就是 //72 / (1.69*1.69) = ? // //然后通过条件判断BMI的范围,打印出是超重还是正常 import java.util.Scanner; public class lianxi { public static void main(String[] args){ System.out.println("请输入体重(kg):"); Scanner weight=new Scanner(System.in); int i=weight.nextInt(); System.out.println("请输入你的身高(m):"); Scanner height=new Scanner(System.in); float a=height.nextFloat(); double BMI=i/(a*a); System.out.println("你的BMI值:"+BMI); if(BMI<18.5) System.out.println("体重过轻"); else if(BMI>=18.5&&BMI<24) System.out.println("正常范围"); else if(BMI>=24&&BMI<27) System.out.println("体重过重"); else if(BMI>=27&&BMI<30) System.out.println("轻度肥胖"); else if (BMI>=30&&BMI<35) System.out.println("中度肥胖"); else if (BMI>=35) System.out.println("超级肥胖"); } }
WAnzhi0810/test
src/lianxi.java
410
//比如邱阳波的体重是72kg, 身高是1.69,那么这位同学的BMI就是
line_comment
zh-cn
//使用Scanner收集你的身高体重,并计算出你的BMI值是多少 // //BMI的计算公式是 体重(kg) / (身高*身高) // //比如 <SUF> //72 / (1.69*1.69) = ? // //然后通过条件判断BMI的范围,打印出是超重还是正常 import java.util.Scanner; public class lianxi { public static void main(String[] args){ System.out.println("请输入体重(kg):"); Scanner weight=new Scanner(System.in); int i=weight.nextInt(); System.out.println("请输入你的身高(m):"); Scanner height=new Scanner(System.in); float a=height.nextFloat(); double BMI=i/(a*a); System.out.println("你的BMI值:"+BMI); if(BMI<18.5) System.out.println("体重过轻"); else if(BMI>=18.5&&BMI<24) System.out.println("正常范围"); else if(BMI>=24&&BMI<27) System.out.println("体重过重"); else if(BMI>=27&&BMI<30) System.out.println("轻度肥胖"); else if (BMI>=30&&BMI<35) System.out.println("中度肥胖"); else if (BMI>=35) System.out.println("超级肥胖"); } }
false
324
27
410
32
386
26
410
32
488
36
false
false
false
false
false
true
20566_0
public class CustomExcepetion { public static void main(String[] args) { int age = 180; if(!(age >= 18 && age <= 120)) { throw new AgeException("年龄需要在 18~120 之间"); } System.out.println("你的年龄范围正确."); } } class AgeException extends RuntimeException { public AgeException(String message) {//构造器 super(message); } }
WCHLi666/WCHLi666
CustomExcepetion.java
114
//构造器
line_comment
zh-cn
public class CustomExcepetion { public static void main(String[] args) { int age = 180; if(!(age >= 18 && age <= 120)) { throw new AgeException("年龄需要在 18~120 之间"); } System.out.println("你的年龄范围正确."); } } class AgeException extends RuntimeException { public AgeException(String message) {//构造 <SUF> super(message); } }
false
102
3
114
3
121
3
114
3
139
4
false
false
false
false
false
true
15775_3
package com.tuling.jucdemo.threadactiveness; import lombok.extern.slf4j.Slf4j; /** * @author Fox * 活锁 */ @Slf4j public class LiveLockTest { /** * 定义一个勺子,ower 表示这个勺子的拥有者 */ static class Spoon { Diner owner; public Spoon(Diner diner) { this.owner = diner; } public String getOwnerName() { return owner.getName(); } public void setOwner(Diner diner) { this.owner = diner; } //表示正在用餐 public void use() { log.info( "{} 用这个勺子吃饭.",owner.getName()); } } /** * 定义一个晚餐类 */ static class Diner { private boolean isHungry; //用餐者的名字 private String name; public Diner(boolean isHungry, String name) { this.isHungry = isHungry; this.name = name; } //和某人吃饭 public void eatWith(Diner diner, Spoon sharedSpoon) { try { synchronized (sharedSpoon) { while (isHungry) { //当前用餐者和勺子拥有者不是同一个人,则进行等待 while (!sharedSpoon.getOwnerName().equals(name)) { sharedSpoon.wait(); } if (diner.isHungry()) { log.info( "{}:亲爱的我饿了,然后{}把勺子给了{}", diner.getName(),name,diner.getName()); sharedSpoon.setOwner(diner); //唤醒等待的线程 sharedSpoon.notifyAll(); } else { //用餐 sharedSpoon.use(); sharedSpoon.setOwner(diner); isHungry = false; } Thread.sleep(500); } } } catch (InterruptedException e) { log.info("{} is interrupted.",name); } } public boolean isHungry() { return isHungry; } public String getName() { return name; } } public static void main(String[] args) { final Diner husband = new Diner(true, "丈夫"); final Diner wife = new Diner(true, "妻子"); //最开始牛郎持有勺子 final Spoon sharedSpoon = new Spoon(husband); //织女和牛郎吃饭 Thread h = new Thread(()->wife.eatWith(husband, sharedSpoon)); h.start(); //牛郎和织女吃饭 Thread w = new Thread(()->husband.eatWith(wife, sharedSpoon)); w.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } h.interrupt(); w.interrupt(); } }
WMWxmtx/juc
src/main/java/com/tuling/jucdemo/threadactiveness/LiveLockTest.java
730
/** * 定义一个晚餐类 */
block_comment
zh-cn
package com.tuling.jucdemo.threadactiveness; import lombok.extern.slf4j.Slf4j; /** * @author Fox * 活锁 */ @Slf4j public class LiveLockTest { /** * 定义一个勺子,ower 表示这个勺子的拥有者 */ static class Spoon { Diner owner; public Spoon(Diner diner) { this.owner = diner; } public String getOwnerName() { return owner.getName(); } public void setOwner(Diner diner) { this.owner = diner; } //表示正在用餐 public void use() { log.info( "{} 用这个勺子吃饭.",owner.getName()); } } /** * 定义一 <SUF>*/ static class Diner { private boolean isHungry; //用餐者的名字 private String name; public Diner(boolean isHungry, String name) { this.isHungry = isHungry; this.name = name; } //和某人吃饭 public void eatWith(Diner diner, Spoon sharedSpoon) { try { synchronized (sharedSpoon) { while (isHungry) { //当前用餐者和勺子拥有者不是同一个人,则进行等待 while (!sharedSpoon.getOwnerName().equals(name)) { sharedSpoon.wait(); } if (diner.isHungry()) { log.info( "{}:亲爱的我饿了,然后{}把勺子给了{}", diner.getName(),name,diner.getName()); sharedSpoon.setOwner(diner); //唤醒等待的线程 sharedSpoon.notifyAll(); } else { //用餐 sharedSpoon.use(); sharedSpoon.setOwner(diner); isHungry = false; } Thread.sleep(500); } } } catch (InterruptedException e) { log.info("{} is interrupted.",name); } } public boolean isHungry() { return isHungry; } public String getName() { return name; } } public static void main(String[] args) { final Diner husband = new Diner(true, "丈夫"); final Diner wife = new Diner(true, "妻子"); //最开始牛郎持有勺子 final Spoon sharedSpoon = new Spoon(husband); //织女和牛郎吃饭 Thread h = new Thread(()->wife.eatWith(husband, sharedSpoon)); h.start(); //牛郎和织女吃饭 Thread w = new Thread(()->husband.eatWith(wife, sharedSpoon)); w.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } h.interrupt(); w.interrupt(); } }
false
628
12
730
13
713
11
730
13
955
19
false
false
false
false
false
true
36126_8
/** * Author: 王俊超 * Date: 2016-01-12 13:18 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * All Rights Reserved !!! */ public class SubMatrix { public int sumOfSubMatrix(int[][] mat, int n) { // 矩阵的行数 int rowCount = mat.length; // 矩阵的列数 int colCount = mat[0].length; // 部分和 int[] partialSum = new int[colCount]; // 最大值 int maxSum = Integer.MIN_VALUE; // rowStart限制开始处理的行 for (int rowStart = 0; rowStart < rowCount; rowStart++) { // 对部分知清零 clear(partialSum); // 下面对[rowStart,...,rowEnd]列表进行处理 for (int rowEnd = rowStart; rowEnd < rowCount; rowEnd++) { // 对所有的列进行处理 for (int col = 0; col < colCount; col++) { // partialSum[col]的值是mat[rowStart...rowEnd][col]行累加的值 partialSum[col] += mat[rowEnd][col]; } // 在此处partialSum[rowStart,...,rowEnd]数组就是 // mat[rowStart,...,rowEnd][0,...,colCount-1]就对列的累加 // 此处的tempMaxSum就是mat[rowStart,...,rowEnd][x,...,y]的某个值 // 其中0<=x<=y<=(colCount-1) int tempMaxSum = maxSubArray(partialSum); if (tempMaxSum > maxSum) { maxSum = tempMaxSum; } } } return maxSum; } /** * 将数组清零 * * @param a */ public void clear(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = 0; } } /** * 求数组的最大的子数组的和 * * @param a * @return */ public int maxSubArray(int[] a) { int max = Integer.MIN_VALUE; int v = 0; for (int i : a) { v += i; if (v > max) { max = v; } if (v < 0) { v = 0; } } return max; } }
Wang-Jun-Chao/Cracking-the-Coding-Interview
1812-动态规划-最大和子矩阵/src/SubMatrix.java
607
// 对所有的列进行处理
line_comment
zh-cn
/** * Author: 王俊超 * Date: 2016-01-12 13:18 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * All Rights Reserved !!! */ public class SubMatrix { public int sumOfSubMatrix(int[][] mat, int n) { // 矩阵的行数 int rowCount = mat.length; // 矩阵的列数 int colCount = mat[0].length; // 部分和 int[] partialSum = new int[colCount]; // 最大值 int maxSum = Integer.MIN_VALUE; // rowStart限制开始处理的行 for (int rowStart = 0; rowStart < rowCount; rowStart++) { // 对部分知清零 clear(partialSum); // 下面对[rowStart,...,rowEnd]列表进行处理 for (int rowEnd = rowStart; rowEnd < rowCount; rowEnd++) { // 对所 <SUF> for (int col = 0; col < colCount; col++) { // partialSum[col]的值是mat[rowStart...rowEnd][col]行累加的值 partialSum[col] += mat[rowEnd][col]; } // 在此处partialSum[rowStart,...,rowEnd]数组就是 // mat[rowStart,...,rowEnd][0,...,colCount-1]就对列的累加 // 此处的tempMaxSum就是mat[rowStart,...,rowEnd][x,...,y]的某个值 // 其中0<=x<=y<=(colCount-1) int tempMaxSum = maxSubArray(partialSum); if (tempMaxSum > maxSum) { maxSum = tempMaxSum; } } } return maxSum; } /** * 将数组清零 * * @param a */ public void clear(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = 0; } } /** * 求数组的最大的子数组的和 * * @param a * @return */ public int maxSubArray(int[] a) { int max = Integer.MIN_VALUE; int v = 0; for (int i : a) { v += i; if (v > max) { max = v; } if (v < 0) { v = 0; } } return max; } }
false
598
6
607
6
643
6
607
6
731
11
false
false
false
false
false
true
48056_9
import java.util.Scanner; /** * Author: 王俊超 * Time: 2016-05-14 10:36 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * Declaration: All Rights Reserved !!! */ public class Main { // 某个点可以移动的四个方向,两个两个一组 private final static int[] D = {-1, 0, 0, 1, 1, 0, 0, -1}; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { int row = scanner.nextInt(); int col = scanner.nextInt(); int[][] matrix = new int[row][col]; for (int i = 0; i < row; i++) { matrix[i] = new int[col]; for (int j = 0; j < col; j++) { matrix[i][j] = scanner.nextInt(); } } System.out.println(maxLength(matrix)); } scanner.close(); } /** * 求最大的下滑长度 * * @param matrix 区域海拔 * @return 最大的下滑长度 */ private static int maxLength(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; // 创建记录高度的二维数组,初始值为0 int[][] length = new int[row][col]; for (int i = 0; i < row; i++) { length[i] = new int[col]; } // 对每一个点进行深度优先遍历 for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { dfs(i, j, matrix, length); } } // 找最大值 int max = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (max < length[i][j]) { max = length[i][j]; } } } return max; } /** * 深度优先遍历 * * @param i 行 * @param j 列 * @param matrix 区域海拔 * @param length 记录每个点可以滑动的最长距离 */ private static void dfs(int i, int j, int[][] matrix, int[][] length) { int row = matrix.length; int col = matrix[0].length; // 如果坐标不合法,或者已经计算过了就返回 if (i < 0 || i >= row || j < 0 || j >= col || length[i][j] > 0) { return; } int max = 0; for (int k = 0; k < D.length; k += 2) { int x = i + D[k]; int y = j + D[k + 1]; // 处理(x, y)点的四个方向 if (x >= 0 && x < row && y >= 0 && y < col && matrix[i][j] > matrix[x][y]) { dfs(x, y, matrix, length); // 记录最大值 if (length[x][y] > max) { max = length[x][y]; } } } // 记录当前点可以滑动的最长距离,1是当前点的长度 length[i][j] = 1 + max; } }
Wang-Jun-Chao/ProgrammingMarathon
030-滑雪/src/Main.java
884
// 处理(x, y)点的四个方向
line_comment
zh-cn
import java.util.Scanner; /** * Author: 王俊超 * Time: 2016-05-14 10:36 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * Declaration: All Rights Reserved !!! */ public class Main { // 某个点可以移动的四个方向,两个两个一组 private final static int[] D = {-1, 0, 0, 1, 1, 0, 0, -1}; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { int row = scanner.nextInt(); int col = scanner.nextInt(); int[][] matrix = new int[row][col]; for (int i = 0; i < row; i++) { matrix[i] = new int[col]; for (int j = 0; j < col; j++) { matrix[i][j] = scanner.nextInt(); } } System.out.println(maxLength(matrix)); } scanner.close(); } /** * 求最大的下滑长度 * * @param matrix 区域海拔 * @return 最大的下滑长度 */ private static int maxLength(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; // 创建记录高度的二维数组,初始值为0 int[][] length = new int[row][col]; for (int i = 0; i < row; i++) { length[i] = new int[col]; } // 对每一个点进行深度优先遍历 for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { dfs(i, j, matrix, length); } } // 找最大值 int max = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (max < length[i][j]) { max = length[i][j]; } } } return max; } /** * 深度优先遍历 * * @param i 行 * @param j 列 * @param matrix 区域海拔 * @param length 记录每个点可以滑动的最长距离 */ private static void dfs(int i, int j, int[][] matrix, int[][] length) { int row = matrix.length; int col = matrix[0].length; // 如果坐标不合法,或者已经计算过了就返回 if (i < 0 || i >= row || j < 0 || j >= col || length[i][j] > 0) { return; } int max = 0; for (int k = 0; k < D.length; k += 2) { int x = i + D[k]; int y = j + D[k + 1]; // 处理 <SUF> if (x >= 0 && x < row && y >= 0 && y < col && matrix[i][j] > matrix[x][y]) { dfs(x, y, matrix, length); // 记录最大值 if (length[x][y] > max) { max = length[x][y]; } } } // 记录当前点可以滑动的最长距离,1是当前点的长度 length[i][j] = 1 + max; } }
false
838
12
884
13
931
10
884
13
1,102
15
false
false
false
false
false
true
53045_6
import java.util.LinkedList; import java.util.List; import java.util.Scanner; /** * Author: 王俊超 * Date: 2016-05-05 08:35 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * Declaration: All Rights Reserved !!! */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { String real = scanner.next(); // System.out.println(convert(real)); // System.out.println(convert2(real)); System.out.println(convert3(real)); } scanner.close(); } /** * 方法一 * 真分数分解为埃及分数 * 解题思路 * <p> * 【贪心算法】 * 设a、b为互质正整数,a < b 分数a/b 可用以下的步骤分解成若干个单位分数之和: * 步骤一: 用b 除以a,得商数q1 及余数r1。(r1=b - a*q1) * 步骤二:把a/b 记作:a/b=1/(q1+1)+(a-r)/b(q1+1) * 步骤三:重复步骤2,直到分解完毕 * 3/7=1/3+2/21=1/3+1/11+1/231 * 13/23=1/2+3/46=1/2+1/16+1/368 * 以上其实是数学家斐波那契提出的一种求解埃及分数的贪心算法,准确的算法表述应该是这样的: * 设某个真分数的分子为a,分母为b; * 把b除以a的商部分加1后的值作为埃及分数的某一个分母c; * 将a乘以c再减去b,作为新的a; * 将b乘以c,得到新的b; * 如果a大于1且能整除b,则最后一个分母为b/a;算法结束; * 或者,如果a等于1,则,最后一个分母为b;算法结束; * 否则重复上面的步骤。 * 备注:事实上,后面判断a是否大于1和a是否等于1的两个判断可以合在一起,及判断b%a是否等于0,最后一个分母为b/a,显然是正确的。 * * @param real 真分数 * @return 埃及分数 */ private static String convert(String real) { String[] parts = real.split("/"); // 分子 int a = Integer.parseInt(parts[0]); // 分母 int b = Integer.parseInt(parts[1]); StringBuilder builder = new StringBuilder(64); // System.out.print("[1]" + a + "/" + b + ": "); while (b % a != 0) { // 求商 int q = b / a; // 余数 int r = b % a; builder.append(1).append('/').append(q + 1).append('+'); a = a - r; b = b * (q + 1); } builder.append(1).append('/').append(b / a); return builder.toString(); } /** * 方法二 * 真分数分解为埃及分数 * <p> * 若真分数的分子a能整除分母b,则真分数经过化简就可以得到埃及分数, * 若真分数的分子不能整除分母,则可以从原来的分数中分解出一个分母为b/a+1的埃及分数。 * 用这种方法将剩余部分反复分解,最后可得到结果。 * * @param real 真分数 * @return 埃及分数 */ private static String convert2(String real) { String[] parts = real.split("/"); // 分子 int a = Integer.parseInt(parts[0]); // 分母 int b = Integer.parseInt(parts[1]); StringBuilder builder = new StringBuilder(64); // System.out.print("[2]" + a + "/" + b + ": "); while (b % a != 0) { // 分解出一个分母为b/a+1的埃及分数 int c = b / a + 1; a = a * c - b; b = b * c; builder.append(1).append('/').append(c).append('+'); } builder.append(1).append('/').append(b / a); return builder.toString(); } /** * 方法三 * 真分数分解为埃及分数 * * @param real 真分数 * @return 埃及分数 */ private static String convert3(String real) { String[] parts = real.split("/"); // 分子 int a = Integer.parseInt(parts[0]); // 分母 int b = Integer.parseInt(parts[1]); StringBuilder builder = new StringBuilder(64); int c; while (a != 1) { if (b % (a - 1) == 0) { builder.append("1/").append(b / (a - 1)).append('+'); a = 1; } else { c = b / a + 1; builder.append("1/").append(c).append('+'); a = a * c - b; b = c * b; if (b % a == 0) { b = b / a; a = 1; } } } builder.append("1/").append(b); return builder.toString(); } }
Wang-Jun-Chao/hawei-online-test
101-将真分数分解为埃及分数/src/Main.java
1,465
/** * 方法二 * 真分数分解为埃及分数 * <p> * 若真分数的分子a能整除分母b,则真分数经过化简就可以得到埃及分数, * 若真分数的分子不能整除分母,则可以从原来的分数中分解出一个分母为b/a+1的埃及分数。 * 用这种方法将剩余部分反复分解,最后可得到结果。 * * @param real 真分数 * @return 埃及分数 */
block_comment
zh-cn
import java.util.LinkedList; import java.util.List; import java.util.Scanner; /** * Author: 王俊超 * Date: 2016-05-05 08:35 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * Declaration: All Rights Reserved !!! */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { String real = scanner.next(); // System.out.println(convert(real)); // System.out.println(convert2(real)); System.out.println(convert3(real)); } scanner.close(); } /** * 方法一 * 真分数分解为埃及分数 * 解题思路 * <p> * 【贪心算法】 * 设a、b为互质正整数,a < b 分数a/b 可用以下的步骤分解成若干个单位分数之和: * 步骤一: 用b 除以a,得商数q1 及余数r1。(r1=b - a*q1) * 步骤二:把a/b 记作:a/b=1/(q1+1)+(a-r)/b(q1+1) * 步骤三:重复步骤2,直到分解完毕 * 3/7=1/3+2/21=1/3+1/11+1/231 * 13/23=1/2+3/46=1/2+1/16+1/368 * 以上其实是数学家斐波那契提出的一种求解埃及分数的贪心算法,准确的算法表述应该是这样的: * 设某个真分数的分子为a,分母为b; * 把b除以a的商部分加1后的值作为埃及分数的某一个分母c; * 将a乘以c再减去b,作为新的a; * 将b乘以c,得到新的b; * 如果a大于1且能整除b,则最后一个分母为b/a;算法结束; * 或者,如果a等于1,则,最后一个分母为b;算法结束; * 否则重复上面的步骤。 * 备注:事实上,后面判断a是否大于1和a是否等于1的两个判断可以合在一起,及判断b%a是否等于0,最后一个分母为b/a,显然是正确的。 * * @param real 真分数 * @return 埃及分数 */ private static String convert(String real) { String[] parts = real.split("/"); // 分子 int a = Integer.parseInt(parts[0]); // 分母 int b = Integer.parseInt(parts[1]); StringBuilder builder = new StringBuilder(64); // System.out.print("[1]" + a + "/" + b + ": "); while (b % a != 0) { // 求商 int q = b / a; // 余数 int r = b % a; builder.append(1).append('/').append(q + 1).append('+'); a = a - r; b = b * (q + 1); } builder.append(1).append('/').append(b / a); return builder.toString(); } /** * 方法二 <SUF>*/ private static String convert2(String real) { String[] parts = real.split("/"); // 分子 int a = Integer.parseInt(parts[0]); // 分母 int b = Integer.parseInt(parts[1]); StringBuilder builder = new StringBuilder(64); // System.out.print("[2]" + a + "/" + b + ": "); while (b % a != 0) { // 分解出一个分母为b/a+1的埃及分数 int c = b / a + 1; a = a * c - b; b = b * c; builder.append(1).append('/').append(c).append('+'); } builder.append(1).append('/').append(b / a); return builder.toString(); } /** * 方法三 * 真分数分解为埃及分数 * * @param real 真分数 * @return 埃及分数 */ private static String convert3(String real) { String[] parts = real.split("/"); // 分子 int a = Integer.parseInt(parts[0]); // 分母 int b = Integer.parseInt(parts[1]); StringBuilder builder = new StringBuilder(64); int c; while (a != 1) { if (b % (a - 1) == 0) { builder.append("1/").append(b / (a - 1)).append('+'); a = 1; } else { c = b / a + 1; builder.append("1/").append(c).append('+'); a = a * c - b; b = c * b; if (b % a == 0) { b = b / a; a = 1; } } } builder.append("1/").append(b); return builder.toString(); } }
false
1,322
118
1,465
144
1,462
121
1,465
144
1,812
183
false
false
false
false
false
true
33125_7
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author: wangjunchao(王俊超) * @time: 2018-09-28 15:29 **/ public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } boolean[] used = new boolean[nums.length]; List<Integer> list = new ArrayList<>(); Arrays.sort(nums); permuteUnique(nums, used, list, res); return res; } /** * 时间复杂度:n! * * @param nums * @param used * @param list * @param res */ private void permuteUnique(int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> res) { if (list.size() == nums.length) { res.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { // 第i个数值已经被使用过 if (used[i]) { continue; } // 第i个字符与前一个字符相等,并且第i-1个字符没有使用,说明此次不应该交换 if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) { continue; } // 标记第i个字符已经被使用 used[i] = true; // 添加到临时结果中 list.add(nums[i]); // 下一次处理 permuteUnique(nums, used, list, res); // 现场还原 used[i] = false; list.remove(list.size() - 1); } } }
Wang-Jun-Chao/leetcode
[0047][Permutations II]/src/Solution.java
459
// 现场还原
line_comment
zh-cn
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author: wangjunchao(王俊超) * @time: 2018-09-28 15:29 **/ public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } boolean[] used = new boolean[nums.length]; List<Integer> list = new ArrayList<>(); Arrays.sort(nums); permuteUnique(nums, used, list, res); return res; } /** * 时间复杂度:n! * * @param nums * @param used * @param list * @param res */ private void permuteUnique(int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> res) { if (list.size() == nums.length) { res.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { // 第i个数值已经被使用过 if (used[i]) { continue; } // 第i个字符与前一个字符相等,并且第i-1个字符没有使用,说明此次不应该交换 if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) { continue; } // 标记第i个字符已经被使用 used[i] = true; // 添加到临时结果中 list.add(nums[i]); // 下一次处理 permuteUnique(nums, used, list, res); // 现场 <SUF> used[i] = false; list.remove(list.size() - 1); } } }
false
411
6
459
6
485
3
459
6
565
6
false
false
false
false
false
true
22723_3
package com.cece.community.entity; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.Date; // shard 分片 @Document(indexName = "discusspost", shards = 6, replicas = 3) public class DiscussPost { @Id private int id; @Field(type = FieldType.Integer) private int userId; // analyzer="ik_max_word":存储的解析器,把它分词,使用最大的分词器,分的最细 // searchAnalyzer = "ik_smart": 搜索的时候使用的分词器,非常聪明 @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart") private String title; @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart") private String content; //0-普通帖子, 1-置顶 @Field(type = FieldType.Integer) private int type; // 1表示精华, 2表示拉黑 @Field(type = FieldType.Integer) private int status; @Field(type = FieldType.Date) private Date createTime; @Field(type = FieldType.Integer) private int commentCount; @Field(type = FieldType.Double) private double score; 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 String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "DiscussPost{" + "id=" + id + ", userId=" + userId + ", title='" + title + '\'' + ", content='" + content + '\'' + ", type=" + type + ", status=" + status + ", createTime=" + createTime + ", commentCount=" + commentCount + ", score=" + score + '}'; } }
WangCece-real/nk_community_project
src/main/java/com/cece/community/entity/DiscussPost.java
737
//0-普通帖子, 1-置顶
line_comment
zh-cn
package com.cece.community.entity; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.Date; // shard 分片 @Document(indexName = "discusspost", shards = 6, replicas = 3) public class DiscussPost { @Id private int id; @Field(type = FieldType.Integer) private int userId; // analyzer="ik_max_word":存储的解析器,把它分词,使用最大的分词器,分的最细 // searchAnalyzer = "ik_smart": 搜索的时候使用的分词器,非常聪明 @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart") private String title; @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart") private String content; //0- <SUF> @Field(type = FieldType.Integer) private int type; // 1表示精华, 2表示拉黑 @Field(type = FieldType.Integer) private int status; @Field(type = FieldType.Date) private Date createTime; @Field(type = FieldType.Integer) private int commentCount; @Field(type = FieldType.Double) private double score; 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 String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "DiscussPost{" + "id=" + id + ", userId=" + userId + ", title='" + title + '\'' + ", content='" + content + '\'' + ", type=" + type + ", status=" + status + ", createTime=" + createTime + ", commentCount=" + commentCount + ", score=" + score + '}'; } }
false
649
11
737
13
812
11
737
13
956
19
false
false
false
false
false
true
35697_14
package com.github.wangji92.arthas.plugin.utils; import com.github.wangji92.arthas.plugin.constants.ArthasCommandConstants; import com.github.wangji92.arthas.plugin.setting.AppSettingsState; import com.google.common.base.Splitter; import com.intellij.notification.NotificationType; import com.intellij.openapi.project.Project; import java.util.List; /** * spring 静态的context 工具类 * * @author 汪小哥 * @date 13-08-2020 */ public class SpringStaticContextUtils { /** * 获取构造Bean的表达式 */ private static final String SPRING_CONTEXT_GET_BEAN = "%s,#springContext.getBean(\"%s\")"; /** * 构造targetBean */ private static final String SPRING_CONTEXT_TARGET_BEAN = "%s,#targetBean=#springContext.getBean(\"%s\")"; /** * 获取静态Spring context的前缀 * //这个是配置的 @com.wj.study.demo.generator.ApplicationContextProvider@context 这个是配置的 * //例子 #springContext=@com.wj.study.demo.generator.ApplicationContextProvider@context,#springContext.getBean("userService") * <p> 构造一个如下的例子 * // #springContext=填充,#springContext.getBean("%s") * * @return */ public static String getStaticSpringContextGetBeanPrefix(Project project, String beanName) { String springStaticContextConfig = getStaticSpringContextPrefix(project); return String.format(SPRING_CONTEXT_GET_BEAN, springStaticContextConfig, beanName); } /** * #springContext=填充,#targetBean=#springContext.getBean("%s") * * @param beanName * @return */ public static String getStaticSpringContextGetBeanVariable(Project project, String beanName) { String springStaticContextConfig = getStaticSpringContextPrefix(project); return String.format(SPRING_CONTEXT_TARGET_BEAN, springStaticContextConfig, beanName); } /** * 获取静态Spring context的前缀 #springContext=@applicationContextProvider@context * * @return */ public static String getStaticSpringContextPrefix(Project project) { String springStaticContextConfig = getSpringStaticContextConfig(project); //#springContext=填充 return "" + ArthasCommandConstants.SPRING_CONTEXT_PARAM + "=" + springStaticContextConfig; } public static String getStaticSpringContextClassName(Project project) { String springStaticContextConfig = getSpringStaticContextConfig(project); //#springContext=填充,#springContext.getBean("%s") // 获取class的classloader List<String> springContextCLassLists = Splitter.on('@').omitEmptyStrings().splitToList(springStaticContextConfig); if (springContextCLassLists.isEmpty()) { throw new IllegalArgumentException("Static Spring context requires manual configuration"); } //@com.wj.study.demo.generator.ApplicationContextProvider@context 配置的是这个玩意 return springContextCLassLists.get(0); } /** * 是否配置 static spring context 上下文 * * @param project * @return */ public static boolean booleanConfigStaticSpringContext(Project project) { try { getStaticSpringContextClassName(project); return true; } catch (Exception e) { return false; } } /** * 是否配置了 static spring context * * @param project * @return */ public static boolean booleanConfigStaticSpringContextFalseOpenConfig(Project project) { boolean staticSpringContextConfig = SpringStaticContextUtils.booleanConfigStaticSpringContext(project); if (!staticSpringContextConfig) { NotifyUtils.notifyMessage(project, "Static Spring context requires manual configuration <a href=\"https://www.yuque.com/arthas-idea-plugin/help/ugrc8n\">arthas idea setting</a>", NotificationType.ERROR); } return staticSpringContextConfig; } /** * 获取spring static context的配置 */ private static String getSpringStaticContextConfig(Project project) { // 这里换个获取配置的方式 AppSettingsState instance = AppSettingsState.getInstance(project); String springContextValue = instance.staticSpringContextOgnl; if (StringUtils.isBlank(springContextValue) || ArthasCommandConstants.DEFAULT_SPRING_CONTEXT_SETTING.equals(springContextValue)) { throw new IllegalArgumentException("Static Spring context requires manual configuration"); } if (springContextValue.endsWith(",")) { springContextValue = springContextValue.substring(0, springContextValue.length() - 2); } return springContextValue; } }
WangJi92/arthas-idea-plugin
src/com/github/wangji92/arthas/plugin/utils/SpringStaticContextUtils.java
1,093
// 这里换个获取配置的方式
line_comment
zh-cn
package com.github.wangji92.arthas.plugin.utils; import com.github.wangji92.arthas.plugin.constants.ArthasCommandConstants; import com.github.wangji92.arthas.plugin.setting.AppSettingsState; import com.google.common.base.Splitter; import com.intellij.notification.NotificationType; import com.intellij.openapi.project.Project; import java.util.List; /** * spring 静态的context 工具类 * * @author 汪小哥 * @date 13-08-2020 */ public class SpringStaticContextUtils { /** * 获取构造Bean的表达式 */ private static final String SPRING_CONTEXT_GET_BEAN = "%s,#springContext.getBean(\"%s\")"; /** * 构造targetBean */ private static final String SPRING_CONTEXT_TARGET_BEAN = "%s,#targetBean=#springContext.getBean(\"%s\")"; /** * 获取静态Spring context的前缀 * //这个是配置的 @com.wj.study.demo.generator.ApplicationContextProvider@context 这个是配置的 * //例子 #springContext=@com.wj.study.demo.generator.ApplicationContextProvider@context,#springContext.getBean("userService") * <p> 构造一个如下的例子 * // #springContext=填充,#springContext.getBean("%s") * * @return */ public static String getStaticSpringContextGetBeanPrefix(Project project, String beanName) { String springStaticContextConfig = getStaticSpringContextPrefix(project); return String.format(SPRING_CONTEXT_GET_BEAN, springStaticContextConfig, beanName); } /** * #springContext=填充,#targetBean=#springContext.getBean("%s") * * @param beanName * @return */ public static String getStaticSpringContextGetBeanVariable(Project project, String beanName) { String springStaticContextConfig = getStaticSpringContextPrefix(project); return String.format(SPRING_CONTEXT_TARGET_BEAN, springStaticContextConfig, beanName); } /** * 获取静态Spring context的前缀 #springContext=@applicationContextProvider@context * * @return */ public static String getStaticSpringContextPrefix(Project project) { String springStaticContextConfig = getSpringStaticContextConfig(project); //#springContext=填充 return "" + ArthasCommandConstants.SPRING_CONTEXT_PARAM + "=" + springStaticContextConfig; } public static String getStaticSpringContextClassName(Project project) { String springStaticContextConfig = getSpringStaticContextConfig(project); //#springContext=填充,#springContext.getBean("%s") // 获取class的classloader List<String> springContextCLassLists = Splitter.on('@').omitEmptyStrings().splitToList(springStaticContextConfig); if (springContextCLassLists.isEmpty()) { throw new IllegalArgumentException("Static Spring context requires manual configuration"); } //@com.wj.study.demo.generator.ApplicationContextProvider@context 配置的是这个玩意 return springContextCLassLists.get(0); } /** * 是否配置 static spring context 上下文 * * @param project * @return */ public static boolean booleanConfigStaticSpringContext(Project project) { try { getStaticSpringContextClassName(project); return true; } catch (Exception e) { return false; } } /** * 是否配置了 static spring context * * @param project * @return */ public static boolean booleanConfigStaticSpringContextFalseOpenConfig(Project project) { boolean staticSpringContextConfig = SpringStaticContextUtils.booleanConfigStaticSpringContext(project); if (!staticSpringContextConfig) { NotifyUtils.notifyMessage(project, "Static Spring context requires manual configuration <a href=\"https://www.yuque.com/arthas-idea-plugin/help/ugrc8n\">arthas idea setting</a>", NotificationType.ERROR); } return staticSpringContextConfig; } /** * 获取spring static context的配置 */ private static String getSpringStaticContextConfig(Project project) { // 这里 <SUF> AppSettingsState instance = AppSettingsState.getInstance(project); String springContextValue = instance.staticSpringContextOgnl; if (StringUtils.isBlank(springContextValue) || ArthasCommandConstants.DEFAULT_SPRING_CONTEXT_SETTING.equals(springContextValue)) { throw new IllegalArgumentException("Static Spring context requires manual configuration"); } if (springContextValue.endsWith(",")) { springContextValue = springContextValue.substring(0, springContextValue.length() - 2); } return springContextValue; } }
false
1,016
8
1,093
8
1,166
8
1,093
8
1,355
13
false
false
false
false
false
true
60130_1
package com.top; public class PoiNode { // poi index public PoiNode[] next; public PoiNode[] before; // 各类条件,比如: // 第一层为4-1号的空房 // 第二层为4-2号的空房 // 第三层为有厕所 // 第四层为有窗户 public PoiNode[] conditionsNext; private int poiid; private int level; public PoiNode(int poiid, int level) { this.poiid = poiid; this.level = level; // 0 is the base level this.next = new PoiNode[level+1]; this.before = null; } public Integer getPoiid() { return this.poiid; } public Integer getLevel() { return this.level; } }
Wangxiaoman/MyProject
src/main/java/com/top/PoiNode.java
207
// 各类条件,比如:
line_comment
zh-cn
package com.top; public class PoiNode { // poi index public PoiNode[] next; public PoiNode[] before; // 各类 <SUF> // 第一层为4-1号的空房 // 第二层为4-2号的空房 // 第三层为有厕所 // 第四层为有窗户 public PoiNode[] conditionsNext; private int poiid; private int level; public PoiNode(int poiid, int level) { this.poiid = poiid; this.level = level; // 0 is the base level this.next = new PoiNode[level+1]; this.before = null; } public Integer getPoiid() { return this.poiid; } public Integer getLevel() { return this.level; } }
false
195
8
207
8
220
7
207
8
261
12
false
false
false
false
false
true
13945_3
/* * Copyright 2013-2018 Lilinfeng. * * 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 com.ljf.netty.bio; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * @author lilinfeng * @version 1.0 * @date 2014年2月14日 */ public class TimeServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { int port = 8080; if (args != null && args.length > 0) { try { port = Integer.valueOf(args[0]); } catch (NumberFormatException e) { // 采用默认值 } } ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("The time server is start in port : " + port); Socket socket = null; while (true) { socket = server.accept(); System.out.println("听说程序阻塞在这里。。。。。。。。"); new Thread(new TimeServerHandler(socket)).start(); } } finally { if (server != null) { System.out.println("The time server close"); server.close(); server = null; } } } }
Watson-ljf/netty-book2-ljf
src/main/java/com/ljf/netty/bio/TimeServer.java
451
// 采用默认值
line_comment
zh-cn
/* * Copyright 2013-2018 Lilinfeng. * * 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 com.ljf.netty.bio; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * @author lilinfeng * @version 1.0 * @date 2014年2月14日 */ public class TimeServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { int port = 8080; if (args != null && args.length > 0) { try { port = Integer.valueOf(args[0]); } catch (NumberFormatException e) { // 采用 <SUF> } } ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("The time server is start in port : " + port); Socket socket = null; while (true) { socket = server.accept(); System.out.println("听说程序阻塞在这里。。。。。。。。"); new Thread(new TimeServerHandler(socket)).start(); } } finally { if (server != null) { System.out.println("The time server close"); server.close(); server = null; } } } }
false
403
5
451
5
474
5
451
5
530
9
false
false
false
false
false
true
62527_4
package cn.wecuit.robot.plugins.msg; import cn.wecuit.backen.utils.NewsUtil; import cn.wecuit.robot.provider.NewsProvider; import lombok.Getter; import net.mamoe.mirai.message.data.LightApp; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author jiyec * @Date 2021/5/19 10:48 * @Version 1.0 **/ public class NewsPlugin extends MessagePluginImpl { private static final List<String> enabledList = new ArrayList<>(); private static final Map<String, Object> pluginData = new HashMap<String, Object>(){{ put("enabledList", enabledList); }}; // 二级指令 @Getter private final Map<String, String> subCmdList = new HashMap<String, String>(){{ put("开启推送", "enablePush"); put("关闭推送", "disablePush"); put("推送测试", "pushTest"); put("添加推送目标", "addPushTarget"); put("查询", "query"); }}; // 需要注册为一级指令的 指令 @Getter private final Map<String, String> registerAsFirstCmd = new HashMap<String, String>(){{ }}; // 本插件一级指令 @Override public String getMainCmd() { return "新闻系统"; } @Override public @NotNull String getHelp() { return "Admin:\n开启/关闭推送 -- 开启/关闭对应群聊的新闻推送功能\n推送测试 -- 在当前群进行一次推送测试\n添加推送目标 群号 -- 添加指定群号到推送列表\n\nUser:\n查询 n -- 查询n天之内的新闻"; } public boolean enablePush(){ long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); String fromId = Long.toString(event.getSubject().getId()); boolean newsNotice = enabledList.contains(fromId); if(!newsNotice) { event.getSubject().sendMessage("已为阁下开启该功能"); enabledList.add(fromId); updatePluginData(); }else{ event.getSubject().sendMessage("已经是开启状态啦~"); } return true; } public boolean disablePush(){ long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); String fromId = Long.toString(event.getSubject().getId()); boolean newsNotice = enabledList.contains(fromId); if(newsNotice) { event.getSubject().sendMessage("已为阁下关闭该功能"); enabledList.remove(fromId); updatePluginData(); }else{ event.getSubject().sendMessage("已经是关闭状态啦~"); } return true; } public boolean addPushTarget(){ long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); if(cmds.size() != 1){ event.getSubject().sendMessage("阁下的指令格式好像不太对呢(・∀・(・∀・(・∀・*)"); return true; } String targetId = cmds.get(0); boolean newsNotice = enabledList.contains(targetId); if(!newsNotice){ event.getSubject().sendMessage("已为阁下添加目标:" + targetId); enabledList.add(targetId); updatePluginData(); } return true; } // 推送测试 public boolean pushTest() throws IOException { long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); String subjectId = Long.toString(event.getSubject().getId()); NewsUtil.newsNotice(new ArrayList<String>(){{add(subjectId);}}); return true; } public boolean query(){ String temp = System.getProperty("java.io.tmpdir") + "/WeCuit"; String cachePath = temp + "/cache"; String listPath = cachePath + "/news/list"; try{ int dayRange = 1; if(cmds.size() > 0) dayRange = Integer.parseInt(cmds.get(0)); List<Map<String, String>> todayNews = NewsUtil.getLatestNews(listPath, dayRange); if(todayNews.size() == 0) { event.getSubject().sendMessage("没有" + dayRange + "天之内的新闻"); return true; } todayNews.forEach(news->{ try { event.getSubject().sendMessage(new LightApp(NewsProvider.genLightJson(news))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }); event.getSubject().sendMessage("以上是" + dayRange + "天之内的新闻"); }catch (Exception e){ e.printStackTrace(); } return true; } public static boolean checkAdmin(Long id){ return id == 1690127128L; } public void updatePluginData(){ updatePluginData(pluginData); } public static List<String> getEnabledList() { return enabledList; } // 初始化插件数据[从外部到内部] public void initPluginData(Map<String, Object> config){ // pluginData.clear(); // 清空 enabledList.addAll((List<String>)config.get("enabledList")); // 置入 } @Override public List<String> getGlobalCmd() { return null; } }
WeCuit/WeCuit-Backen-JAVA
src/main/java/cn/wecuit/robot/plugins/msg/NewsPlugin.java
1,377
// 推送测试
line_comment
zh-cn
package cn.wecuit.robot.plugins.msg; import cn.wecuit.backen.utils.NewsUtil; import cn.wecuit.robot.provider.NewsProvider; import lombok.Getter; import net.mamoe.mirai.message.data.LightApp; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author jiyec * @Date 2021/5/19 10:48 * @Version 1.0 **/ public class NewsPlugin extends MessagePluginImpl { private static final List<String> enabledList = new ArrayList<>(); private static final Map<String, Object> pluginData = new HashMap<String, Object>(){{ put("enabledList", enabledList); }}; // 二级指令 @Getter private final Map<String, String> subCmdList = new HashMap<String, String>(){{ put("开启推送", "enablePush"); put("关闭推送", "disablePush"); put("推送测试", "pushTest"); put("添加推送目标", "addPushTarget"); put("查询", "query"); }}; // 需要注册为一级指令的 指令 @Getter private final Map<String, String> registerAsFirstCmd = new HashMap<String, String>(){{ }}; // 本插件一级指令 @Override public String getMainCmd() { return "新闻系统"; } @Override public @NotNull String getHelp() { return "Admin:\n开启/关闭推送 -- 开启/关闭对应群聊的新闻推送功能\n推送测试 -- 在当前群进行一次推送测试\n添加推送目标 群号 -- 添加指定群号到推送列表\n\nUser:\n查询 n -- 查询n天之内的新闻"; } public boolean enablePush(){ long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); String fromId = Long.toString(event.getSubject().getId()); boolean newsNotice = enabledList.contains(fromId); if(!newsNotice) { event.getSubject().sendMessage("已为阁下开启该功能"); enabledList.add(fromId); updatePluginData(); }else{ event.getSubject().sendMessage("已经是开启状态啦~"); } return true; } public boolean disablePush(){ long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); String fromId = Long.toString(event.getSubject().getId()); boolean newsNotice = enabledList.contains(fromId); if(newsNotice) { event.getSubject().sendMessage("已为阁下关闭该功能"); enabledList.remove(fromId); updatePluginData(); }else{ event.getSubject().sendMessage("已经是关闭状态啦~"); } return true; } public boolean addPushTarget(){ long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); if(cmds.size() != 1){ event.getSubject().sendMessage("阁下的指令格式好像不太对呢(・∀・(・∀・(・∀・*)"); return true; } String targetId = cmds.get(0); boolean newsNotice = enabledList.contains(targetId); if(!newsNotice){ event.getSubject().sendMessage("已为阁下添加目标:" + targetId); enabledList.add(targetId); updatePluginData(); } return true; } // 推送 <SUF> public boolean pushTest() throws IOException { long senderId = event.getSender().getId(); if(!checkAdmin(senderId)) event.getSubject().sendMessage("没有权限"); String subjectId = Long.toString(event.getSubject().getId()); NewsUtil.newsNotice(new ArrayList<String>(){{add(subjectId);}}); return true; } public boolean query(){ String temp = System.getProperty("java.io.tmpdir") + "/WeCuit"; String cachePath = temp + "/cache"; String listPath = cachePath + "/news/list"; try{ int dayRange = 1; if(cmds.size() > 0) dayRange = Integer.parseInt(cmds.get(0)); List<Map<String, String>> todayNews = NewsUtil.getLatestNews(listPath, dayRange); if(todayNews.size() == 0) { event.getSubject().sendMessage("没有" + dayRange + "天之内的新闻"); return true; } todayNews.forEach(news->{ try { event.getSubject().sendMessage(new LightApp(NewsProvider.genLightJson(news))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }); event.getSubject().sendMessage("以上是" + dayRange + "天之内的新闻"); }catch (Exception e){ e.printStackTrace(); } return true; } public static boolean checkAdmin(Long id){ return id == 1690127128L; } public void updatePluginData(){ updatePluginData(pluginData); } public static List<String> getEnabledList() { return enabledList; } // 初始化插件数据[从外部到内部] public void initPluginData(Map<String, Object> config){ // pluginData.clear(); // 清空 enabledList.addAll((List<String>)config.get("enabledList")); // 置入 } @Override public List<String> getGlobalCmd() { return null; } }
false
1,231
5
1,377
5
1,450
4
1,377
5
1,750
8
false
false
false
false
false
true
40502_4
package com.guang.app.fragment; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.apkfuns.logutils.LogUtils; import com.guang.app.AppConfig; import com.guang.app.R; import com.guang.app.activity.AboutActivity; import com.guang.app.activity.CardHistoryActivity; import com.guang.app.activity.FeedbackActivity; import com.guang.app.activity.LoginActivity; import com.guang.app.api.CardApiFactory; import com.guang.app.api.JwApiFactory; import com.guang.app.api.WorkApiFactory; import com.guang.app.model.BasicInfo; import com.guang.app.model.CardBasic; import com.guang.app.model.Schedule; import com.guang.app.model.StrObjectResponse; import com.guang.app.util.FileUtils; import com.guang.app.util.ShareUtils; import com.guang.app.util.TimeUtils; import com.guang.app.util.drcom.DrcomFileUtils; import com.tencent.mm.opensdk.modelmsg.SendMessageToWX; import com.umeng.analytics.MobclickAgent; import org.litepal.crud.DataSupport; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import okhttp3.ResponseBody; public class MeFragment extends Fragment { private static JwApiFactory factory = JwApiFactory.getInstance(); private static CardApiFactory cardFactory = CardApiFactory.getInstance(); private static WorkApiFactory workApiFactory = WorkApiFactory.getInstance(); private static String mCardNum; //校园卡卡号,获取校园卡余额时赋值 @Bind(R.id.tv_me_icon) ImageView tvMeIcon; @Bind(R.id.tv_me_sno) TextView tvMeSno; @Bind(R.id.tv_me_name) TextView tvMeName; @Bind(R.id.tv_me_class) TextView tvMeClass; @Bind(R.id.tv_me_cash) TextView tvMeCash; // @Bind(R.id.tv_me_update) // TextView tvMeUpdate; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_me, container, false); ButterKnife.bind(this, view); getActivity().setTitle(R.string.app_name); tvMeSno.setText(AppConfig.sno); BasicInfo basicInfo = DataSupport.findFirst(BasicInfo.class); if(null != basicInfo) { setBasicInfo4View(basicInfo); }else{ queryBasicInfo(); } queryCurrentCash(); return view; } //获取用户基本信息,姓名班级等 private void queryBasicInfo(){ factory.getBasicInfo(new Observer<BasicInfo>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(BasicInfo value) { DataSupport.deleteAll(BasicInfo.class); value.save(); setBasicInfo4View(value); } @Override public void onError(Throwable e) { if(e != null && !TextUtils.isEmpty(e.getMessage())) { LogUtils.e(e.toString()); Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onComplete() { } }); } //校园卡余额 private void queryCurrentCash(){ cardFactory.getCurrentCash(new Observer<CardBasic>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(CardBasic value) { if(null != value && !TextUtils.isEmpty(value.getCash())) { tvMeCash.setText("¥" + value.getCash()); mCardNum = value.getCardNum(); }else{ tvMeCash.setText("获取失败"); } } @Override public void onError(Throwable e) { if(e != null && !TextUtils.isEmpty(e.getMessage())) { LogUtils.e(e.toString()); Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } tvMeCash.setText("获取失败"); } @Override public void onComplete() { } }); } private void setBasicInfo4View(BasicInfo value) { if (value.getSex().equals("女")){ tvMeName.setTextColor(getResources().getColor(R.color.pink)); } tvMeName.setText(value.getName()); tvMeClass.setText(value.getClassroom()); Bitmap bitmap = FileUtils.loadAvatarBitmap(getActivity()); if(bitmap != null){ //读取本地图片头像 tvMeIcon.setImageBitmap(bitmap); }else{ //网络加载头像 workApiFactory.getAvatarIcon(""+value.getName().charAt(0), new Observer<ResponseBody>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(ResponseBody value) { Bitmap bitmap = BitmapFactory.decodeStream(value.byteStream()); FileUtils.saveAvatarImage(getActivity(),bitmap); tvMeIcon.setImageBitmap(bitmap); } @Override public void onError(Throwable e) { if(tvMeIcon != null) { //模拟器测试时的不知名原因 低概率出现 tvMeIcon.setBackgroundResource(R.mipmap.avatar_h); } } @Override public void onComplete() { } }); } //如果是公历生日那天打开,会弹窗表示生日祝福 if( !TextUtils.isEmpty(value.getBirthday()) && value.getBirthday().length() == 8 && value.getBirthday().substring(4, 8) .equals( TimeUtils.getDateStringWithFormat("MMdd"))){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage( " 生日快乐 (๑•̀ㅂ•́)و✧"); builder.setTitle(value.getName()); builder.setPositiveButton("蟹蟹",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int which) { } }); builder.create().show();; } if(AppConfig.schoolmateSno.equals(AppConfig.sno)) { tvMeSno.setText("88888888888"); tvMeName.setText("校友"); tvMeClass.setText("广东财经大学毕业生班"); } } @OnClick(R.id.layout_me_cashhistory) void showConsumeToday(){ if(TextUtils.isEmpty(mCardNum)){ Toast.makeText(getActivity(), "交易记录获取异常", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(getActivity(), CardHistoryActivity.class); intent.putExtra(CardHistoryActivity.intentCardNum,mCardNum); startActivity(intent); } private int mSelectedPage = AppConfig.DefaultPage.HOME; //选择默认页的对话框的当前选择项 @OnClick(R.id.tv_me_default_page) void clickDefaultPage(){ final Context context = getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.mipmap.me_default_page); builder.setTitle("打开APP后直达该页面"); final String[] pages = { context.getString(R.string.tab_home), context.getString(R.string.tab_features), context.getString(R.string.tab_settings),context.getString(R.string.menu_drcom) }; int pageIndex = AppConfig.defaultPage; //默认选择哪个 if(pageIndex == AppConfig.DefaultPage.DRCOM){ pageIndex = 3; } mSelectedPage = pageIndex; //当前选择 //点击item选择时的事件 builder.setSingleChoiceItems(pages, pageIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedPage = which; } }); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(mSelectedPage == 3){ mSelectedPage = AppConfig.DefaultPage.DRCOM; } AppConfig.defaultPage = mSelectedPage; FileUtils.setStoredDefaultPage(context,AppConfig.defaultPage); } }); builder.setNegativeButton("取消", null); builder.show(); } @OnClick(R.id.tv_me_share) void clickShare() { android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(getActivity()); builder.setIcon(R.mipmap.app_icon); builder.setTitle("爱分享的人运气总不会差"); builder.setItems(R.array.shareList, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { int scene = SendMessageToWX.Req.WXSceneSession; if(which == 1) { scene = SendMessageToWX.Req.WXSceneTimeline; }else if(which == 2){ scene = SendMessageToWX.Req.WXSceneFavorite; } ShareUtils.install(getActivity()); ShareUtils.shareWeb(getActivity(),getResources().getString(R.string.app_name)+",你的掌上校园伴侣","广财专用APP,学生开发,课表饭卡校园网,一样不少",AppConfig.WXSHARE_URL, scene); } }); builder.create().show(); } @OnClick(R.id.tv_me_about) void clickAbout(){ startActivity(new Intent(getActivity(), AboutActivity.class)); } @OnClick(R.id.tv_me_feedback) void feedback(){ startActivity(new Intent(getActivity(), FeedbackActivity.class)); } @OnClick(R.id.tv_me_exit) void logout() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("确定退出(切换)账号?"); builder.setMessage("通常情况下按返回键就好了"); builder.setNegativeButton("取消",null); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(getActivity(), LoginActivity.class)); FileUtils.expireStoredAccount(getActivity());//防止点退出后重新打开APP会进入旧帐号 // FileUtils.expireTipsNeverShowAgain(getActivity());/// 重新登陆/切换用户后登陆提示不给看到 DrcomFileUtils.expireStoredAccount(getActivity()); //drcom信息 FileUtils.clearAvatarImage(getActivity()); //清除头像 DataSupport.deleteAll(Schedule.class); //清空课程表 DataSupport.deleteAll(BasicInfo.class); MobclickAgent.onProfileSignOff();//友盟统计用户退出 //服务器端的退出登陆,这个成功与否不影响上面操作 workApiFactory.allLogout(new Observer<StrObjectResponse>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(StrObjectResponse value) { //不需要做处理 } @Override public void onError(Throwable e) { if(null != e.getMessage()){ LogUtils.e(e.getMessage()); } } @Override public void onComplete() { } }); getActivity().finish(); } }); builder.create().show(); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
WeGdufe/SmallGdufe-Android
app/src/main/java/com/guang/app/fragment/MeFragment.java
2,916
//校园卡余额
line_comment
zh-cn
package com.guang.app.fragment; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.apkfuns.logutils.LogUtils; import com.guang.app.AppConfig; import com.guang.app.R; import com.guang.app.activity.AboutActivity; import com.guang.app.activity.CardHistoryActivity; import com.guang.app.activity.FeedbackActivity; import com.guang.app.activity.LoginActivity; import com.guang.app.api.CardApiFactory; import com.guang.app.api.JwApiFactory; import com.guang.app.api.WorkApiFactory; import com.guang.app.model.BasicInfo; import com.guang.app.model.CardBasic; import com.guang.app.model.Schedule; import com.guang.app.model.StrObjectResponse; import com.guang.app.util.FileUtils; import com.guang.app.util.ShareUtils; import com.guang.app.util.TimeUtils; import com.guang.app.util.drcom.DrcomFileUtils; import com.tencent.mm.opensdk.modelmsg.SendMessageToWX; import com.umeng.analytics.MobclickAgent; import org.litepal.crud.DataSupport; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import okhttp3.ResponseBody; public class MeFragment extends Fragment { private static JwApiFactory factory = JwApiFactory.getInstance(); private static CardApiFactory cardFactory = CardApiFactory.getInstance(); private static WorkApiFactory workApiFactory = WorkApiFactory.getInstance(); private static String mCardNum; //校园卡卡号,获取校园卡余额时赋值 @Bind(R.id.tv_me_icon) ImageView tvMeIcon; @Bind(R.id.tv_me_sno) TextView tvMeSno; @Bind(R.id.tv_me_name) TextView tvMeName; @Bind(R.id.tv_me_class) TextView tvMeClass; @Bind(R.id.tv_me_cash) TextView tvMeCash; // @Bind(R.id.tv_me_update) // TextView tvMeUpdate; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_me, container, false); ButterKnife.bind(this, view); getActivity().setTitle(R.string.app_name); tvMeSno.setText(AppConfig.sno); BasicInfo basicInfo = DataSupport.findFirst(BasicInfo.class); if(null != basicInfo) { setBasicInfo4View(basicInfo); }else{ queryBasicInfo(); } queryCurrentCash(); return view; } //获取用户基本信息,姓名班级等 private void queryBasicInfo(){ factory.getBasicInfo(new Observer<BasicInfo>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(BasicInfo value) { DataSupport.deleteAll(BasicInfo.class); value.save(); setBasicInfo4View(value); } @Override public void onError(Throwable e) { if(e != null && !TextUtils.isEmpty(e.getMessage())) { LogUtils.e(e.toString()); Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onComplete() { } }); } //校园 <SUF> private void queryCurrentCash(){ cardFactory.getCurrentCash(new Observer<CardBasic>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(CardBasic value) { if(null != value && !TextUtils.isEmpty(value.getCash())) { tvMeCash.setText("¥" + value.getCash()); mCardNum = value.getCardNum(); }else{ tvMeCash.setText("获取失败"); } } @Override public void onError(Throwable e) { if(e != null && !TextUtils.isEmpty(e.getMessage())) { LogUtils.e(e.toString()); Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } tvMeCash.setText("获取失败"); } @Override public void onComplete() { } }); } private void setBasicInfo4View(BasicInfo value) { if (value.getSex().equals("女")){ tvMeName.setTextColor(getResources().getColor(R.color.pink)); } tvMeName.setText(value.getName()); tvMeClass.setText(value.getClassroom()); Bitmap bitmap = FileUtils.loadAvatarBitmap(getActivity()); if(bitmap != null){ //读取本地图片头像 tvMeIcon.setImageBitmap(bitmap); }else{ //网络加载头像 workApiFactory.getAvatarIcon(""+value.getName().charAt(0), new Observer<ResponseBody>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(ResponseBody value) { Bitmap bitmap = BitmapFactory.decodeStream(value.byteStream()); FileUtils.saveAvatarImage(getActivity(),bitmap); tvMeIcon.setImageBitmap(bitmap); } @Override public void onError(Throwable e) { if(tvMeIcon != null) { //模拟器测试时的不知名原因 低概率出现 tvMeIcon.setBackgroundResource(R.mipmap.avatar_h); } } @Override public void onComplete() { } }); } //如果是公历生日那天打开,会弹窗表示生日祝福 if( !TextUtils.isEmpty(value.getBirthday()) && value.getBirthday().length() == 8 && value.getBirthday().substring(4, 8) .equals( TimeUtils.getDateStringWithFormat("MMdd"))){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage( " 生日快乐 (๑•̀ㅂ•́)و✧"); builder.setTitle(value.getName()); builder.setPositiveButton("蟹蟹",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int which) { } }); builder.create().show();; } if(AppConfig.schoolmateSno.equals(AppConfig.sno)) { tvMeSno.setText("88888888888"); tvMeName.setText("校友"); tvMeClass.setText("广东财经大学毕业生班"); } } @OnClick(R.id.layout_me_cashhistory) void showConsumeToday(){ if(TextUtils.isEmpty(mCardNum)){ Toast.makeText(getActivity(), "交易记录获取异常", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(getActivity(), CardHistoryActivity.class); intent.putExtra(CardHistoryActivity.intentCardNum,mCardNum); startActivity(intent); } private int mSelectedPage = AppConfig.DefaultPage.HOME; //选择默认页的对话框的当前选择项 @OnClick(R.id.tv_me_default_page) void clickDefaultPage(){ final Context context = getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.mipmap.me_default_page); builder.setTitle("打开APP后直达该页面"); final String[] pages = { context.getString(R.string.tab_home), context.getString(R.string.tab_features), context.getString(R.string.tab_settings),context.getString(R.string.menu_drcom) }; int pageIndex = AppConfig.defaultPage; //默认选择哪个 if(pageIndex == AppConfig.DefaultPage.DRCOM){ pageIndex = 3; } mSelectedPage = pageIndex; //当前选择 //点击item选择时的事件 builder.setSingleChoiceItems(pages, pageIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedPage = which; } }); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(mSelectedPage == 3){ mSelectedPage = AppConfig.DefaultPage.DRCOM; } AppConfig.defaultPage = mSelectedPage; FileUtils.setStoredDefaultPage(context,AppConfig.defaultPage); } }); builder.setNegativeButton("取消", null); builder.show(); } @OnClick(R.id.tv_me_share) void clickShare() { android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(getActivity()); builder.setIcon(R.mipmap.app_icon); builder.setTitle("爱分享的人运气总不会差"); builder.setItems(R.array.shareList, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { int scene = SendMessageToWX.Req.WXSceneSession; if(which == 1) { scene = SendMessageToWX.Req.WXSceneTimeline; }else if(which == 2){ scene = SendMessageToWX.Req.WXSceneFavorite; } ShareUtils.install(getActivity()); ShareUtils.shareWeb(getActivity(),getResources().getString(R.string.app_name)+",你的掌上校园伴侣","广财专用APP,学生开发,课表饭卡校园网,一样不少",AppConfig.WXSHARE_URL, scene); } }); builder.create().show(); } @OnClick(R.id.tv_me_about) void clickAbout(){ startActivity(new Intent(getActivity(), AboutActivity.class)); } @OnClick(R.id.tv_me_feedback) void feedback(){ startActivity(new Intent(getActivity(), FeedbackActivity.class)); } @OnClick(R.id.tv_me_exit) void logout() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("确定退出(切换)账号?"); builder.setMessage("通常情况下按返回键就好了"); builder.setNegativeButton("取消",null); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(getActivity(), LoginActivity.class)); FileUtils.expireStoredAccount(getActivity());//防止点退出后重新打开APP会进入旧帐号 // FileUtils.expireTipsNeverShowAgain(getActivity());/// 重新登陆/切换用户后登陆提示不给看到 DrcomFileUtils.expireStoredAccount(getActivity()); //drcom信息 FileUtils.clearAvatarImage(getActivity()); //清除头像 DataSupport.deleteAll(Schedule.class); //清空课程表 DataSupport.deleteAll(BasicInfo.class); MobclickAgent.onProfileSignOff();//友盟统计用户退出 //服务器端的退出登陆,这个成功与否不影响上面操作 workApiFactory.allLogout(new Observer<StrObjectResponse>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(StrObjectResponse value) { //不需要做处理 } @Override public void onError(Throwable e) { if(null != e.getMessage()){ LogUtils.e(e.getMessage()); } } @Override public void onComplete() { } }); getActivity().finish(); } }); builder.create().show(); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
false
2,365
4
2,916
7
3,012
4
2,916
7
3,677
14
false
false
false
false
false
true
62232_2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.study.shortLink.admin.remote.dto.req; import lombok.Data; /** * 短链接监控请求参数 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Data public class ShortLinkStatsReqDTO { /** * 完整短链接 */ private String fullShortUrl; /** * 分组标识 */ private String gid; /** * 开始日期 */ private String startDate; /** * 结束日期 */ private String endDate; }
WearingCucumber/shortlink
admin/src/main/java/com/study/shortLink/admin/remote/dto/req/ShortLinkStatsReqDTO.java
325
/** * 完整短链接 */
block_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.study.shortLink.admin.remote.dto.req; import lombok.Data; /** * 短链接监控请求参数 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Data public class ShortLinkStatsReqDTO { /** * 完整短 <SUF>*/ private String fullShortUrl; /** * 分组标识 */ private String gid; /** * 开始日期 */ private String startDate; /** * 结束日期 */ private String endDate; }
false
296
11
325
9
330
11
325
9
425
19
false
false
false
false
false
true
26192_10
package BusinessLogic; import DataAccess.*; import UI.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; public class Main { public static void main(String[] args) { //最初的写入词汇包文件 InitWordBags.initWordBags(); //加载配置信息 Config config = null; try(ObjectInputStream input = new ObjectInputStream(new FileInputStream("./wordBags/config"))){ config = (Config)input.readObject(); }catch(Exception ex){ ex.printStackTrace(); } CurrentField.setCurrentField(config.field); //打开窗口 MainFrame mainFrame = new MainFrame(); mainFrame.addWindowListener(new MyWindowListener()); mainFrame.setVisible(true); //检查更新 WordBagUpdater.checkUpdate(); } } //爬虫测试类 class DetectorTest{ public static void test() throws IOException, ClassNotFoundException{ //显示相关微博热搜条目 System.out.println("相关微博热搜条目:"); java.util.List<HotItem> weiboSelectedItems = Detector.weiboDetector(); for(HotItem s : weiboSelectedItems){ System.out.println(s); } System.out.println(); //显示相关知乎热榜 System.out.println("相关知乎热榜条目"); java.util.List<HotItem> zhihuSelectedItems = Detector.zhihuDetector(); for(HotItem s : zhihuSelectedItems){ System.out.println(s); } System.out.println(); //显示相关百度实时热点条目 System.out.println("相关百度实时热点条目"); java.util.List<HotItem> baiduSelectedItems = Detector.baiduDetector(); for(HotItem s : baiduSelectedItems){ System.out.println(s); } } } //最初的词汇包写入 class InitWordBags{ //备份词库 private static String[] techWordBag = { //企业名称 "苹果","三星","华为","荣耀","小米","红米","华米","OPPO", "vivo","魅族","努比亚","锤子","阿里","腾讯","百度","微软", "谷歌","台积电","中兴","联想","中芯","海信","Facebook","亚马逊", "美团","当当","饿了么","一加","字节跳动","京东","高通","英特尔", "英伟达","IBM","特斯拉","蔚来","小鹏","任天堂","索尼","格力", "中国移动","联通","电信","摩托罗拉","米家","realme", "网易","蚂蚁金服","Space","滴滴","大疆","菜鸟","旷视","海康", "拼多多","乐视", //科技人物 "乔布斯","库克","马斯克","李国庆","余渝","雷军","林斌","卢伟冰", "常程","刘作虎","任正非","余承东","赵明","马云","蒋凡", "张勇","扎克伯格","贝佐斯","贝索斯","刘强东","董明珠","罗永浩", "贾跃亭", //科技产品 "iPhone","Mac","iPad","Watch","AirPod","HomePod","iOS", "安卓","Android","鸿蒙","小爱","支付宝","nova","HMS","Kindle", "比特","微信","QQ","Switch","抖音","快手","B站","骁龙", "钉钉","Linux","Windows","Siri","Surface","C++","Python", "Java","Swift", //其他短语 "科技","科学","智能","手机","手环","电脑","电视","智慧屏", "软件","硬件","计算机","电子","航天","卫星","硅谷","芯", "VR","虚拟现实","AR","增强现实","开发者","AI","区块链","APP", "UI","机器学习","屏幕","CPU","APP","PC","脑机","屏幕", "IT","电动","网络","互联","工信部","运营商","广电","5G", "4G","信号","编程","专利","星链","VPN","程序","基站", "通信","设备","折叠屏","充电","物联网","旗舰","数据","编程", "com","自动驾驶","无人","融资","服务器","设计","合伙人","高管", "设计","用户","代码","源码","开源","宇宙","火箭","太空", "IP","Pro","业绩","下载","黑客","极客", }; //备份屏蔽词库 private static String[] blockedTechWordBag = {}; private static String[] entertainmentWordBag = { "娱乐圈","虞书欣","何炅","陈芊芊","王一博","易烊千玺","谢娜","伊能静","鹿晗","郑云龙","仝卓","吴宣仪","杨幂", "饭圈","歌手","演员","卫视","娱乐","电视剧","影视剧","主角","配角","定档","翻拍","综艺","明星", "第一季","第二季","第三季","第四季","第五季","第六季", "奔跑吧","青你","青春有你","最强大脑","声入人心","好声音", "校草","校花","CP","分手","演技","恋情", "李宇春","陈小春","张根硕","何猷君","应采儿","王一博","肖战","易烊千玺", "严浩翔","王俊凯","罗云熙","翟潇闻","蔡徐坤","迪丽热巴","周震南","李现","朱一龙", "范丞丞","华晨宇","任嘉伦","黄子韬","赵丽颖","朱正廷","王源","黄晓明","范冰冰","谢娜", "张云雷","张杰","李易峰","孟美岐","李荣浩","杨紫","鞠婧祎","吴宣仪","邓超","薛之谦", "沈腾","刘亦菲","陈赫","周冬雨","江疏影","毛不易","杨超越","张若昀", }; private static String[] blockedEntertainmentWordBag = {}; private static String[] sportWordBag = { "体育","DOTA","LoL","LOL","英雄联盟","王者荣耀","守望先锋","CSGO","阴阳师", "iG","RNG", "排位","转会","退役","联赛","赛季","MVP", "篮球","网球","足球","排球","乒乓球","高尔夫","手游","太极拳", "NBA","CBA","英超","中超","暴雪", "詹姆斯","科比","乔丹","威少","奥登", "骑士","湖人","火箭", "跑步","田径","跳高","跨栏","跳远","接力","拔河","跳绳","运动", "奥运会","亚运会","锦标赛","运动会", }; private static String[] blockedSportWordBag = {}; private static String[] customWordBag = {}; private static String[] blockedCustomWordBag = {}; public static void initWordBags() { try{ File f1 = new File("./wordBags/techWordBag"); if(!f1.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f1))){ output.writeObject(techWordBag); } } File f2 = new File("./wordBags/blockedTechWordBag"); if(!f2.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f2))){ output.writeObject(blockedTechWordBag); } } File f3 = new File("./wordBags/entertainmentWordBag"); if(!f3.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f3))){ output.writeObject(entertainmentWordBag); } } File f4 = new File("./wordBags/blockedEntertainmentWordBag"); if(!f4.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f4))){ output.writeObject(blockedEntertainmentWordBag); } } File f5 = new File("./wordBags/sportWordBag"); if(!f5.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f5))){ output.writeObject(sportWordBag); } } File f6 = new File("./wordBags/blockedSportWordBag"); if(!f6.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f6))){ output.writeObject(blockedSportWordBag); } } File f7 = new File("./wordBags/customWordBag"); if(!f7.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f7))){ output.writeObject(customWordBag); } } File f8 = new File("./wordBags/blockedCustomWordBag"); if(!f8.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f8))){ output.writeObject(blockedCustomWordBag); } } //初始化配置信息 File fConfig = new File("./wordBags/config"); if(!fConfig.exists()){ try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(fConfig))){ output.writeObject(new Config("6.0", Field.Tech)); } } }catch(IOException ex){ Warning.NoPermissionWarning(); ex.printStackTrace(); } } } class MyWindowListener extends WindowAdapter{ @Override public void windowClosing(WindowEvent e){ super.windowClosing(e); } }
WebboHsu/HotDetector
src/BusinessLogic/Main.java
2,613
//企业名称
line_comment
zh-cn
package BusinessLogic; import DataAccess.*; import UI.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; public class Main { public static void main(String[] args) { //最初的写入词汇包文件 InitWordBags.initWordBags(); //加载配置信息 Config config = null; try(ObjectInputStream input = new ObjectInputStream(new FileInputStream("./wordBags/config"))){ config = (Config)input.readObject(); }catch(Exception ex){ ex.printStackTrace(); } CurrentField.setCurrentField(config.field); //打开窗口 MainFrame mainFrame = new MainFrame(); mainFrame.addWindowListener(new MyWindowListener()); mainFrame.setVisible(true); //检查更新 WordBagUpdater.checkUpdate(); } } //爬虫测试类 class DetectorTest{ public static void test() throws IOException, ClassNotFoundException{ //显示相关微博热搜条目 System.out.println("相关微博热搜条目:"); java.util.List<HotItem> weiboSelectedItems = Detector.weiboDetector(); for(HotItem s : weiboSelectedItems){ System.out.println(s); } System.out.println(); //显示相关知乎热榜 System.out.println("相关知乎热榜条目"); java.util.List<HotItem> zhihuSelectedItems = Detector.zhihuDetector(); for(HotItem s : zhihuSelectedItems){ System.out.println(s); } System.out.println(); //显示相关百度实时热点条目 System.out.println("相关百度实时热点条目"); java.util.List<HotItem> baiduSelectedItems = Detector.baiduDetector(); for(HotItem s : baiduSelectedItems){ System.out.println(s); } } } //最初的词汇包写入 class InitWordBags{ //备份词库 private static String[] techWordBag = { //企业 <SUF> "苹果","三星","华为","荣耀","小米","红米","华米","OPPO", "vivo","魅族","努比亚","锤子","阿里","腾讯","百度","微软", "谷歌","台积电","中兴","联想","中芯","海信","Facebook","亚马逊", "美团","当当","饿了么","一加","字节跳动","京东","高通","英特尔", "英伟达","IBM","特斯拉","蔚来","小鹏","任天堂","索尼","格力", "中国移动","联通","电信","摩托罗拉","米家","realme", "网易","蚂蚁金服","Space","滴滴","大疆","菜鸟","旷视","海康", "拼多多","乐视", //科技人物 "乔布斯","库克","马斯克","李国庆","余渝","雷军","林斌","卢伟冰", "常程","刘作虎","任正非","余承东","赵明","马云","蒋凡", "张勇","扎克伯格","贝佐斯","贝索斯","刘强东","董明珠","罗永浩", "贾跃亭", //科技产品 "iPhone","Mac","iPad","Watch","AirPod","HomePod","iOS", "安卓","Android","鸿蒙","小爱","支付宝","nova","HMS","Kindle", "比特","微信","QQ","Switch","抖音","快手","B站","骁龙", "钉钉","Linux","Windows","Siri","Surface","C++","Python", "Java","Swift", //其他短语 "科技","科学","智能","手机","手环","电脑","电视","智慧屏", "软件","硬件","计算机","电子","航天","卫星","硅谷","芯", "VR","虚拟现实","AR","增强现实","开发者","AI","区块链","APP", "UI","机器学习","屏幕","CPU","APP","PC","脑机","屏幕", "IT","电动","网络","互联","工信部","运营商","广电","5G", "4G","信号","编程","专利","星链","VPN","程序","基站", "通信","设备","折叠屏","充电","物联网","旗舰","数据","编程", "com","自动驾驶","无人","融资","服务器","设计","合伙人","高管", "设计","用户","代码","源码","开源","宇宙","火箭","太空", "IP","Pro","业绩","下载","黑客","极客", }; //备份屏蔽词库 private static String[] blockedTechWordBag = {}; private static String[] entertainmentWordBag = { "娱乐圈","虞书欣","何炅","陈芊芊","王一博","易烊千玺","谢娜","伊能静","鹿晗","郑云龙","仝卓","吴宣仪","杨幂", "饭圈","歌手","演员","卫视","娱乐","电视剧","影视剧","主角","配角","定档","翻拍","综艺","明星", "第一季","第二季","第三季","第四季","第五季","第六季", "奔跑吧","青你","青春有你","最强大脑","声入人心","好声音", "校草","校花","CP","分手","演技","恋情", "李宇春","陈小春","张根硕","何猷君","应采儿","王一博","肖战","易烊千玺", "严浩翔","王俊凯","罗云熙","翟潇闻","蔡徐坤","迪丽热巴","周震南","李现","朱一龙", "范丞丞","华晨宇","任嘉伦","黄子韬","赵丽颖","朱正廷","王源","黄晓明","范冰冰","谢娜", "张云雷","张杰","李易峰","孟美岐","李荣浩","杨紫","鞠婧祎","吴宣仪","邓超","薛之谦", "沈腾","刘亦菲","陈赫","周冬雨","江疏影","毛不易","杨超越","张若昀", }; private static String[] blockedEntertainmentWordBag = {}; private static String[] sportWordBag = { "体育","DOTA","LoL","LOL","英雄联盟","王者荣耀","守望先锋","CSGO","阴阳师", "iG","RNG", "排位","转会","退役","联赛","赛季","MVP", "篮球","网球","足球","排球","乒乓球","高尔夫","手游","太极拳", "NBA","CBA","英超","中超","暴雪", "詹姆斯","科比","乔丹","威少","奥登", "骑士","湖人","火箭", "跑步","田径","跳高","跨栏","跳远","接力","拔河","跳绳","运动", "奥运会","亚运会","锦标赛","运动会", }; private static String[] blockedSportWordBag = {}; private static String[] customWordBag = {}; private static String[] blockedCustomWordBag = {}; public static void initWordBags() { try{ File f1 = new File("./wordBags/techWordBag"); if(!f1.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f1))){ output.writeObject(techWordBag); } } File f2 = new File("./wordBags/blockedTechWordBag"); if(!f2.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f2))){ output.writeObject(blockedTechWordBag); } } File f3 = new File("./wordBags/entertainmentWordBag"); if(!f3.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f3))){ output.writeObject(entertainmentWordBag); } } File f4 = new File("./wordBags/blockedEntertainmentWordBag"); if(!f4.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f4))){ output.writeObject(blockedEntertainmentWordBag); } } File f5 = new File("./wordBags/sportWordBag"); if(!f5.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f5))){ output.writeObject(sportWordBag); } } File f6 = new File("./wordBags/blockedSportWordBag"); if(!f6.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f6))){ output.writeObject(blockedSportWordBag); } } File f7 = new File("./wordBags/customWordBag"); if(!f7.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f7))){ output.writeObject(customWordBag); } } File f8 = new File("./wordBags/blockedCustomWordBag"); if(!f8.exists()) { try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f8))){ output.writeObject(blockedCustomWordBag); } } //初始化配置信息 File fConfig = new File("./wordBags/config"); if(!fConfig.exists()){ try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(fConfig))){ output.writeObject(new Config("6.0", Field.Tech)); } } }catch(IOException ex){ Warning.NoPermissionWarning(); ex.printStackTrace(); } } } class MyWindowListener extends WindowAdapter{ @Override public void windowClosing(WindowEvent e){ super.windowClosing(e); } }
false
2,070
3
2,612
3
2,446
3
2,613
3
3,410
7
false
false
false
false
false
true
25475_1
package xin.pxyu.servlet; /* c/s模式 p2p模式 应用层协议 http ftp tftp telnet smtp pop3 imap dns ssh ssl 传输层协议 tcp udp rdt1.0 rdt2.0 rdt2.1 rdt2.2 rdt3.0 go-back-n select-repeat */ import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import xin.pxyu.json.SingleObject; import xin.pxyu.json.StatusObject; import xin.pxyu.model.TaskImage; import xin.pxyu.service.TaskImageService; import xin.pxyu.util.JackJsonUtils; import xin.pxyu.util.ResponseUtils; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; //上传图片 public class fileUpload extends HttpServlet { /* http请求报文: 1)请求行 :请求方法,请求资源的url 2)首部行header: 3)尸体主题body: */ public void doPost(HttpServletRequest request, HttpServletResponse response){ System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"FileUpload接口收到"+request.getRemoteAddr()+"的请求"); if(ServletFileUpload.isMultipartContent(request)){//二进制上传; "multipart/form-data" //获取tomcat路径; // String path = request.getServletContext().getRealPath("/"); String path="/root/apache-tomcat-8.0.52/webapps/"; //获取系统的路径分隔符; String tmp = System.getProperty("file.separator")+"temp"; //创建临时目录 File tmpDir = new File(tmp); //创建磁盘文件工厂 DiskFileItemFactory dff = new DiskFileItemFactory(); dff.setRepository(tmpDir);//设置临时存储目录 dff.setSizeThreshold(1024*1024*10);//设置临时文件缓存大//10M //创建 ServletFileUpload sfu = new ServletFileUpload(dff);//servlet文件上传对象; sfu.setFileSizeMax(1024*1024*10);//设置单个文件最大空间 sfu.setSizeMax(1024*1024*10*100);//设置所有文件最大空间大小; try{ //获取所有上传组件的遍历器 FileItemIterator fii = sfu.getItemIterator(request); TaskImage taskImage= TaskImageService.upload(path,fii); if(TaskImageService.updateTaskImage(taskImage)){ TaskImage list=taskImage; SingleObject singleObject=new SingleObject(); singleObject.setObject(list); if(list!=null) { singleObject.setStatusObject(new StatusObject("200", "上传图片成功")); String responseText= JackJsonUtils.toJson(singleObject); ResponseUtils.renderJson(response,responseText); } }else{ TaskImage list=taskImage; SingleObject singleObject=new SingleObject(); singleObject.setObject(list); String responseText= JackJsonUtils.toJson(singleObject); ResponseUtils.renderJson(response,responseText);singleObject.setStatusObject(new StatusObject("400","上传图片失败")); } }catch(FileUploadException f){ System.out.println("FileUploadException错误"); f.printStackTrace(); }catch (IOException e){ System.out.println("IOException错误"); e.printStackTrace(); } }} }
WechatAppletByWD/ByHand
src/xin/pxyu/servlet/fileUpload.java
914
//上传图片
line_comment
zh-cn
package xin.pxyu.servlet; /* c/s模式 p2p模式 应用层协议 http ftp tftp telnet smtp pop3 imap dns ssh ssl 传输层协议 tcp udp rdt1.0 rdt2.0 rdt2.1 rdt2.2 rdt3.0 go-back-n select-repeat */ import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import xin.pxyu.json.SingleObject; import xin.pxyu.json.StatusObject; import xin.pxyu.model.TaskImage; import xin.pxyu.service.TaskImageService; import xin.pxyu.util.JackJsonUtils; import xin.pxyu.util.ResponseUtils; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; //上传 <SUF> public class fileUpload extends HttpServlet { /* http请求报文: 1)请求行 :请求方法,请求资源的url 2)首部行header: 3)尸体主题body: */ public void doPost(HttpServletRequest request, HttpServletResponse response){ System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"FileUpload接口收到"+request.getRemoteAddr()+"的请求"); if(ServletFileUpload.isMultipartContent(request)){//二进制上传; "multipart/form-data" //获取tomcat路径; // String path = request.getServletContext().getRealPath("/"); String path="/root/apache-tomcat-8.0.52/webapps/"; //获取系统的路径分隔符; String tmp = System.getProperty("file.separator")+"temp"; //创建临时目录 File tmpDir = new File(tmp); //创建磁盘文件工厂 DiskFileItemFactory dff = new DiskFileItemFactory(); dff.setRepository(tmpDir);//设置临时存储目录 dff.setSizeThreshold(1024*1024*10);//设置临时文件缓存大//10M //创建 ServletFileUpload sfu = new ServletFileUpload(dff);//servlet文件上传对象; sfu.setFileSizeMax(1024*1024*10);//设置单个文件最大空间 sfu.setSizeMax(1024*1024*10*100);//设置所有文件最大空间大小; try{ //获取所有上传组件的遍历器 FileItemIterator fii = sfu.getItemIterator(request); TaskImage taskImage= TaskImageService.upload(path,fii); if(TaskImageService.updateTaskImage(taskImage)){ TaskImage list=taskImage; SingleObject singleObject=new SingleObject(); singleObject.setObject(list); if(list!=null) { singleObject.setStatusObject(new StatusObject("200", "上传图片成功")); String responseText= JackJsonUtils.toJson(singleObject); ResponseUtils.renderJson(response,responseText); } }else{ TaskImage list=taskImage; SingleObject singleObject=new SingleObject(); singleObject.setObject(list); String responseText= JackJsonUtils.toJson(singleObject); ResponseUtils.renderJson(response,responseText);singleObject.setStatusObject(new StatusObject("400","上传图片失败")); } }catch(FileUploadException f){ System.out.println("FileUploadException错误"); f.printStackTrace(); }catch (IOException e){ System.out.println("IOException错误"); e.printStackTrace(); } }} }
false
795
3
914
3
938
3
914
3
1,138
5
false
false
false
false
false
true
61470_0
package lintcode.China.section02; import utils.ListNode; /** * 容易 翻转链表 41% 通过 翻转一个链表 您在真实的面试中是否遇到过这个题? Yes 样例 给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null 挑战 在原地一次翻转完成 http://www.lintcode.com/zh-cn/problem/reverse-linked-list/ * */ public class Reverse { public ListNode reverse(ListNode head) { return mySolution(head); } private ListNode mySolution(ListNode head) { ListNode prev = null; while (head != null) { ListNode temp = head.next; head.next = prev; prev = head; head = temp; } return prev; } public static void main(String[] args) { ListNode l = new ListNode(3); l.next = new ListNode(2); l.next.next = new ListNode(1); Reverse r = new Reverse(); System.out.println(r.reverse(l)); } }
WeiEast/Algorithms
src/main/java/lintcode/China/section02/Reverse.java
298
/** * 容易 翻转链表 41% 通过 翻转一个链表 您在真实的面试中是否遇到过这个题? Yes 样例 给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null 挑战 在原地一次翻转完成 http://www.lintcode.com/zh-cn/problem/reverse-linked-list/ * */
block_comment
zh-cn
package lintcode.China.section02; import utils.ListNode; /** * 容易 <SUF>*/ public class Reverse { public ListNode reverse(ListNode head) { return mySolution(head); } private ListNode mySolution(ListNode head) { ListNode prev = null; while (head != null) { ListNode temp = head.next; head.next = prev; prev = head; head = temp; } return prev; } public static void main(String[] args) { ListNode l = new ListNode(3); l.next = new ListNode(2); l.next.next = new ListNode(1); Reverse r = new Reverse(); System.out.println(r.reverse(l)); } }
false
248
102
296
110
291
107
296
110
382
157
false
false
false
false
false
true
20523_6
import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import us.codecraft.xsoup.Xsoup; import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Cipher; /** * * 补位方式RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同 目前是jdk1.7 * * */ public class RSAUPKCS1tils { /** * 生成公钥和私钥 * @throws NoSuchAlgorithmException * */ public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{ HashMap<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put("public", publicKey); map.put("private", privateKey); return map; } /** * * * @param modulus * 模 * @param exponent * 指数 * @return */ public static RSAPublicKey getPublicKey(String modulus, String exponent) throws Exception { BigInteger b1 = new BigInteger(modulus, 16); BigInteger b2 = new BigInteger(exponent, 16); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } /** * * @param modulus * 模 * @param exponent * 指数 * @return */ public static RSAPrivateKey getPrivateKey(String modulus, String exponent) throws Exception { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } /** * 公钥加密 * * @param data * @param publicKey * @return * @throws Exception */ public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 模长 int key_len = publicKey.getModulus().bitLength() / 8; // 加密数据长度 <= 模长-11 String[] datas = splitString(data, key_len - 11); String mi = ""; //如果明文长度大于模长-11则要分组加密 for (String s : datas) { mi += bcd2Str(cipher.doFinal(s.getBytes())); } return mi; } /** * 私钥解密 * * @param data * @param privateKey * @return * @throws Exception */ public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); //模长 int key_len = privateKey.getModulus().bitLength() / 8; byte[] bytes = data.getBytes(); byte[] bcd = ASCII_To_BCD(bytes, bytes.length); System.err.println(bcd.length); //如果密文长度大于模长则要分组解密 String ming = ""; byte[][] arrays = splitArray(bcd, key_len); for(byte[] arr : arrays){ ming += new String(cipher.doFinal(arr)); } return ming; } /** * ASCII码转BCD码 * */ public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) { byte[] bcd = new byte[asc_len / 2]; int j = 0; for (int i = 0; i < (asc_len + 1) / 2; i++) { bcd[i] = asc_to_bcd(ascii[j++]); bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4)); } return bcd; } public static byte asc_to_bcd(byte asc) { byte bcd; if ((asc >= '0') && (asc <= '9')) bcd = (byte) (asc - '0'); else if ((asc >= 'A') && (asc <= 'F')) bcd = (byte) (asc - 'A' + 10); else if ((asc >= 'a') && (asc <= 'f')) bcd = (byte) (asc - 'a' + 10); else bcd = (byte) (asc - 48); return bcd; } /** * BCD转字符串 */ public static String bcd2Str(byte[] bytes) { char temp[] = new char[bytes.length * 2], val; for (int i = 0; i < bytes.length; i++) { val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f); temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); val = (char) (bytes[i] & 0x0f); temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); } return new String(temp); } /** * 拆分字符串 */ public static String[] splitString(String string, int len) { int x = string.length() / len; int y = string.length() % len; int z = 0; if (y != 0) { z = 1; } String[] strings = new String[x + z]; String str = ""; for (int i=0; i<x+z; i++) { if (i==x+z-1 && y!=0) { str = string.substring(i*len, i*len+y); }else{ str = string.substring(i*len, i*len+len); } strings[i] = str; } return strings; } /** *拆分数组 */ public static byte[][] splitArray(byte[] data,int len){ int x = data.length / len; int y = data.length % len; int z = 0; if(y!=0){ z = 1; } byte[][] arrays = new byte[x+z][]; byte[] arr; for(int i=0; i<x+z; i++){ arr = new byte[len]; if(i==x+z-1 && y!=0){ System.arraycopy(data, i*len, arr, 0, y); }else{ System.arraycopy(data, i*len, arr, 0, len); } arrays[i] = arr; } return arrays; } public static String getHexEnc(String message, String modulus, String public_exponent) throws Exception{ RSAPublicKey pubKey = RSAUPKCS1tils.getPublicKey(modulus, public_exponent); String mi = RSAUPKCS1tils.encryptByPublicKey(message, pubKey); return mi; } public static String getBase64Enc(String message, String modulus, String public_exponent) throws Exception{ return Base64Utils.encode(BytesHexUtlis.hexStringToBytes(getHexEnc(message, modulus, public_exponent))); } }
WeiEast/prox
ras.java
2,052
//如果明文长度大于模长-11则要分组加密
line_comment
zh-cn
import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import us.codecraft.xsoup.Xsoup; import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Cipher; /** * * 补位方式RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同 目前是jdk1.7 * * */ public class RSAUPKCS1tils { /** * 生成公钥和私钥 * @throws NoSuchAlgorithmException * */ public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{ HashMap<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put("public", publicKey); map.put("private", privateKey); return map; } /** * * * @param modulus * 模 * @param exponent * 指数 * @return */ public static RSAPublicKey getPublicKey(String modulus, String exponent) throws Exception { BigInteger b1 = new BigInteger(modulus, 16); BigInteger b2 = new BigInteger(exponent, 16); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } /** * * @param modulus * 模 * @param exponent * 指数 * @return */ public static RSAPrivateKey getPrivateKey(String modulus, String exponent) throws Exception { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } /** * 公钥加密 * * @param data * @param publicKey * @return * @throws Exception */ public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 模长 int key_len = publicKey.getModulus().bitLength() / 8; // 加密数据长度 <= 模长-11 String[] datas = splitString(data, key_len - 11); String mi = ""; //如果 <SUF> for (String s : datas) { mi += bcd2Str(cipher.doFinal(s.getBytes())); } return mi; } /** * 私钥解密 * * @param data * @param privateKey * @return * @throws Exception */ public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); //模长 int key_len = privateKey.getModulus().bitLength() / 8; byte[] bytes = data.getBytes(); byte[] bcd = ASCII_To_BCD(bytes, bytes.length); System.err.println(bcd.length); //如果密文长度大于模长则要分组解密 String ming = ""; byte[][] arrays = splitArray(bcd, key_len); for(byte[] arr : arrays){ ming += new String(cipher.doFinal(arr)); } return ming; } /** * ASCII码转BCD码 * */ public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) { byte[] bcd = new byte[asc_len / 2]; int j = 0; for (int i = 0; i < (asc_len + 1) / 2; i++) { bcd[i] = asc_to_bcd(ascii[j++]); bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4)); } return bcd; } public static byte asc_to_bcd(byte asc) { byte bcd; if ((asc >= '0') && (asc <= '9')) bcd = (byte) (asc - '0'); else if ((asc >= 'A') && (asc <= 'F')) bcd = (byte) (asc - 'A' + 10); else if ((asc >= 'a') && (asc <= 'f')) bcd = (byte) (asc - 'a' + 10); else bcd = (byte) (asc - 48); return bcd; } /** * BCD转字符串 */ public static String bcd2Str(byte[] bytes) { char temp[] = new char[bytes.length * 2], val; for (int i = 0; i < bytes.length; i++) { val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f); temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); val = (char) (bytes[i] & 0x0f); temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); } return new String(temp); } /** * 拆分字符串 */ public static String[] splitString(String string, int len) { int x = string.length() / len; int y = string.length() % len; int z = 0; if (y != 0) { z = 1; } String[] strings = new String[x + z]; String str = ""; for (int i=0; i<x+z; i++) { if (i==x+z-1 && y!=0) { str = string.substring(i*len, i*len+y); }else{ str = string.substring(i*len, i*len+len); } strings[i] = str; } return strings; } /** *拆分数组 */ public static byte[][] splitArray(byte[] data,int len){ int x = data.length / len; int y = data.length % len; int z = 0; if(y!=0){ z = 1; } byte[][] arrays = new byte[x+z][]; byte[] arr; for(int i=0; i<x+z; i++){ arr = new byte[len]; if(i==x+z-1 && y!=0){ System.arraycopy(data, i*len, arr, 0, y); }else{ System.arraycopy(data, i*len, arr, 0, len); } arrays[i] = arr; } return arrays; } public static String getHexEnc(String message, String modulus, String public_exponent) throws Exception{ RSAPublicKey pubKey = RSAUPKCS1tils.getPublicKey(modulus, public_exponent); String mi = RSAUPKCS1tils.encryptByPublicKey(message, pubKey); return mi; } public static String getBase64Enc(String message, String modulus, String public_exponent) throws Exception{ return Base64Utils.encode(BytesHexUtlis.hexStringToBytes(getHexEnc(message, modulus, public_exponent))); } }
false
1,896
16
2,052
16
2,210
15
2,052
16
2,437
20
false
false
false
false
false
true
45989_34
package com.jw.tree; /** * 线索化二叉树: * 1. n 个节点的二叉链表含有 n+1 个空指针(n-1条连接线),(2n - (n-1))= n+1;也就是说每个节点都是单线联系 * 2. 该空指针指向该节点按照某种遍历次序的前驱或后继节点;这种附加指针 --> 线索 * 1. 某种遍历次序:前序、中序、后序;按照此顺序,节点分为 前驱 / 后继 节点;节点同时还有 左子树 / 右子树 节点,要注意区分 * * 扩展:使用前序、后序线索化二叉树?? */ public class ThreadedBinaryTreeTest { public static void main(String[] args) { ThreadedBinaryTree threadedBinaryTree = new ThreadedBinaryTree(); HeroNode2 root = new HeroNode2(1, "tom"); HeroNode2 node2 = new HeroNode2(3, "jack"); HeroNode2 node3 = new HeroNode2(6, "smith"); HeroNode2 node4 = new HeroNode2(8, "mary"); HeroNode2 node5 = new HeroNode2(10, "kind"); HeroNode2 node6 = new HeroNode2(14, "dim"); threadedBinaryTree.setRoot(root); root.setLeft(node2); root.setRight(node3); node2.setLeft(node4); node2.setRight(node5); node3.setLeft(node6); //threadedBinaryTree.preOrder();//1,3,8,10,6,14 //threadedBinaryTree.infixOrder();//8,3,10,1,14,6 //threadedBinaryTree.postOrder();//8,10,3,14,6,1 //threadedBinaryTree.threadedNodes_pre(root); //threadedBinaryTree.threadedNodes_Infix(root); // // System.out.println(node5.getLeft()); // System.out.println(node5.getRight()); // System.out.println(node5.getLeftType()); // System.out.println(node5.getRightType()); // threadedBinaryTree.threadedList(); } } class ThreadedBinaryTree{ private HeroNode2 root; private HeroNode2 pre = null; public void setRoot(HeroNode2 root) { this.root = root; } //中序遍历次序来线索化节点 public void threadedNodes_Infix(HeroNode2 node){ if (node == null) { return; } threadedNodes_Infix(node.getLeft());//线索化左子树 //处理当前节点的前驱节点 if (node.getLeft() == null) { node.setLeft(pre); node.setLeftType(1);//存储前驱 } //处理前驱节点的后继节点 if (pre != null && pre.getRight() == null) { pre.setRight(node);//让前驱节点的右指针指向当前节点 pre.setRightType(1); } pre = node; threadedNodes_Infix(node.getRight());//线索化右子树 } //前序遍历次序来线索化节点; 1,3,8,10,6,14 // public void threadedNodes_pre(HeroNode2 node){ // if (node == null) { // return; // } // // //前序:先处理当前节点的前驱节点 // if (node.getLeft() == null) { // node.setLeft(pre); // node.setLeftType(1);//存储前驱 // } // // //处理前驱节点的后继节点 // if (node.getRight() == null) { // pre.setRight(node);//让前驱节点的右指针指向当前节点 // pre.setRightType(1); // } // // pre = node; // // threadedNodes_pre(node.getLeft());//线索化左子树 // threadedNodes_pre(node.getRight());//线索化右子树 // } /** * 线索化二叉树遍历:遍历结果的节点顺序 取决于 线索化时的构造顺序 * */ public void threadedList(){ HeroNode2 node = root; while (node != null){ //向左遍历找到getLeftType() == 1的节点, 说明是按照线索化后的有效节点 while (node.getLeftType() == 0){ node = node.getLeft(); } System.out.println(node);//输出当前节点 while (node.getRightType() == 1){ node = node.getRight(); System.out.println(node); } node = node.getRight(); } } public void preOrder(){ if (this.root == null) { System.out.println("树为空,无法遍历!"); }else { this.root.preOrder(); } } public void infixOrder(){ if (this.root == null) { System.out.println("树为空,无法遍历!"); }else { this.root.infixOrder(); } } public void postOrder(){ if (this.root == null) { System.out.println("树为空,无法遍历!"); }else { this.root.postOrder(); } } public HeroNode2 preOrderSearch(int no){ if (root != null) { return root.preOrderSearch(no); }else{ return null; } } //中序查找 public HeroNode2 infixOrderSearch(int no){ if (root != null) { return root.infixOrderSearch(no); }else{ return null; } } //后序查找 public HeroNode2 postOrderSearch(int no){ if (root != null) { return root.postOrderSearch(no); }else{ return null; } } } class HeroNode2{ private int id; private String name; private HeroNode2 left; private HeroNode2 right; private int leftType;//0:指向左子树 1: 指向前驱 private int rightType;//0:指向右子树 1: 指向后继 public int getLeftType() { return leftType; } public void setLeftType(int leftType) { this.leftType = leftType; } public int getRightType() { return rightType; } public void setRightType(int rightType) { this.rightType = rightType; } public HeroNode2(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HeroNode2 getLeft() { return left; } public void setLeft(HeroNode2 left) { this.left = left; } public HeroNode2 getRight() { return right; } public void setRight(HeroNode2 right) { this.right = right; } @Override public String toString() { return "HeroNode{" + "id=" + id + ", name='" + name + '\'' + '}'; } //前序遍历 public void preOrder(){ System.out.println(this); if (this.left != null) { this.left.preOrder(); } if (this.right != null) { this.right.preOrder(); } } //中序遍历 public void infixOrder(){ if (this.left != null) { this.left.infixOrder(); } System.out.println(this); if (this.right != null) { this.right.infixOrder(); } } //后序遍历 public void postOrder(){ if (this.left != null) { this.left.postOrder(); } if (this.right != null) { this.right.postOrder(); } System.out.println(this); } //前序查找 /** * * @param no 要查找的英雄no * @return 找到返回英雄节点,没找到返回null */ public HeroNode2 preOrderSearch(int no){ if (no == this.id) { return this; } HeroNode2 tempNode = null; if (this.left != null) { tempNode = this.left.preOrderSearch(no); } if (tempNode != null) { return tempNode; } if (this.right != null) { tempNode = this.right.preOrderSearch(no); } if (tempNode != null) { return tempNode; } return tempNode; } //中序查找 public HeroNode2 infixOrderSearch(int no){ HeroNode2 tempNode = null; if (this.left != null) { tempNode = this.left.infixOrderSearch(no); } if (tempNode != null) { return tempNode; } if (no == this.id) { return this; } if (this.right != null) { tempNode = this.right.infixOrderSearch(no); } if (tempNode != null) { return tempNode; } return tempNode; } //后序查找 public HeroNode2 postOrderSearch(int no){ HeroNode2 tempNode = null; if (this.left != null) { tempNode = this.left.postOrderSearch(no); } if (tempNode != null) { return tempNode; } if (this.right != null) { tempNode = this.right.postOrderSearch(no); } if (tempNode != null) { return tempNode; } if (no == this.id) { return this; } return tempNode; } }
WeiJinCA/Java
DataStructure/src/com/jw/tree/ThreadedBinaryTreeTest.java
2,433
//输出当前节点
line_comment
zh-cn
package com.jw.tree; /** * 线索化二叉树: * 1. n 个节点的二叉链表含有 n+1 个空指针(n-1条连接线),(2n - (n-1))= n+1;也就是说每个节点都是单线联系 * 2. 该空指针指向该节点按照某种遍历次序的前驱或后继节点;这种附加指针 --> 线索 * 1. 某种遍历次序:前序、中序、后序;按照此顺序,节点分为 前驱 / 后继 节点;节点同时还有 左子树 / 右子树 节点,要注意区分 * * 扩展:使用前序、后序线索化二叉树?? */ public class ThreadedBinaryTreeTest { public static void main(String[] args) { ThreadedBinaryTree threadedBinaryTree = new ThreadedBinaryTree(); HeroNode2 root = new HeroNode2(1, "tom"); HeroNode2 node2 = new HeroNode2(3, "jack"); HeroNode2 node3 = new HeroNode2(6, "smith"); HeroNode2 node4 = new HeroNode2(8, "mary"); HeroNode2 node5 = new HeroNode2(10, "kind"); HeroNode2 node6 = new HeroNode2(14, "dim"); threadedBinaryTree.setRoot(root); root.setLeft(node2); root.setRight(node3); node2.setLeft(node4); node2.setRight(node5); node3.setLeft(node6); //threadedBinaryTree.preOrder();//1,3,8,10,6,14 //threadedBinaryTree.infixOrder();//8,3,10,1,14,6 //threadedBinaryTree.postOrder();//8,10,3,14,6,1 //threadedBinaryTree.threadedNodes_pre(root); //threadedBinaryTree.threadedNodes_Infix(root); // // System.out.println(node5.getLeft()); // System.out.println(node5.getRight()); // System.out.println(node5.getLeftType()); // System.out.println(node5.getRightType()); // threadedBinaryTree.threadedList(); } } class ThreadedBinaryTree{ private HeroNode2 root; private HeroNode2 pre = null; public void setRoot(HeroNode2 root) { this.root = root; } //中序遍历次序来线索化节点 public void threadedNodes_Infix(HeroNode2 node){ if (node == null) { return; } threadedNodes_Infix(node.getLeft());//线索化左子树 //处理当前节点的前驱节点 if (node.getLeft() == null) { node.setLeft(pre); node.setLeftType(1);//存储前驱 } //处理前驱节点的后继节点 if (pre != null && pre.getRight() == null) { pre.setRight(node);//让前驱节点的右指针指向当前节点 pre.setRightType(1); } pre = node; threadedNodes_Infix(node.getRight());//线索化右子树 } //前序遍历次序来线索化节点; 1,3,8,10,6,14 // public void threadedNodes_pre(HeroNode2 node){ // if (node == null) { // return; // } // // //前序:先处理当前节点的前驱节点 // if (node.getLeft() == null) { // node.setLeft(pre); // node.setLeftType(1);//存储前驱 // } // // //处理前驱节点的后继节点 // if (node.getRight() == null) { // pre.setRight(node);//让前驱节点的右指针指向当前节点 // pre.setRightType(1); // } // // pre = node; // // threadedNodes_pre(node.getLeft());//线索化左子树 // threadedNodes_pre(node.getRight());//线索化右子树 // } /** * 线索化二叉树遍历:遍历结果的节点顺序 取决于 线索化时的构造顺序 * */ public void threadedList(){ HeroNode2 node = root; while (node != null){ //向左遍历找到getLeftType() == 1的节点, 说明是按照线索化后的有效节点 while (node.getLeftType() == 0){ node = node.getLeft(); } System.out.println(node);//输出 <SUF> while (node.getRightType() == 1){ node = node.getRight(); System.out.println(node); } node = node.getRight(); } } public void preOrder(){ if (this.root == null) { System.out.println("树为空,无法遍历!"); }else { this.root.preOrder(); } } public void infixOrder(){ if (this.root == null) { System.out.println("树为空,无法遍历!"); }else { this.root.infixOrder(); } } public void postOrder(){ if (this.root == null) { System.out.println("树为空,无法遍历!"); }else { this.root.postOrder(); } } public HeroNode2 preOrderSearch(int no){ if (root != null) { return root.preOrderSearch(no); }else{ return null; } } //中序查找 public HeroNode2 infixOrderSearch(int no){ if (root != null) { return root.infixOrderSearch(no); }else{ return null; } } //后序查找 public HeroNode2 postOrderSearch(int no){ if (root != null) { return root.postOrderSearch(no); }else{ return null; } } } class HeroNode2{ private int id; private String name; private HeroNode2 left; private HeroNode2 right; private int leftType;//0:指向左子树 1: 指向前驱 private int rightType;//0:指向右子树 1: 指向后继 public int getLeftType() { return leftType; } public void setLeftType(int leftType) { this.leftType = leftType; } public int getRightType() { return rightType; } public void setRightType(int rightType) { this.rightType = rightType; } public HeroNode2(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HeroNode2 getLeft() { return left; } public void setLeft(HeroNode2 left) { this.left = left; } public HeroNode2 getRight() { return right; } public void setRight(HeroNode2 right) { this.right = right; } @Override public String toString() { return "HeroNode{" + "id=" + id + ", name='" + name + '\'' + '}'; } //前序遍历 public void preOrder(){ System.out.println(this); if (this.left != null) { this.left.preOrder(); } if (this.right != null) { this.right.preOrder(); } } //中序遍历 public void infixOrder(){ if (this.left != null) { this.left.infixOrder(); } System.out.println(this); if (this.right != null) { this.right.infixOrder(); } } //后序遍历 public void postOrder(){ if (this.left != null) { this.left.postOrder(); } if (this.right != null) { this.right.postOrder(); } System.out.println(this); } //前序查找 /** * * @param no 要查找的英雄no * @return 找到返回英雄节点,没找到返回null */ public HeroNode2 preOrderSearch(int no){ if (no == this.id) { return this; } HeroNode2 tempNode = null; if (this.left != null) { tempNode = this.left.preOrderSearch(no); } if (tempNode != null) { return tempNode; } if (this.right != null) { tempNode = this.right.preOrderSearch(no); } if (tempNode != null) { return tempNode; } return tempNode; } //中序查找 public HeroNode2 infixOrderSearch(int no){ HeroNode2 tempNode = null; if (this.left != null) { tempNode = this.left.infixOrderSearch(no); } if (tempNode != null) { return tempNode; } if (no == this.id) { return this; } if (this.right != null) { tempNode = this.right.infixOrderSearch(no); } if (tempNode != null) { return tempNode; } return tempNode; } //后序查找 public HeroNode2 postOrderSearch(int no){ HeroNode2 tempNode = null; if (this.left != null) { tempNode = this.left.postOrderSearch(no); } if (tempNode != null) { return tempNode; } if (this.right != null) { tempNode = this.right.postOrderSearch(no); } if (tempNode != null) { return tempNode; } if (no == this.id) { return this; } return tempNode; } }
false
2,245
4
2,433
4
2,587
4
2,433
4
3,069
7
false
false
false
false
false
true
31263_5
/* * @Author: Weidows * @Date: 2020-07-08 08:30:19 * @LastEditors: Weidows * @LastEditTime: 2021-10-12 13:54:16 * @FilePath: \Java\Java\src\main\java\demos\castle\castle\Game.java */ package demos.castle.castle; import java.util.Scanner; public class Game { private Room currentRoom; public Game() { createRooms(); } private void createRooms() { /** * 虽然可以直接把此函数做成构造函数,但考虑封装..还是让构造函数调用此函数比较好 */ //初始化房间 Room outside = new Room("城堡外"); Room lobby = new Room("大堂"); Room pub = new Room("酒吧"); Room study = new Room("书房"); Room bedroom = new Room("卧室"); currentRoom = outside; //从城堡门外开始 //初始化房间出口 outside.setExits(null, lobby, study, pub); lobby.setExits(null, null, null, outside); pub.setExits(null, outside, null, null); study.setExits(outside, bedroom, null, null); bedroom.setExits(null, null, null, study); } private void printWelcome() { System.out.println("\n欢迎来到城堡!\n这是一个超级无聊的游戏.\n如果需要帮助,请输入'help'.\n"); this.location(); } private void printHelp() { System.out.println("迷路了吗?你可以做的命令有:go,bye,help"); System.out.println("如:go east"); } private void location() { System.out.print("现在你在" + currentRoom + "出口有:"); // 判断出口 if (currentRoom.northExit != null) System.out.print("north\t"); if (currentRoom.southExit != null) System.out.print("south\t"); if (currentRoom.westExit != null) System.out.print("west\t"); if (currentRoom.eastExit != null) System.out.print("east\t"); System.out.println(); } private void goRoom(String direction) { // Room nextRoom = null; if (direction.equals("north") || direction.equals("south") || direction.equals("east") || direction.equals("west")) { if (direction.equals("north")) currentRoom = currentRoom.northExit; if (direction.equals("east")) currentRoom = currentRoom.eastExit; if (direction.equals("west")) currentRoom = currentRoom.westExit; if (direction.equals("south")) currentRoom = currentRoom.southExit; } else System.out.println("那里没有门!"); this.location(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); Game game = new Game(); game.printWelcome(); while (true) { System.out.print("输入动作:"); //短语分词(好方法) String line = in.nextLine(); //根据空格把line分成数组 String[] words = line.split(" "); if (words[0].equals("help")) game.printHelp(); else if (words[0].equals("go")) game.goRoom(words[1]); else if (words[0].equals("bye")) { System.out.println("感谢您的光临,再见!"); in.close(); break; } else System.out.println("输入错误!请重新输入."); } } }
Weidows/Java
Java/src/main/java/demos/castle/castle/Game.java
905
// 判断出口
line_comment
zh-cn
/* * @Author: Weidows * @Date: 2020-07-08 08:30:19 * @LastEditors: Weidows * @LastEditTime: 2021-10-12 13:54:16 * @FilePath: \Java\Java\src\main\java\demos\castle\castle\Game.java */ package demos.castle.castle; import java.util.Scanner; public class Game { private Room currentRoom; public Game() { createRooms(); } private void createRooms() { /** * 虽然可以直接把此函数做成构造函数,但考虑封装..还是让构造函数调用此函数比较好 */ //初始化房间 Room outside = new Room("城堡外"); Room lobby = new Room("大堂"); Room pub = new Room("酒吧"); Room study = new Room("书房"); Room bedroom = new Room("卧室"); currentRoom = outside; //从城堡门外开始 //初始化房间出口 outside.setExits(null, lobby, study, pub); lobby.setExits(null, null, null, outside); pub.setExits(null, outside, null, null); study.setExits(outside, bedroom, null, null); bedroom.setExits(null, null, null, study); } private void printWelcome() { System.out.println("\n欢迎来到城堡!\n这是一个超级无聊的游戏.\n如果需要帮助,请输入'help'.\n"); this.location(); } private void printHelp() { System.out.println("迷路了吗?你可以做的命令有:go,bye,help"); System.out.println("如:go east"); } private void location() { System.out.print("现在你在" + currentRoom + "出口有:"); // 判断 <SUF> if (currentRoom.northExit != null) System.out.print("north\t"); if (currentRoom.southExit != null) System.out.print("south\t"); if (currentRoom.westExit != null) System.out.print("west\t"); if (currentRoom.eastExit != null) System.out.print("east\t"); System.out.println(); } private void goRoom(String direction) { // Room nextRoom = null; if (direction.equals("north") || direction.equals("south") || direction.equals("east") || direction.equals("west")) { if (direction.equals("north")) currentRoom = currentRoom.northExit; if (direction.equals("east")) currentRoom = currentRoom.eastExit; if (direction.equals("west")) currentRoom = currentRoom.westExit; if (direction.equals("south")) currentRoom = currentRoom.southExit; } else System.out.println("那里没有门!"); this.location(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); Game game = new Game(); game.printWelcome(); while (true) { System.out.print("输入动作:"); //短语分词(好方法) String line = in.nextLine(); //根据空格把line分成数组 String[] words = line.split(" "); if (words[0].equals("help")) game.printHelp(); else if (words[0].equals("go")) game.goRoom(words[1]); else if (words[0].equals("bye")) { System.out.println("感谢您的光临,再见!"); in.close(); break; } else System.out.println("输入错误!请重新输入."); } } }
false
802
4
905
4
938
3
905
4
1,142
6
false
false
false
false
false
true
25041_5
package dp;/** * @author Weiyan Xiang on 2021/1/20 */ import java.util.ArrayList; import java.util.List; /** * http://www.matrix67.com/blog/archives/266 * <p> * Gray码 假如我有4个潜在的GF,我需要决定最终到底和谁在一起。一个简单的办法就是,依次和每个MM交往一段时间,最后选择给我带来的“满意度”最大的MM。但看了dd牛的理论后,事情开始变得复杂了:我可以选择和多个MM在一起。这样,需要考核的状态变成了2^4=16种(当然包括0000这一状态,因为我有可能是玻璃)。现在的问题就是,我应该用什么顺序来遍历这16种状态呢? * 传统的做法是,用二进制数的顺序来遍历所有可能的组合。也就是说,我需要以0000->0001->0010->0011->0100->…->1111这样的顺序对每种状态进行测试。这个顺序很不科学,很多时候状态的转移都很耗时。比如从0111到1000时我需要暂时甩掉当前所有的3个MM,然后去把第4个MM。同时改变所有MM与我的关系是一件何等巨大的工程啊。因此,我希望知道,是否有一种方法可以使得,从没有MM这一状态出发,每次只改变我和一个MM的关系(追或者甩),15次操作后恰好遍历完所有可能的组合(最终状态不一定是1111)。大家自己先试一试看行不行。 * 解决这个问题的方法很巧妙。我们来说明,假如我们已经知道了n=2时的合法遍历顺序,我们如何得到n=3的遍历顺序。显然,n=2的遍历顺序如下: * <p> * 00 01 11 10 * <p> * 你可能已经想到了如何把上面的遍历顺序扩展到n=3的情况。n=3时一共有8种状态,其中前面4个把n=2的遍历顺序照搬下来,然后把它们对称翻折下去并在最前面加上1作为后面4个状态: * <p> * 000 001 011 010 ↑ ——– 110 ↓ 111 101 100 * <p> * 用这种方法得到的遍历顺序显然符合要求。首先,上面8个状态恰好是n=3时的所有8种组合,因为它们是在n=2的全部四种组合的基础上考虑选不选第3个元素所得到的。然后我们看到,后面一半的状态应该和前面一半一样满足“相邻状态间仅一位不同”的限制,而“镜面”处则是最前面那一位数不同。再次翻折三阶遍历顺序,我们就得到了刚才的问题的答案: * <p> * 0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 * <p> * 这种遍历顺序作为一种编码方式存在,叫做Gray码(写个中文让蜘蛛来抓:格雷码)。它的应用范围很广。比如,n阶的Gray码相当于在n维立方体上的Hamilton回路,因为沿着立方体上的边走一步,n维坐标中只会有一个值改变。再比如,Gray码和Hanoi塔问题等价。Gray码改变的是第几个数,Hanoi塔就该移动哪个盘子。比如,3阶的Gray码每次改变的元素所在位置依次为1-2-1-3-1-2-1,这正好是3阶Hanoi塔每次移动盘子编号。如果我们可以快速求出Gray码的第n个数是多少,我们就可以输出任意步数后Hanoi塔的移动步骤。现在我告诉你,Gray码的第n个数(从0算起)是n * xor (n shr 1),你能想出来这是为什么吗?先自己想想吧。 */ public class GrayCode { /** * 89. Gray Code * <p> * https://leetcode.com/problems/gray-code/ * <p> * upvoted ans */ public List<Integer> grayCode(int n) { List<Integer> ans = new ArrayList<>(); ans.add(0); for (int i = 0; i < n; i++) { int len = ans.size(); // why from len-1? because i.e. 0,1,3,2, next must be flip 1 digits so we take 3 (11) to flip for (int j = len - 1; j >= 0; j--) { // put a "1" in the "head" of the old number. (e.g. make "101" to be 1101 (101 | 1000 == 1101)) /** * 00 * 01 * 11 * 10 * * 你可能已经想到了如何把上面的遍历顺序扩展到n=3的情况。n=3时一共有8种状态,其中前面4个把n=2的遍历顺序照搬下来, * 然后把它们对称翻折下去并在最前面加上1作为后面4个状态: * * 0k开头的就是前面循环的答案,所以每次 1<<i 即可 * 000 * 001 * 011 * 010 ↑ * ——– * 110 ↓ * 111 * 101 * 100 */ ans.add(ans.get(j) | 1 << i); } } return ans; } }
WeiyanXiang/algorithm-study
src/main/java/dp/GrayCode.java
1,531
/** * 00 * 01 * 11 * 10 * * 你可能已经想到了如何把上面的遍历顺序扩展到n=3的情况。n=3时一共有8种状态,其中前面4个把n=2的遍历顺序照搬下来, * 然后把它们对称翻折下去并在最前面加上1作为后面4个状态: * * 0k开头的就是前面循环的答案,所以每次 1<<i 即可 * 000 * 001 * 011 * 010 ↑ * ——– * 110 ↓ * 111 * 101 * 100 */
block_comment
zh-cn
package dp;/** * @author Weiyan Xiang on 2021/1/20 */ import java.util.ArrayList; import java.util.List; /** * http://www.matrix67.com/blog/archives/266 * <p> * Gray码 假如我有4个潜在的GF,我需要决定最终到底和谁在一起。一个简单的办法就是,依次和每个MM交往一段时间,最后选择给我带来的“满意度”最大的MM。但看了dd牛的理论后,事情开始变得复杂了:我可以选择和多个MM在一起。这样,需要考核的状态变成了2^4=16种(当然包括0000这一状态,因为我有可能是玻璃)。现在的问题就是,我应该用什么顺序来遍历这16种状态呢? * 传统的做法是,用二进制数的顺序来遍历所有可能的组合。也就是说,我需要以0000->0001->0010->0011->0100->…->1111这样的顺序对每种状态进行测试。这个顺序很不科学,很多时候状态的转移都很耗时。比如从0111到1000时我需要暂时甩掉当前所有的3个MM,然后去把第4个MM。同时改变所有MM与我的关系是一件何等巨大的工程啊。因此,我希望知道,是否有一种方法可以使得,从没有MM这一状态出发,每次只改变我和一个MM的关系(追或者甩),15次操作后恰好遍历完所有可能的组合(最终状态不一定是1111)。大家自己先试一试看行不行。 * 解决这个问题的方法很巧妙。我们来说明,假如我们已经知道了n=2时的合法遍历顺序,我们如何得到n=3的遍历顺序。显然,n=2的遍历顺序如下: * <p> * 00 01 11 10 * <p> * 你可能已经想到了如何把上面的遍历顺序扩展到n=3的情况。n=3时一共有8种状态,其中前面4个把n=2的遍历顺序照搬下来,然后把它们对称翻折下去并在最前面加上1作为后面4个状态: * <p> * 000 001 011 010 ↑ ——– 110 ↓ 111 101 100 * <p> * 用这种方法得到的遍历顺序显然符合要求。首先,上面8个状态恰好是n=3时的所有8种组合,因为它们是在n=2的全部四种组合的基础上考虑选不选第3个元素所得到的。然后我们看到,后面一半的状态应该和前面一半一样满足“相邻状态间仅一位不同”的限制,而“镜面”处则是最前面那一位数不同。再次翻折三阶遍历顺序,我们就得到了刚才的问题的答案: * <p> * 0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 * <p> * 这种遍历顺序作为一种编码方式存在,叫做Gray码(写个中文让蜘蛛来抓:格雷码)。它的应用范围很广。比如,n阶的Gray码相当于在n维立方体上的Hamilton回路,因为沿着立方体上的边走一步,n维坐标中只会有一个值改变。再比如,Gray码和Hanoi塔问题等价。Gray码改变的是第几个数,Hanoi塔就该移动哪个盘子。比如,3阶的Gray码每次改变的元素所在位置依次为1-2-1-3-1-2-1,这正好是3阶Hanoi塔每次移动盘子编号。如果我们可以快速求出Gray码的第n个数是多少,我们就可以输出任意步数后Hanoi塔的移动步骤。现在我告诉你,Gray码的第n个数(从0算起)是n * xor (n shr 1),你能想出来这是为什么吗?先自己想想吧。 */ public class GrayCode { /** * 89. Gray Code * <p> * https://leetcode.com/problems/gray-code/ * <p> * upvoted ans */ public List<Integer> grayCode(int n) { List<Integer> ans = new ArrayList<>(); ans.add(0); for (int i = 0; i < n; i++) { int len = ans.size(); // why from len-1? because i.e. 0,1,3,2, next must be flip 1 digits so we take 3 (11) to flip for (int j = len - 1; j >= 0; j--) { // put a "1" in the "head" of the old number. (e.g. make "101" to be 1101 (101 | 1000 == 1101)) /** * 00 <SUF>*/ ans.add(ans.get(j) | 1 << i); } } return ans; } }
false
1,368
189
1,531
189
1,411
187
1,531
189
2,139
268
false
false
false
false
false
true
52877_3
/* * Copyright (c) 2019. zhengweiyi.cn all rights reserved * 郑维一版权所有,未经授权禁止使用,开源项目请遵守指定的开源协议 */ package cn.zhengweiyi.weiyichild.bean; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Keep; import java.util.Date; @Entity(nameInDb = "dietary_list") public class Dietary { @Id(autoincrement = true) private Long id; // id private Date date; // 食谱对应日期 private int sequence; // 序号 private String name; // 餐名,如“早餐” private String foods; // 具体食物名称 @Keep public Dietary(Date date, int sequence, String name, String foods) { this.date = date; this.sequence = sequence; this.name = name; this.foods = foods; } @Generated(hash = 1630206678) public Dietary(Long id, Date date, int sequence, String name, String foods) { this.id = id; this.date = date; this.sequence = sequence; this.name = name; this.foods = foods; } @Generated(hash = 2076241465) public Dietary() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } public int getSequence() { return this.sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getFoods() { return this.foods; } public void setFoods(String foods) { this.foods = foods; } }
Weiyi-C/WeiyiChild
app/src/main/java/cn/zhengweiyi/weiyichild/bean/Dietary.java
566
// 具体食物名称
line_comment
zh-cn
/* * Copyright (c) 2019. zhengweiyi.cn all rights reserved * 郑维一版权所有,未经授权禁止使用,开源项目请遵守指定的开源协议 */ package cn.zhengweiyi.weiyichild.bean; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Keep; import java.util.Date; @Entity(nameInDb = "dietary_list") public class Dietary { @Id(autoincrement = true) private Long id; // id private Date date; // 食谱对应日期 private int sequence; // 序号 private String name; // 餐名,如“早餐” private String foods; // 具体 <SUF> @Keep public Dietary(Date date, int sequence, String name, String foods) { this.date = date; this.sequence = sequence; this.name = name; this.foods = foods; } @Generated(hash = 1630206678) public Dietary(Long id, Date date, int sequence, String name, String foods) { this.id = id; this.date = date; this.sequence = sequence; this.name = name; this.foods = foods; } @Generated(hash = 2076241465) public Dietary() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } public int getSequence() { return this.sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getFoods() { return this.foods; } public void setFoods(String foods) { this.foods = foods; } }
false
487
6
566
6
579
5
566
6
689
10
false
false
false
false
false
true
13522_10
package com.gupaoedu.essearch.util; import java.text.DecimalFormat; import java.util.HashSet; import java.util.Random; import java.util.Set; /** * 生成随机数 * @author Tom * */ public class RandomUtil { private static Random random = new Random(); private static final char [] sexs = "男女".toCharArray(); private static final char [] wxNo = "abcdefghijklmnopqrstuvwxyz0123456789".toLowerCase().toCharArray(); private static final char [] firstName = "赵钱孙李周吴郑王冯陈卫蒋沈韩杨朱秦许何吕施张孔曹严金魏陶姜谢邹窦章苏潘葛范彭谭夏胡".toCharArray(); //确保车牌号不重复,声明一个缓存区 private static Set<String> wxNoCache; /** * 随机生成性别 * @return */ public static String randomSex(){ int i = random.nextInt(sexs.length); return ("" + sexs[i]); } /** * 随机生成车牌号 * @return */ public static String randomWxNo(){ //初始化缓冲区 openCache(); //微信号自动生成规则,wx_开头加上10位数字字组合 StringBuffer sb = new StringBuffer(); for(int c = 0;c < 10;c ++){ int i = random.nextInt(wxNo.length); sb.append(wxNo[i]); } String carNum = ("wx_" + sb.toString()); //为了防止微信号重复,生成以后检查一下 //如果重复,递归重新生成,直到不重复为止 if(wxNoCache.contains(carNum)){ return randomWxNo(); } wxNoCache.add(carNum); return carNum; } /** * 随机生成坐标 */ public static double[] randomPoint(double myLat,double myLon){ double min = 0.000001;//坐标范围,最小1米 double max = 0.00002;//坐标范围,最大1000米 //随机生成一组长沙附近的坐标 double s = random.nextDouble() % (max - min + 1) + max; //格式化保留6位小数 DecimalFormat df = new DecimalFormat("######0.000000"); String slon = df.format(s + myLon); String slat = df.format(s + myLat); Double dlon = Double.valueOf(slon); Double dlat = Double.valueOf(slat); return new double []{dlat,dlon}; } /** * 随机生成司机姓名 * @return */ public static String randomNickName(String sex){ int i = random.nextInt(firstName.length); return firstName[i] + ("男".equals(sex) ? "先生" : "女士"); } /** * 开启缓存区 */ public static void openCache(){ if(wxNoCache == null){ wxNoCache = new HashSet<String>(); } } /** * 清空缓存区 */ public static void clearCache(){ wxNoCache = null; } }
WellsYuu/corresponding-auxiliary-data
系列2-综合源码/gupaoedu-es-search-nearby/src/main/java/com/gupaoedu/essearch/util/RandomUtil.java
859
//坐标范围,最大1000米
line_comment
zh-cn
package com.gupaoedu.essearch.util; import java.text.DecimalFormat; import java.util.HashSet; import java.util.Random; import java.util.Set; /** * 生成随机数 * @author Tom * */ public class RandomUtil { private static Random random = new Random(); private static final char [] sexs = "男女".toCharArray(); private static final char [] wxNo = "abcdefghijklmnopqrstuvwxyz0123456789".toLowerCase().toCharArray(); private static final char [] firstName = "赵钱孙李周吴郑王冯陈卫蒋沈韩杨朱秦许何吕施张孔曹严金魏陶姜谢邹窦章苏潘葛范彭谭夏胡".toCharArray(); //确保车牌号不重复,声明一个缓存区 private static Set<String> wxNoCache; /** * 随机生成性别 * @return */ public static String randomSex(){ int i = random.nextInt(sexs.length); return ("" + sexs[i]); } /** * 随机生成车牌号 * @return */ public static String randomWxNo(){ //初始化缓冲区 openCache(); //微信号自动生成规则,wx_开头加上10位数字字组合 StringBuffer sb = new StringBuffer(); for(int c = 0;c < 10;c ++){ int i = random.nextInt(wxNo.length); sb.append(wxNo[i]); } String carNum = ("wx_" + sb.toString()); //为了防止微信号重复,生成以后检查一下 //如果重复,递归重新生成,直到不重复为止 if(wxNoCache.contains(carNum)){ return randomWxNo(); } wxNoCache.add(carNum); return carNum; } /** * 随机生成坐标 */ public static double[] randomPoint(double myLat,double myLon){ double min = 0.000001;//坐标范围,最小1米 double max = 0.00002;//坐标 <SUF> //随机生成一组长沙附近的坐标 double s = random.nextDouble() % (max - min + 1) + max; //格式化保留6位小数 DecimalFormat df = new DecimalFormat("######0.000000"); String slon = df.format(s + myLon); String slat = df.format(s + myLat); Double dlon = Double.valueOf(slon); Double dlat = Double.valueOf(slat); return new double []{dlat,dlon}; } /** * 随机生成司机姓名 * @return */ public static String randomNickName(String sex){ int i = random.nextInt(firstName.length); return firstName[i] + ("男".equals(sex) ? "先生" : "女士"); } /** * 开启缓存区 */ public static void openCache(){ if(wxNoCache == null){ wxNoCache = new HashSet<String>(); } } /** * 清空缓存区 */ public static void clearCache(){ wxNoCache = null; } }
false
719
11
852
11
834
11
852
11
1,122
20
false
false
false
false
false
true
34927_2
package com.kevin.delegationadapter.sample.samedata.bean; import java.util.List; /** * Bill * * @author [email protected], Created on 2018-04-28 15:43:32 * Major Function:<b></b> * <p/> * 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!! * @author mender,Modified Date Modify Content: */ public class Bill { public String title = ""; // 标题 public String waiter = ""; // 服务员 public String cashier = ""; // 收银员 public int ramadhin = 0; // 桌号 public int guests = 0; // 客人数 public String beginTime = ""; // 开台时间 public String endTime = ""; // 结账时间 public String duration = ""; // 用餐时长 public List<Item> details = null; // 用餐详情 public String total = ""; // 合计 public String discounts = ""; // 优惠 public String receivable = ""; // 应收 public String describe = ""; // 描述信息 public static class Item { public String name = ""; // 名称 public String count = ""; // 数量 public String price = ""; // 单价 public String subtotal = "";// 小计 } }
WenkaiZhou/DelegationAdapter
sample/src/main/java/com/kevin/delegationadapter/sample/samedata/bean/Bill.java
360
// 收银员
line_comment
zh-cn
package com.kevin.delegationadapter.sample.samedata.bean; import java.util.List; /** * Bill * * @author [email protected], Created on 2018-04-28 15:43:32 * Major Function:<b></b> * <p/> * 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!! * @author mender,Modified Date Modify Content: */ public class Bill { public String title = ""; // 标题 public String waiter = ""; // 服务员 public String cashier = ""; // 收银 <SUF> public int ramadhin = 0; // 桌号 public int guests = 0; // 客人数 public String beginTime = ""; // 开台时间 public String endTime = ""; // 结账时间 public String duration = ""; // 用餐时长 public List<Item> details = null; // 用餐详情 public String total = ""; // 合计 public String discounts = ""; // 优惠 public String receivable = ""; // 应收 public String describe = ""; // 描述信息 public static class Item { public String name = ""; // 名称 public String count = ""; // 数量 public String price = ""; // 单价 public String subtotal = "";// 小计 } }
false
338
5
360
5
341
4
360
5
439
7
false
false
false
false
false
true
51129_3
package com.xm.coder.leetcode; import org.junit.jupiter.api.Test; import java.util.Arrays; /** * @auther xings * @email [email protected] * @description * @date 2021/7/30 11:00 上午 */ public class Order { /** * 冒泡排序 */ @Test public void bub() { int[] nums = {2, 3, 4, 5, 1}; int len = nums.length; for (int count = 1; count < len - 1; count++) { for (int i = 0; i < len - count; i++) { if (nums[i] < nums[i + 1]) { int temp = nums[i]; nums[i] = nums[i + 1]; nums[i + 1] = temp; } } } } /** * 选择排序 */ @Test public void sel() { int[] nums = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; int len = nums.length; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (nums[i] < nums[j]) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } } /** * 插入排序 */ @Test public void ins() { int[] nums = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; //将a[]按升序排列 int N = nums.length; for (int i = 1; i < N; i++) { //将a[i]插入到a[i-1],a[i-2],a[i-3]……之中 for (int j = i; j >= 1; j--) { if(nums[j - 1] > nums[j]){ int temp = nums[j]; nums[j] = nums[j - 1]; nums[j - 1] = temp; } } } } }
WhenCoding/coder-xiaoming
src/main/java/com/xm/coder/leetcode/Order.java
620
/** * 插入排序 */
block_comment
zh-cn
package com.xm.coder.leetcode; import org.junit.jupiter.api.Test; import java.util.Arrays; /** * @auther xings * @email [email protected] * @description * @date 2021/7/30 11:00 上午 */ public class Order { /** * 冒泡排序 */ @Test public void bub() { int[] nums = {2, 3, 4, 5, 1}; int len = nums.length; for (int count = 1; count < len - 1; count++) { for (int i = 0; i < len - count; i++) { if (nums[i] < nums[i + 1]) { int temp = nums[i]; nums[i] = nums[i + 1]; nums[i + 1] = temp; } } } } /** * 选择排序 */ @Test public void sel() { int[] nums = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; int len = nums.length; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (nums[i] < nums[j]) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } } /** * 插入排 <SUF>*/ @Test public void ins() { int[] nums = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; //将a[]按升序排列 int N = nums.length; for (int i = 1; i < N; i++) { //将a[i]插入到a[i-1],a[i-2],a[i-3]……之中 for (int j = i; j >= 1; j--) { if(nums[j - 1] > nums[j]){ int temp = nums[j]; nums[j] = nums[j - 1]; nums[j - 1] = temp; } } } } }
false
578
10
620
9
659
9
620
9
746
16
false
false
false
false
false
true
21495_1
// 一、打怪 // 你在玩儿游戏打怪兽,现在有两个怪兽,生命值分别是a和b,你有两个技能,一个是单体攻击技能,伤害是x。一个是群体攻击技能,伤害是y,给定a,b,x,y求使用最少几个技能可以杀死两个怪兽。 // 输入5 3 3 2 // 输出3 import java.util.*; public class WY1 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { int a = input.nextInt(); int b = input.nextInt(); int x = input.nextInt(); int y = input.nextInt(); //如果y >= x,肯定直接选用群体攻击方式 if(x <= y) { int maxBlood = Math.max(a, b); int res = (maxBlood - 1) / y + 1; System.out.println(res); } else if(x <= y * 2) { //如果x <= y * 2,也就是说群体攻击伤害值加起来比x大,优先使用群体攻击,直到一个怪物死亡,再使用单体攻击攻击另一个怪物 int res = 0; while(a > 0 && b > 0) { a -= y; b -= y; res += 1; } if(a > 0 || b > 0) { res += 1; } System.out.println(res); } else { //单体攻击伤害值比群体攻击一共的伤害值还要高,优先使用单体攻击,将每个怪物的生命值打到小于等于y的时候,在使用一个群体攻击直接一起带走 int res = 0; while(a > y) { a -= x; res += 1; } while(b > y) { b -= x; res += 1; } if(a > 0 || b > 0) { res += 1; } System.out.println(res); } } } }
Whiskeyi/algorithm
WY1.java
541
// 你在玩儿游戏打怪兽,现在有两个怪兽,生命值分别是a和b,你有两个技能,一个是单体攻击技能,伤害是x。一个是群体攻击技能,伤害是y,给定a,b,x,y求使用最少几个技能可以杀死两个怪兽。
line_comment
zh-cn
// 一、打怪 // 你在 <SUF> // 输入5 3 3 2 // 输出3 import java.util.*; public class WY1 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { int a = input.nextInt(); int b = input.nextInt(); int x = input.nextInt(); int y = input.nextInt(); //如果y >= x,肯定直接选用群体攻击方式 if(x <= y) { int maxBlood = Math.max(a, b); int res = (maxBlood - 1) / y + 1; System.out.println(res); } else if(x <= y * 2) { //如果x <= y * 2,也就是说群体攻击伤害值加起来比x大,优先使用群体攻击,直到一个怪物死亡,再使用单体攻击攻击另一个怪物 int res = 0; while(a > 0 && b > 0) { a -= y; b -= y; res += 1; } if(a > 0 || b > 0) { res += 1; } System.out.println(res); } else { //单体攻击伤害值比群体攻击一共的伤害值还要高,优先使用单体攻击,将每个怪物的生命值打到小于等于y的时候,在使用一个群体攻击直接一起带走 int res = 0; while(a > y) { a -= x; res += 1; } while(b > y) { b -= x; res += 1; } if(a > 0 || b > 0) { res += 1; } System.out.println(res); } } } }
false
443
62
541
90
515
66
541
90
698
126
false
false
false
false
false
true
39469_9
package com.whitemagic2014.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * @Description: string-> 对象 获得锁对象 * @author: magic chen * @date: 2020/8/22 22:33 **/ public class MagicLock { private static final Map<String, Object> forLock = new ConcurrentHashMap<>(); private static final Map<String, Object> forPrivateLock = new ConcurrentHashMap<>(); private static final Map<String, ReentrantLock> forLockRemoveable = new ConcurrentHashMap<>(); /** * @Name: getLock * @Description: 获得锁对象 配合 synchronized 使用, 这个锁有缺陷,不能释放锁占用的内存 * @Param: lockKey * @Return: java.lang.Object * @Author: magic chen * @Date: 2020/8/22 22:35 **/ public static Object getLock(String lockKey) { Object lock = forLock.putIfAbsent(lockKey, new Object()); if (null == lock) { lock = forLock.get(lockKey); } return lock; } //##### 一个很酷炫的 锁 #### /** * @Name: getPrivateLock * @Description: 拿锁 :为每一个线程提供不同的 唯一锁 * @Param: lockKey * @Return: java.lang.Object * @Author: magic chen * @Date: 2020/8/22 22:35 **/ public static Object getPrivateLock(String lockKey) { return new Object(); } /** * @Name: waitLock * @Description: 等锁 :如果map中有其他锁存在,则表明有其他线程在锁这个key,等其他线程的锁被释放,将自己的锁放入map * @Param: lockKey * @Param: lock * @Return: void * @Author: magic chen * @Date: 2020/8/22 22:35 **/ public static void waitLock(String lockKey, Object lock) { Object oldLock = null; while ((oldLock = forPrivateLock.putIfAbsent(lockKey, lock)) != null) { synchronized (oldLock) { // nothing to do,but need; } } } /** * @Name: removePrivateLock * @Description: 释放锁 * @Param: lockKey * @Param: object * @Return: void * @Author: magic chen * @Date: 2020/8/22 22:36 **/ public static void removePrivateLock(String lockKey, Object object) { forPrivateLock.remove(lockKey, object); } /** * @Name: busniessSimulator * @Description: 酷炫锁使用方法业务模板 * @Param: * @Return: void * @Author: magic chen * @Date: 2020/8/22 22:36 **/ private void busniessSimulator() { String lockKey = "";//先搞到key Object lock = MagicLock.getPrivateLock(lockKey);// 获得 属于本线程 的唯一锁 MagicLock.waitLock(lockKey, lock);//等锁 synchronized (lock) { try { // 业务 } catch (Exception e) { // 如果业务中用了事务,为了让事务生效,则要抛出RuntimeException e.printStackTrace(); throw new RuntimeException(); } finally { MagicLock.removePrivateLock(lockKey, lock); } } } //##### 酷炫锁结束 #### // ###### 公平重入锁 ##### /** * @Name: getLockRemoveable * @Description: 获得Removeable锁对象 单独使用 记得try - finally unlock * @Param: lockKey * @Return: 一个公平的重入锁 ReentrantLock * @Author: magic chen * @Date: 2020/8/22 22:37 **/ public static ReentrantLock getLockRemoveable(String lockKey) { ReentrantLock lock = forLockRemoveable.putIfAbsent(lockKey, new ReentrantLock(true)); if (null == lock) { lock = forLockRemoveable.get(lockKey); } return lock; } /** * @Name: remove * @Description: 释放Removeable锁占用的内存 * @Param: lockkey * @Author: magic chen * @Date: 2020/8/22 22:38 **/ public static void remove(String lockkey) { if (forLockRemoveable.containsKey(lockkey) && !forLockRemoveable.get(lockkey).hasQueuedThreads() && !forLockRemoveable.get(lockkey).isLocked()) { forLockRemoveable.remove(lockkey); } } /** * @Name: clear * @Description: 对所有的Removeable 锁对象清理 * @Author: magic chen * @Date: 2020/8/22 22:38 **/ public static void clear() { for (String lockkey : forLockRemoveable.keySet()) { if (!forLockRemoveable.get(lockkey).hasQueuedThreads() && !forLockRemoveable.get(lockkey).isLocked()) { forLockRemoveable.remove(lockkey); } } } // ###### 公平重入锁 结束 ##### }
WhiteMagic2014/WMagicBotR
src/main/java/com/whitemagic2014/util/MagicLock.java
1,331
// 获得 属于本线程 的唯一锁
line_comment
zh-cn
package com.whitemagic2014.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * @Description: string-> 对象 获得锁对象 * @author: magic chen * @date: 2020/8/22 22:33 **/ public class MagicLock { private static final Map<String, Object> forLock = new ConcurrentHashMap<>(); private static final Map<String, Object> forPrivateLock = new ConcurrentHashMap<>(); private static final Map<String, ReentrantLock> forLockRemoveable = new ConcurrentHashMap<>(); /** * @Name: getLock * @Description: 获得锁对象 配合 synchronized 使用, 这个锁有缺陷,不能释放锁占用的内存 * @Param: lockKey * @Return: java.lang.Object * @Author: magic chen * @Date: 2020/8/22 22:35 **/ public static Object getLock(String lockKey) { Object lock = forLock.putIfAbsent(lockKey, new Object()); if (null == lock) { lock = forLock.get(lockKey); } return lock; } //##### 一个很酷炫的 锁 #### /** * @Name: getPrivateLock * @Description: 拿锁 :为每一个线程提供不同的 唯一锁 * @Param: lockKey * @Return: java.lang.Object * @Author: magic chen * @Date: 2020/8/22 22:35 **/ public static Object getPrivateLock(String lockKey) { return new Object(); } /** * @Name: waitLock * @Description: 等锁 :如果map中有其他锁存在,则表明有其他线程在锁这个key,等其他线程的锁被释放,将自己的锁放入map * @Param: lockKey * @Param: lock * @Return: void * @Author: magic chen * @Date: 2020/8/22 22:35 **/ public static void waitLock(String lockKey, Object lock) { Object oldLock = null; while ((oldLock = forPrivateLock.putIfAbsent(lockKey, lock)) != null) { synchronized (oldLock) { // nothing to do,but need; } } } /** * @Name: removePrivateLock * @Description: 释放锁 * @Param: lockKey * @Param: object * @Return: void * @Author: magic chen * @Date: 2020/8/22 22:36 **/ public static void removePrivateLock(String lockKey, Object object) { forPrivateLock.remove(lockKey, object); } /** * @Name: busniessSimulator * @Description: 酷炫锁使用方法业务模板 * @Param: * @Return: void * @Author: magic chen * @Date: 2020/8/22 22:36 **/ private void busniessSimulator() { String lockKey = "";//先搞到key Object lock = MagicLock.getPrivateLock(lockKey);// 获得 <SUF> MagicLock.waitLock(lockKey, lock);//等锁 synchronized (lock) { try { // 业务 } catch (Exception e) { // 如果业务中用了事务,为了让事务生效,则要抛出RuntimeException e.printStackTrace(); throw new RuntimeException(); } finally { MagicLock.removePrivateLock(lockKey, lock); } } } //##### 酷炫锁结束 #### // ###### 公平重入锁 ##### /** * @Name: getLockRemoveable * @Description: 获得Removeable锁对象 单独使用 记得try - finally unlock * @Param: lockKey * @Return: 一个公平的重入锁 ReentrantLock * @Author: magic chen * @Date: 2020/8/22 22:37 **/ public static ReentrantLock getLockRemoveable(String lockKey) { ReentrantLock lock = forLockRemoveable.putIfAbsent(lockKey, new ReentrantLock(true)); if (null == lock) { lock = forLockRemoveable.get(lockKey); } return lock; } /** * @Name: remove * @Description: 释放Removeable锁占用的内存 * @Param: lockkey * @Author: magic chen * @Date: 2020/8/22 22:38 **/ public static void remove(String lockkey) { if (forLockRemoveable.containsKey(lockkey) && !forLockRemoveable.get(lockkey).hasQueuedThreads() && !forLockRemoveable.get(lockkey).isLocked()) { forLockRemoveable.remove(lockkey); } } /** * @Name: clear * @Description: 对所有的Removeable 锁对象清理 * @Author: magic chen * @Date: 2020/8/22 22:38 **/ public static void clear() { for (String lockkey : forLockRemoveable.keySet()) { if (!forLockRemoveable.get(lockkey).hasQueuedThreads() && !forLockRemoveable.get(lockkey).isLocked()) { forLockRemoveable.remove(lockkey); } } } // ###### 公平重入锁 结束 ##### }
false
1,311
13
1,331
11
1,400
9
1,331
11
1,670
19
false
false
false
false
false
true
34008_3
package model; import java.awt.*; import java.util.Random; public class Tank implements AttackCallable { private final int tankType; private final Random random; private final long[] propTime; private int x; private int y; private int dir; private int hp; private int bulletType; private boolean isAlive; private int speed; private MyPanel myPanel; private long lastFireTime; private String[] img; // 传入的是 敌人、玩家 public Tank(int tankType, MyPanel myPanel, int x, int y) { this.setX(x); this.setY(y); this.hp = Const.MAX_HP; this.isAlive = true; this.tankType = tankType; this.setMyPanel(myPanel); this.random = new Random(); this.setLastFireTime(System.currentTimeMillis()); propTime = new long[]{0, 0, 0}; } public void move() { if (canMove()) { switch (this.dir) { case Const.UP -> this.setY(this.getY() - speed); case Const.DOWN -> this.setY(this.getY() + speed); case Const.LEFT -> this.setX(this.getX() - speed); case Const.RIGHT -> this.setX(this.getX() + speed); } } } /** * 等待被重写 * * @return true or false */ public boolean canMove() { return false; } public void fire() { if (canFire()) { addBullet(); } } /** * 是否可以发射子弹,对于不同的子类需要重写 * * @return true 可以 false 不可以 */ public boolean canFire() { return false; } public void addBullet() { int x = this.getX(); int y = this.getY(); switch (this.getDir()) { case Const.UP -> { x += Const.WIDTH; y -= Const.WIDTH; } case Const.DOWN -> { x += Const.WIDTH; y += Const.TANK_WIDTH; } case Const.RIGHT -> { x += Const.TANK_WIDTH; y += Const.WIDTH; } case Const.LEFT -> { x -= Const.WIDTH; y += Const.WIDTH; } } this.getMyPanel().getBullets().add(new Bullet(x, y, this.getDir(), this.getBulletType(), this.getTankType(), this.getMyPanel())); } // 画血条 public void draw(Graphics g1) { int width = 50; int y; Graphics2D g = (Graphics2D) g1; String path = this.getImg()[this.getDir() - 1]; g.drawImage(Toolkit.getDefaultToolkit().getImage(path), this.getX(), this.getY(), Const.TANK_WIDTH, Const.TANK_WIDTH, this.getMyPanel()); int hp = this.getHp(); g.setColor(Color.white); g.setStroke(new BasicStroke(3)); if (this.getY() <= 10) { y = this.getY() + Const.TANK_WIDTH + 10; } else { y = this.getY() - 10; } g.drawRect(this.getX() + 5, y, width, 5); g.setColor(Color.red); g.fillRect(this.getX() + 5, y, width * hp / Const.MAX_HP, 5); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; } public long getLastFireTime() { return lastFireTime; } public void setLastFireTime(long lastFireTime) { this.lastFireTime = lastFireTime; } public int getHp() { return hp; } public void setHp(int hp) { if (hp < 0) { this.hp = 0; this.setAlive(false); } else { this.hp = hp; } } public MyPanel getMyPanel() { return myPanel; } public void setMyPanel(MyPanel myPanel) { this.myPanel = myPanel; } public int getBulletType() { return bulletType; } public void setBulletType(int bulletType) { this.bulletType = bulletType; } public int getTankType() { return tankType; } public boolean isAlive() { return isAlive; } public void setAlive(boolean alive) { isAlive = alive; } public Random getRandom() { return random; } public String[] getImg() { return img; } public void setImg(String[] img) { this.img = img; } public long[] getPropTime() { return propTime; } public void setPropTime(long time, int type) { this.propTime[type] = time; } @Override public void onAttacked(int damage) { this.setHp(this.getHp() - damage); } }
WhiteNight123/Tank-War
src/model/Tank.java
1,329
// 画血条
line_comment
zh-cn
package model; import java.awt.*; import java.util.Random; public class Tank implements AttackCallable { private final int tankType; private final Random random; private final long[] propTime; private int x; private int y; private int dir; private int hp; private int bulletType; private boolean isAlive; private int speed; private MyPanel myPanel; private long lastFireTime; private String[] img; // 传入的是 敌人、玩家 public Tank(int tankType, MyPanel myPanel, int x, int y) { this.setX(x); this.setY(y); this.hp = Const.MAX_HP; this.isAlive = true; this.tankType = tankType; this.setMyPanel(myPanel); this.random = new Random(); this.setLastFireTime(System.currentTimeMillis()); propTime = new long[]{0, 0, 0}; } public void move() { if (canMove()) { switch (this.dir) { case Const.UP -> this.setY(this.getY() - speed); case Const.DOWN -> this.setY(this.getY() + speed); case Const.LEFT -> this.setX(this.getX() - speed); case Const.RIGHT -> this.setX(this.getX() + speed); } } } /** * 等待被重写 * * @return true or false */ public boolean canMove() { return false; } public void fire() { if (canFire()) { addBullet(); } } /** * 是否可以发射子弹,对于不同的子类需要重写 * * @return true 可以 false 不可以 */ public boolean canFire() { return false; } public void addBullet() { int x = this.getX(); int y = this.getY(); switch (this.getDir()) { case Const.UP -> { x += Const.WIDTH; y -= Const.WIDTH; } case Const.DOWN -> { x += Const.WIDTH; y += Const.TANK_WIDTH; } case Const.RIGHT -> { x += Const.TANK_WIDTH; y += Const.WIDTH; } case Const.LEFT -> { x -= Const.WIDTH; y += Const.WIDTH; } } this.getMyPanel().getBullets().add(new Bullet(x, y, this.getDir(), this.getBulletType(), this.getTankType(), this.getMyPanel())); } // 画血 <SUF> public void draw(Graphics g1) { int width = 50; int y; Graphics2D g = (Graphics2D) g1; String path = this.getImg()[this.getDir() - 1]; g.drawImage(Toolkit.getDefaultToolkit().getImage(path), this.getX(), this.getY(), Const.TANK_WIDTH, Const.TANK_WIDTH, this.getMyPanel()); int hp = this.getHp(); g.setColor(Color.white); g.setStroke(new BasicStroke(3)); if (this.getY() <= 10) { y = this.getY() + Const.TANK_WIDTH + 10; } else { y = this.getY() - 10; } g.drawRect(this.getX() + 5, y, width, 5); g.setColor(Color.red); g.fillRect(this.getX() + 5, y, width * hp / Const.MAX_HP, 5); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; } public long getLastFireTime() { return lastFireTime; } public void setLastFireTime(long lastFireTime) { this.lastFireTime = lastFireTime; } public int getHp() { return hp; } public void setHp(int hp) { if (hp < 0) { this.hp = 0; this.setAlive(false); } else { this.hp = hp; } } public MyPanel getMyPanel() { return myPanel; } public void setMyPanel(MyPanel myPanel) { this.myPanel = myPanel; } public int getBulletType() { return bulletType; } public void setBulletType(int bulletType) { this.bulletType = bulletType; } public int getTankType() { return tankType; } public boolean isAlive() { return isAlive; } public void setAlive(boolean alive) { isAlive = alive; } public Random getRandom() { return random; } public String[] getImg() { return img; } public void setImg(String[] img) { this.img = img; } public long[] getPropTime() { return propTime; } public void setPropTime(long time, int type) { this.propTime[type] = time; } @Override public void onAttacked(int damage) { this.setHp(this.getHp() - damage); } }
false
1,201
5
1,329
6
1,476
4
1,329
6
1,640
7
false
false
false
false
false
true
35165_0
package ml; import com.google.common.base.Splitter; import yangUtil.YangCollectionUtil; import java.util.*; /** * 思想:与重要词共现的词也很重要 * S(Vi) = (1-d) + d*Sigma(j->in(vi)) 1/out(Vj) * S(Vj) * S(Vi)是网页i的中重要性(PR值)。d是阻尼系数,一般设置为0.85。In(Vi)是存在指向网页i的链接的网页集合。Out(Vj)是网页j中的链接存在的链接指向的网页的集合。|Out(Vj)|是集合中元素的个数。 * 网页的重要性取决于指向网页i的链接的网页集合且与集合大小成正比,并且与指向该网页的页面的重要性成正比,网页的连接数量成反比 * Created by hwyang on 2015/8/24. */ public class TextRank { public static void main(String[] args) { List<String> wordList = segWords(""); Map<String, Set<String>> toupiao = toupiao(wordList); Map<String, Double> scoreMap = new LinkedHashMap<>(); double d = 0.85;//阻尼系数 int maxIter = 1000;//最大迭代数 while (maxIter-- > 0) { for (Map.Entry<String, Set<String>> entry : toupiao.entrySet()) { String word = entry.getKey(); Set<String> js = entry.getValue(); double score = 0; for (String j : js) { if (j.equals(word)) { continue; } int size = toupiao.get(j).size(); Double weight = scoreMap.get(j) == null ? 1 : scoreMap.get(j);//初始权重都为1 score += d * 1 / (size + 1) * weight; } score = 0.15 + score; scoreMap.put(word, score); } } YangCollectionUtil.sortMapByValue(scoreMap, true); for (Map.Entry<String, Double> entry : scoreMap.entrySet()) { System.out.println(entry.getKey() + "\t" + entry.getValue()); } System.out.println(); } private static Map<String, Set<String>> toupiao(List<String> wordList) { Map<String, Set<String>> map = new HashMap<>(); for (int i = 0, max = wordList.size(); i < wordList.size(); i++) { int start = i - 5 >= 0 ? i - 5 : 0; int end = i + 5 >= max ? max : i + 5; String key = wordList.get(i); Set<String> value = map.get(key); HashSet<String> set = new HashSet<>(wordList.subList(start, end)); if (value == null) { map.put(key, set); } else { value.addAll(set); } } return map; } public static List<String> segWords(String line) { return Splitter.on(", ").omitEmptyStrings().splitToList("程序员, 英文, 程序, 开发, 维护, 专业, 人员, 程序员, 分为, 程序, 设计, 人员, 程序, 编码, 人员, 界限, 特别, 中国, 软件, 人员, 分为, 程序员, 高级, 程序员, 系统, 分析员, 项目, 经理"); } }
WhizzoTech/WorkHome
yangutil/src/main/java/ml/TextRank.java
876
/** * 思想:与重要词共现的词也很重要 * S(Vi) = (1-d) + d*Sigma(j->in(vi)) 1/out(Vj) * S(Vj) * S(Vi)是网页i的中重要性(PR值)。d是阻尼系数,一般设置为0.85。In(Vi)是存在指向网页i的链接的网页集合。Out(Vj)是网页j中的链接存在的链接指向的网页的集合。|Out(Vj)|是集合中元素的个数。 * 网页的重要性取决于指向网页i的链接的网页集合且与集合大小成正比,并且与指向该网页的页面的重要性成正比,网页的连接数量成反比 * Created by hwyang on 2015/8/24. */
block_comment
zh-cn
package ml; import com.google.common.base.Splitter; import yangUtil.YangCollectionUtil; import java.util.*; /** * 思想: <SUF>*/ public class TextRank { public static void main(String[] args) { List<String> wordList = segWords(""); Map<String, Set<String>> toupiao = toupiao(wordList); Map<String, Double> scoreMap = new LinkedHashMap<>(); double d = 0.85;//阻尼系数 int maxIter = 1000;//最大迭代数 while (maxIter-- > 0) { for (Map.Entry<String, Set<String>> entry : toupiao.entrySet()) { String word = entry.getKey(); Set<String> js = entry.getValue(); double score = 0; for (String j : js) { if (j.equals(word)) { continue; } int size = toupiao.get(j).size(); Double weight = scoreMap.get(j) == null ? 1 : scoreMap.get(j);//初始权重都为1 score += d * 1 / (size + 1) * weight; } score = 0.15 + score; scoreMap.put(word, score); } } YangCollectionUtil.sortMapByValue(scoreMap, true); for (Map.Entry<String, Double> entry : scoreMap.entrySet()) { System.out.println(entry.getKey() + "\t" + entry.getValue()); } System.out.println(); } private static Map<String, Set<String>> toupiao(List<String> wordList) { Map<String, Set<String>> map = new HashMap<>(); for (int i = 0, max = wordList.size(); i < wordList.size(); i++) { int start = i - 5 >= 0 ? i - 5 : 0; int end = i + 5 >= max ? max : i + 5; String key = wordList.get(i); Set<String> value = map.get(key); HashSet<String> set = new HashSet<>(wordList.subList(start, end)); if (value == null) { map.put(key, set); } else { value.addAll(set); } } return map; } public static List<String> segWords(String line) { return Splitter.on(", ").omitEmptyStrings().splitToList("程序员, 英文, 程序, 开发, 维护, 专业, 人员, 程序员, 分为, 程序, 设计, 人员, 程序, 编码, 人员, 界限, 特别, 中国, 软件, 人员, 分为, 程序员, 高级, 程序员, 系统, 分析员, 项目, 经理"); } }
false
798
184
876
205
883
191
876
205
1,065
272
false
false
false
false
false
true
26769_0
package box; import javax.swing.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; class MenuWindow extends JFrame implements ActionListener{ public static JTextField text; private void addItem(JMenu menu,String menuName,ActionListener listener){ JMenuItem aItem=new JMenuItem(menuName); aItem.setActionCommand(menuName); aItem.addActionListener(listener); menu.add(aItem); } public MenuWindow(String s,int w,int h){ setTitle(s); Container con=this.getContentPane(); con.setLayout(new BorderLayout()); this.setLocation(100,100); this.setSize(w, h); JMenu menu1=new JMenu("体育"); addItem(menu1,"跑步",this); addItem(menu1,"器械",this); addItem(menu1,"游泳",this); JMenu menu2=new JMenu("娱乐"); addItem(menu2,"唱歌",this); addItem(menu2,"跳舞",this); addItem(menu2,"游戏",this); JMenuBar mBar=new JMenuBar(); text=new JTextField(); mBar.add(menu1); mBar.add(menu2); setJMenuBar(mBar);//向窗口增设惨淡条 con.add(text, BorderLayout.NORTH); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub text.setText(e.getActionCommand()+"被选中"); } } public class menu extends Applet implements ActionListener{ MenuWindow window;JButton button;boolean bool; public void init(){ button=new JButton("打开我的窗口"); bool=true; window=new MenuWindow("窗口",100,100); button.addActionListener(this); add(button); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==button){ if(bool){ window.setVisible(true); bool=false; button.setLabel("已打开"); }else{ window.setVisible(false); bool=true; button.setLabel("打开"); } } } }
William-Gu/Java-zi
Example_6/src/box/menu.java
582
//向窗口增设惨淡条
line_comment
zh-cn
package box; import javax.swing.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; class MenuWindow extends JFrame implements ActionListener{ public static JTextField text; private void addItem(JMenu menu,String menuName,ActionListener listener){ JMenuItem aItem=new JMenuItem(menuName); aItem.setActionCommand(menuName); aItem.addActionListener(listener); menu.add(aItem); } public MenuWindow(String s,int w,int h){ setTitle(s); Container con=this.getContentPane(); con.setLayout(new BorderLayout()); this.setLocation(100,100); this.setSize(w, h); JMenu menu1=new JMenu("体育"); addItem(menu1,"跑步",this); addItem(menu1,"器械",this); addItem(menu1,"游泳",this); JMenu menu2=new JMenu("娱乐"); addItem(menu2,"唱歌",this); addItem(menu2,"跳舞",this); addItem(menu2,"游戏",this); JMenuBar mBar=new JMenuBar(); text=new JTextField(); mBar.add(menu1); mBar.add(menu2); setJMenuBar(mBar);//向窗 <SUF> con.add(text, BorderLayout.NORTH); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub text.setText(e.getActionCommand()+"被选中"); } } public class menu extends Applet implements ActionListener{ MenuWindow window;JButton button;boolean bool; public void init(){ button=new JButton("打开我的窗口"); bool=true; window=new MenuWindow("窗口",100,100); button.addActionListener(this); add(button); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==button){ if(bool){ window.setVisible(true); bool=false; button.setLabel("已打开"); }else{ window.setVisible(false); bool=true; button.setLabel("打开"); } } } }
false
439
7
582
10
557
8
582
10
719
17
false
false
false
false
false
true
57670_0
package yw22912; import java.util.Scanner; public class ifDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入酒量:"); int wine = sc.nextInt(); if (wine >2){ //语句体 System.out.println("小伙子不错哦!"); } else { System.out.println("你不行!"); } } }
WilliamWang9009/Study
day02/src/yw22912/ifDemo.java
118
//语句体
line_comment
zh-cn
package yw22912; import java.util.Scanner; public class ifDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入酒量:"); int wine = sc.nextInt(); if (wine >2){ //语句 <SUF> System.out.println("小伙子不错哦!"); } else { System.out.println("你不行!"); } } }
false
94
5
117
4
121
4
117
4
140
7
false
false
false
false
false
true
63316_0
# -*- coding:utf-8 -*- /* @Author:Charles Van @E-mail: [email protected] @Time:2019-08-19 10:42 @Project:InterView_Book @Filename:20_善变的伙伴.py @description: 题目描述 又到了吃午饭的时间,你和你的同伴刚刚研发出了最新的GSS-483型自动打饭机器人,现在你们正在对机器人进行功能测试。 为了简化问题,我们假设午饭一共有N个菜,对于第i个菜,你和你的同伴对其定义了一个好吃程度(或难吃程度,如果是负数的话……)A[i], 由于一些技(经)术(费)限制,机器人一次只能接受一个指令:两个数L, R——表示机器人将会去打第L~R一共R-L+1个菜。 本着不浪费的原则,你们决定机器人打上来的菜,含着泪也要都吃完,于是你们希望机器人打的菜的好吃程度之和最大 然而,你善变的同伴希望对机器人进行多次测试(实际上可能是为了多吃到好吃的菜),他想知道机器人打M次菜能达到的最大的好吃程度之和 当然,打过一次的菜是不能再打的,而且你也可以对机器人输入-1, -1,表示一个菜也不打 输入描述: 第一行:N, M 第二行:A[1], A[2], ..., A[N] 输出描述: 一个数字S,表示M次打菜的最大好吃程度之和 **/ import java.util.ArrayDeque; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(), M = sc.nextInt(); int[] change = new int[N + 1]; for (int i = 1; i <= N; ++i) { change[i] = change[i - 1] + sc.nextInt(); } System.out.println(solve(M, change)); } private static int solve(int M, int[] change) { int n = change.length, v, p = 0, ans = 0; PriorityQueue<Integer> profits = new PriorityQueue<Integer>(n / 2 + 1, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return i2 - i1; } }); ArrayDeque<Integer> vs = new ArrayDeque<Integer>(); ArrayDeque<Integer> ps = new ArrayDeque<Integer>(); while (p < n) { for (v = p; v < n - 1 && change[v + 1] <= change[v]; ++v) { ; } for (p = v + 1; p < n && change[p - 1] <= change[p]; ++p) { ; } while (!vs.isEmpty() && change[v] < change[vs.peek()]) { profits.add(change[ps.pop() - 1] - change[vs.pop()]); } while (!ps.isEmpty() && change[p - 1] >= change[ps.peek() - 1]) { profits.add(change[ps.pop() - 1] - change[v]); v = vs.pop(); } vs.push(v); ps.push(p); } while (!vs.isEmpty()) { profits.add(change[ps.pop() - 1] - change[vs.pop()]); } while (M-- > 0 && !profits.isEmpty()) { ans += profits.poll(); } return ans; } }
Willianan/Interview_Book
nowcoder/20_善变的伙伴.java
950
/* @Author:Charles Van @E-mail: [email protected] @Time:2019-08-19 10:42 @Project:InterView_Book @Filename:20_善变的伙伴.py @description: 题目描述 又到了吃午饭的时间,你和你的同伴刚刚研发出了最新的GSS-483型自动打饭机器人,现在你们正在对机器人进行功能测试。 为了简化问题,我们假设午饭一共有N个菜,对于第i个菜,你和你的同伴对其定义了一个好吃程度(或难吃程度,如果是负数的话……)A[i], 由于一些技(经)术(费)限制,机器人一次只能接受一个指令:两个数L, R——表示机器人将会去打第L~R一共R-L+1个菜。 本着不浪费的原则,你们决定机器人打上来的菜,含着泪也要都吃完,于是你们希望机器人打的菜的好吃程度之和最大 然而,你善变的同伴希望对机器人进行多次测试(实际上可能是为了多吃到好吃的菜),他想知道机器人打M次菜能达到的最大的好吃程度之和 当然,打过一次的菜是不能再打的,而且你也可以对机器人输入-1, -1,表示一个菜也不打 输入描述: 第一行:N, M 第二行:A[1], A[2], ..., A[N] 输出描述: 一个数字S,表示M次打菜的最大好吃程度之和 **/
block_comment
zh-cn
# -*- coding:utf-8 -*- /* @Au <SUF>*/ import java.util.ArrayDeque; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(), M = sc.nextInt(); int[] change = new int[N + 1]; for (int i = 1; i <= N; ++i) { change[i] = change[i - 1] + sc.nextInt(); } System.out.println(solve(M, change)); } private static int solve(int M, int[] change) { int n = change.length, v, p = 0, ans = 0; PriorityQueue<Integer> profits = new PriorityQueue<Integer>(n / 2 + 1, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return i2 - i1; } }); ArrayDeque<Integer> vs = new ArrayDeque<Integer>(); ArrayDeque<Integer> ps = new ArrayDeque<Integer>(); while (p < n) { for (v = p; v < n - 1 && change[v + 1] <= change[v]; ++v) { ; } for (p = v + 1; p < n && change[p - 1] <= change[p]; ++p) { ; } while (!vs.isEmpty() && change[v] < change[vs.peek()]) { profits.add(change[ps.pop() - 1] - change[vs.pop()]); } while (!ps.isEmpty() && change[p - 1] >= change[ps.peek() - 1]) { profits.add(change[ps.pop() - 1] - change[v]); v = vs.pop(); } vs.push(v); ps.push(p); } while (!vs.isEmpty()) { profits.add(change[ps.pop() - 1] - change[vs.pop()]); } while (M-- > 0 && !profits.isEmpty()) { ans += profits.poll(); } return ans; } }
false
786
333
950
419
913
349
950
419
1,191
581
true
true
true
true
true
false
18065_1
package com.sw; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.Map; /** * @Author Czy * @Date 20/02/17 * @detail 验证码识别 */ public class ImgIdenfy { private int height = 22; private int width = 62; private int rgbThres = 150; public int[][] binaryImg(BufferedImage img) { int[][] imgArr = new int[this.height][this.width]; for (int x = 0; x < this.width; ++x) { for (int y = 0; y < this.height; ++y) { if (x == 0 || y == 0 || x == this.width - 1 || y == this.height - 1) { imgArr[y][x] = 1; continue; } int pixel = img.getRGB(x, y); if (((pixel & 0xff0000) >> 16) < this.rgbThres && ((pixel & 0xff00) >> 8) < this.rgbThres && (pixel & 0xff) < this.rgbThres) { imgArr[y][x] = 0; } else { imgArr[y][x] = 1; } } } return imgArr; } // 去掉干扰线 public void removeByLine(int[][] imgArr) { for (int y = 1; y < this.height - 1; ++y) { for (int x = 1; x < this.width - 1; ++x) { if (imgArr[y][x] == 0) { int count = imgArr[y][x - 1] + imgArr[y][x + 1] + imgArr[y + 1][x] + imgArr[y - 1][x]; if (count > 2) imgArr[y][x] = 1; } } } } // 裁剪 public int[][][] imgCut(int[][] imgArr, int[][] xCut, int[][] yCut, int num) { int[][][] imgArrArr = new int[num][yCut[0][1] - yCut[0][0]][xCut[0][1] - xCut[0][0]]; for (int i = 0; i < num; ++i) { for (int j = yCut[i][0]; j < yCut[i][1]; ++j) { for (int k = xCut[i][0]; k < xCut[i][1]; ++k) { imgArrArr[i][j-yCut[i][0]][k-xCut[i][0]] = imgArr[j][k]; } } } return imgArrArr; } // 转字符串 public String getString(int[][] imgArr){ StringBuilder s = new StringBuilder(); int unitHeight = imgArr.length; int unitWidth = imgArr[0].length; for (int y = 0; y < unitHeight; ++y) { for (int x = 0; x < unitWidth; ++x) { s.append(imgArr[y][x]); } } return s.toString(); } // 相同大小直接对比 private int comparedText(String s1,String s2){ int n = s1.length(); int percent = 0; for(int i = 0; i < n ; ++i) { if (s1.charAt(i) == s2.charAt(i)) percent++; } return percent; } /** * 匹配识别 * @param imgArrArr * @return */ public String matchCode(int [][][] imgArrArr){ StringBuilder s = new StringBuilder(); Map<String,String> charMap = CharMap.getCharMap(); for (int[][] imgArr : imgArrArr){ int maxMatch = 0; String tempRecord = ""; for(Map.Entry<String,String> m : charMap.entrySet()){ int percent = this.comparedText(this.getString(imgArr),m.getValue()); if(percent > maxMatch){ maxMatch = percent; tempRecord = m.getKey(); } } s.append(tempRecord); } return s.toString(); } // 写入硬盘 public void writeImage(BufferedImage sourceImg) { File imageFile = new File("v.jpg"); try (FileOutputStream outStream = new FileOutputStream(imageFile)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(sourceImg, "jpg", out); byte[] data = out.toByteArray(); outStream.write(data); } catch (Exception e) { System.out.println(e.toString()); } } // 控制台打印 public void showImg(int[][] imgArr) { int unitHeight = imgArr.length; int unitWidth = imgArr[0].length; for (int y = 0; y < unitHeight; ++y) { for (int x = 0; x < unitWidth; ++x) { System.out.print(imgArr[y][x]); } System.out.println(); } } public static void main(String[] args) { ImgIdenfy imgIdenfy = new ImgIdenfy(); try (InputStream is = new URL("http://xxxxxxxxxxxxxxx/verifycode.servlet").openStream()) { BufferedImage sourceImg = ImageIO.read(is); imgIdenfy.writeImage(sourceImg); // 图片写入硬盘 int[][] imgArr = imgIdenfy.binaryImg(sourceImg); // 二值化 imgIdenfy.removeByLine(imgArr); // 去除干扰先 引用传递 int[][][] imgArrArr = imgIdenfy.imgCut(imgArr, new int[][]{new int[]{4, 13}, new int[]{14, 23}, new int[]{24, 33}, new int[]{34, 43}}, new int[][]{new int[]{4, 16}, new int[]{4, 16}, new int[]{4, 16}, new int[]{4, 16}}, 4); System.out.println(imgIdenfy.matchCode(imgArrArr)); // 识别 // imgIdenfy.showImg(imgArr); //控制台打印图片 // imgIdenfy.showImg(imgArrArr[0]); //控制台打印图片 // System.out.println(imgIdenfy.getString(imgArrArr[0])); } catch (Exception e) { e.printStackTrace(); } } }
WindrunnerMax/SWVerifyCode
Java/ImgIdenfy.java
1,627
// 去掉干扰线
line_comment
zh-cn
package com.sw; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.Map; /** * @Author Czy * @Date 20/02/17 * @detail 验证码识别 */ public class ImgIdenfy { private int height = 22; private int width = 62; private int rgbThres = 150; public int[][] binaryImg(BufferedImage img) { int[][] imgArr = new int[this.height][this.width]; for (int x = 0; x < this.width; ++x) { for (int y = 0; y < this.height; ++y) { if (x == 0 || y == 0 || x == this.width - 1 || y == this.height - 1) { imgArr[y][x] = 1; continue; } int pixel = img.getRGB(x, y); if (((pixel & 0xff0000) >> 16) < this.rgbThres && ((pixel & 0xff00) >> 8) < this.rgbThres && (pixel & 0xff) < this.rgbThres) { imgArr[y][x] = 0; } else { imgArr[y][x] = 1; } } } return imgArr; } // 去掉 <SUF> public void removeByLine(int[][] imgArr) { for (int y = 1; y < this.height - 1; ++y) { for (int x = 1; x < this.width - 1; ++x) { if (imgArr[y][x] == 0) { int count = imgArr[y][x - 1] + imgArr[y][x + 1] + imgArr[y + 1][x] + imgArr[y - 1][x]; if (count > 2) imgArr[y][x] = 1; } } } } // 裁剪 public int[][][] imgCut(int[][] imgArr, int[][] xCut, int[][] yCut, int num) { int[][][] imgArrArr = new int[num][yCut[0][1] - yCut[0][0]][xCut[0][1] - xCut[0][0]]; for (int i = 0; i < num; ++i) { for (int j = yCut[i][0]; j < yCut[i][1]; ++j) { for (int k = xCut[i][0]; k < xCut[i][1]; ++k) { imgArrArr[i][j-yCut[i][0]][k-xCut[i][0]] = imgArr[j][k]; } } } return imgArrArr; } // 转字符串 public String getString(int[][] imgArr){ StringBuilder s = new StringBuilder(); int unitHeight = imgArr.length; int unitWidth = imgArr[0].length; for (int y = 0; y < unitHeight; ++y) { for (int x = 0; x < unitWidth; ++x) { s.append(imgArr[y][x]); } } return s.toString(); } // 相同大小直接对比 private int comparedText(String s1,String s2){ int n = s1.length(); int percent = 0; for(int i = 0; i < n ; ++i) { if (s1.charAt(i) == s2.charAt(i)) percent++; } return percent; } /** * 匹配识别 * @param imgArrArr * @return */ public String matchCode(int [][][] imgArrArr){ StringBuilder s = new StringBuilder(); Map<String,String> charMap = CharMap.getCharMap(); for (int[][] imgArr : imgArrArr){ int maxMatch = 0; String tempRecord = ""; for(Map.Entry<String,String> m : charMap.entrySet()){ int percent = this.comparedText(this.getString(imgArr),m.getValue()); if(percent > maxMatch){ maxMatch = percent; tempRecord = m.getKey(); } } s.append(tempRecord); } return s.toString(); } // 写入硬盘 public void writeImage(BufferedImage sourceImg) { File imageFile = new File("v.jpg"); try (FileOutputStream outStream = new FileOutputStream(imageFile)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(sourceImg, "jpg", out); byte[] data = out.toByteArray(); outStream.write(data); } catch (Exception e) { System.out.println(e.toString()); } } // 控制台打印 public void showImg(int[][] imgArr) { int unitHeight = imgArr.length; int unitWidth = imgArr[0].length; for (int y = 0; y < unitHeight; ++y) { for (int x = 0; x < unitWidth; ++x) { System.out.print(imgArr[y][x]); } System.out.println(); } } public static void main(String[] args) { ImgIdenfy imgIdenfy = new ImgIdenfy(); try (InputStream is = new URL("http://xxxxxxxxxxxxxxx/verifycode.servlet").openStream()) { BufferedImage sourceImg = ImageIO.read(is); imgIdenfy.writeImage(sourceImg); // 图片写入硬盘 int[][] imgArr = imgIdenfy.binaryImg(sourceImg); // 二值化 imgIdenfy.removeByLine(imgArr); // 去除干扰先 引用传递 int[][][] imgArrArr = imgIdenfy.imgCut(imgArr, new int[][]{new int[]{4, 13}, new int[]{14, 23}, new int[]{24, 33}, new int[]{34, 43}}, new int[][]{new int[]{4, 16}, new int[]{4, 16}, new int[]{4, 16}, new int[]{4, 16}}, 4); System.out.println(imgIdenfy.matchCode(imgArrArr)); // 识别 // imgIdenfy.showImg(imgArr); //控制台打印图片 // imgIdenfy.showImg(imgArrArr[0]); //控制台打印图片 // System.out.println(imgIdenfy.getString(imgArrArr[0])); } catch (Exception e) { e.printStackTrace(); } } }
false
1,490
7
1,627
8
1,714
5
1,627
8
1,920
13
false
false
false
false
false
true
5400_0
package com.lyl.boon.ui; import android.os.Bundle; import androidx.annotation.IdRes; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.Toast; import com.lyl.boon.R; import com.lyl.boon.ui.base.BaseActivity; import com.lyl.boon.ui.joke.JokeFragment; import com.lyl.boon.ui.learn.LearnFragment; import com.lyl.boon.ui.superboon.SuperBoonFragment; import com.lyl.boon.ui.wanandroid.WanAndroidFragment; import com.lyl.boon.ui.young.YoungFragment; import com.lyl.boon.utils.NetStatusUtil; import com.roughike.bottombar.BottomBar; import com.roughike.bottombar.OnTabSelectListener; import butterknife.Bind; import butterknife.ButterKnife; import me.drakeet.materialdialog.MaterialDialog; public class MainActivity extends BaseActivity { private LearnFragment learnFragment; private WanAndroidFragment wanandroidFragment; private YoungFragment youngFragment; private JokeFragment jokeFragment; private SuperBoonFragment superFragment; private Fragment oldFragment; @Bind(R.id.bottomBar) BottomBar mBottomBar; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initActionbar(); setAppAbout(); setFavoriteIcon(); initBottom(); initFragmentContent(); } /** * 设置中间内容页 */ private void initFragmentContent() { learnFragment = new LearnFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_content, learnFragment).commit(); oldFragment = learnFragment; } /** * 设置底部按钮 */ private void initBottom() { mBottomBar.setOnTabSelectListener(new OnTabSelectListener() { @Override public void onTabSelected(@IdRes int tabId) { switch (tabId) { case R.id.menu_learn: //学习 setActTitle(R.string.menu_learn_msg); toFragment(learnFragment); break; case R.id.menu_wanandroid: //玩Android goFragment(0); break; case R.id.menu_joke: //开心 checkNet(1); break; case R.id.menu_young: //美女 checkNet(2); break; case R.id.menu_super: //超级福利 checkNet(3); break; default: setActTitle(R.string.menu_learn_msg); toFragment(learnFragment); break; } } }); } /** * 检查网络,并跳转 */ private void checkNet(final int position) { if (NetStatusUtil.isWifi(MainActivity.this)) { goFragment(position); } else { final MaterialDialog dialog = new MaterialDialog(this); dialog.setTitle("提示"); dialog.setMessage("您当前不是WIFI状态,访问会消耗大量的流量,您确定要访问吗?"); dialog.setPositiveButton("没事儿拼了", new View.OnClickListener() { @Override public void onClick(View v) { goFragment(position); dialog.dismiss(); } }); dialog.setNegativeButton("还是不看了", new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); showToast("(*^__^*) 没事去读书学习吧"); mBottomBar.selectTabWithId(R.id.menu_wanandroid); } }); dialog.show(); } } private void goFragment(int position) { switch (position) { case 0://玩Android setActTitle(R.string.menu_wanandroid_msg); if (wanandroidFragment == null) { wanandroidFragment = new WanAndroidFragment(); } toFragment(wanandroidFragment); break; case 1://开心 setActTitle(R.string.menu_joke_msg); if (jokeFragment == null) { jokeFragment = new JokeFragment(); } toFragment(jokeFragment); break; case 2: //美女 setActTitle(R.string.menu_young_msg); if (youngFragment == null) { youngFragment = new YoungFragment(); } toFragment(youngFragment); break; case 3: //超级福利 setActTitle(R.string.menu_super_msg); if (superFragment == null) { superFragment = new SuperBoonFragment(); } toFragment(superFragment); break; } } /** * 切换Fragment * * @param to 下一个Fragment页面 */ private void toFragment(Fragment to) { if (to == oldFragment) return; FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out); if (!to.isAdded()) { // 先判断是否被add过 transaction.hide(oldFragment).add(R.id.fragment_content, to).commit(); // 隐藏当前的fragment,add下一个到Activity中 } else { transaction.hide(oldFragment).show(to).commit(); // 隐藏当前的fragment,显示下一个 } oldFragment = to; } /** * 设置导航栏的标题 */ private void setActTitle(int res) { if (mActionTitle != null) { mActionTitle.setText(getString(res)); } } //*************************** // 双击返回退出 //*************************** private long time = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (System.currentTimeMillis() - time <= 2000) { finish(); } else { time = System.currentTimeMillis(); Toast.makeText(getApplicationContext(), R.string.exit_app, Toast.LENGTH_SHORT).show(); } return true; } return super.onKeyDown(keyCode, event); } }
Wing-Li/boon
app/src/main/java/com/lyl/boon/ui/MainActivity.java
1,531
/** * 设置中间内容页 */
block_comment
zh-cn
package com.lyl.boon.ui; import android.os.Bundle; import androidx.annotation.IdRes; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.Toast; import com.lyl.boon.R; import com.lyl.boon.ui.base.BaseActivity; import com.lyl.boon.ui.joke.JokeFragment; import com.lyl.boon.ui.learn.LearnFragment; import com.lyl.boon.ui.superboon.SuperBoonFragment; import com.lyl.boon.ui.wanandroid.WanAndroidFragment; import com.lyl.boon.ui.young.YoungFragment; import com.lyl.boon.utils.NetStatusUtil; import com.roughike.bottombar.BottomBar; import com.roughike.bottombar.OnTabSelectListener; import butterknife.Bind; import butterknife.ButterKnife; import me.drakeet.materialdialog.MaterialDialog; public class MainActivity extends BaseActivity { private LearnFragment learnFragment; private WanAndroidFragment wanandroidFragment; private YoungFragment youngFragment; private JokeFragment jokeFragment; private SuperBoonFragment superFragment; private Fragment oldFragment; @Bind(R.id.bottomBar) BottomBar mBottomBar; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initActionbar(); setAppAbout(); setFavoriteIcon(); initBottom(); initFragmentContent(); } /** * 设置中 <SUF>*/ private void initFragmentContent() { learnFragment = new LearnFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_content, learnFragment).commit(); oldFragment = learnFragment; } /** * 设置底部按钮 */ private void initBottom() { mBottomBar.setOnTabSelectListener(new OnTabSelectListener() { @Override public void onTabSelected(@IdRes int tabId) { switch (tabId) { case R.id.menu_learn: //学习 setActTitle(R.string.menu_learn_msg); toFragment(learnFragment); break; case R.id.menu_wanandroid: //玩Android goFragment(0); break; case R.id.menu_joke: //开心 checkNet(1); break; case R.id.menu_young: //美女 checkNet(2); break; case R.id.menu_super: //超级福利 checkNet(3); break; default: setActTitle(R.string.menu_learn_msg); toFragment(learnFragment); break; } } }); } /** * 检查网络,并跳转 */ private void checkNet(final int position) { if (NetStatusUtil.isWifi(MainActivity.this)) { goFragment(position); } else { final MaterialDialog dialog = new MaterialDialog(this); dialog.setTitle("提示"); dialog.setMessage("您当前不是WIFI状态,访问会消耗大量的流量,您确定要访问吗?"); dialog.setPositiveButton("没事儿拼了", new View.OnClickListener() { @Override public void onClick(View v) { goFragment(position); dialog.dismiss(); } }); dialog.setNegativeButton("还是不看了", new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); showToast("(*^__^*) 没事去读书学习吧"); mBottomBar.selectTabWithId(R.id.menu_wanandroid); } }); dialog.show(); } } private void goFragment(int position) { switch (position) { case 0://玩Android setActTitle(R.string.menu_wanandroid_msg); if (wanandroidFragment == null) { wanandroidFragment = new WanAndroidFragment(); } toFragment(wanandroidFragment); break; case 1://开心 setActTitle(R.string.menu_joke_msg); if (jokeFragment == null) { jokeFragment = new JokeFragment(); } toFragment(jokeFragment); break; case 2: //美女 setActTitle(R.string.menu_young_msg); if (youngFragment == null) { youngFragment = new YoungFragment(); } toFragment(youngFragment); break; case 3: //超级福利 setActTitle(R.string.menu_super_msg); if (superFragment == null) { superFragment = new SuperBoonFragment(); } toFragment(superFragment); break; } } /** * 切换Fragment * * @param to 下一个Fragment页面 */ private void toFragment(Fragment to) { if (to == oldFragment) return; FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out); if (!to.isAdded()) { // 先判断是否被add过 transaction.hide(oldFragment).add(R.id.fragment_content, to).commit(); // 隐藏当前的fragment,add下一个到Activity中 } else { transaction.hide(oldFragment).show(to).commit(); // 隐藏当前的fragment,显示下一个 } oldFragment = to; } /** * 设置导航栏的标题 */ private void setActTitle(int res) { if (mActionTitle != null) { mActionTitle.setText(getString(res)); } } //*************************** // 双击返回退出 //*************************** private long time = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (System.currentTimeMillis() - time <= 2000) { finish(); } else { time = System.currentTimeMillis(); Toast.makeText(getApplicationContext(), R.string.exit_app, Toast.LENGTH_SHORT).show(); } return true; } return super.onKeyDown(keyCode, event); } }
false
1,305
10
1,531
9
1,614
11
1,531
9
1,902
15
false
false
false
false
false
true
5806_1
package cn.luischen.model; import lombok.Data; import java.io.Serializable; /** * 日志类 * Created by winterchen on 2018/4/29. */ @Data public class LogDomain implements Serializable { private static final long serialVersionUID = 1L; /** * 日志主键 */ private Integer id; /** * 产生的动作 */ private String action; /** * 产生的数据 */ private String data; /** * 发生人id */ private Integer authorId; /** * 日志产生的ip */ private String ip; /** * 日志创建时间 */ private Integer created; }
WinterChenS/my-site
src/main/java/cn/luischen/model/LogDomain.java
170
/** * 日志主键 */
block_comment
zh-cn
package cn.luischen.model; import lombok.Data; import java.io.Serializable; /** * 日志类 * Created by winterchen on 2018/4/29. */ @Data public class LogDomain implements Serializable { private static final long serialVersionUID = 1L; /** * 日志主 <SUF>*/ private Integer id; /** * 产生的动作 */ private String action; /** * 产生的数据 */ private String data; /** * 发生人id */ private Integer authorId; /** * 日志产生的ip */ private String ip; /** * 日志创建时间 */ private Integer created; }
false
156
10
170
8
187
10
170
8
230
14
false
false
false
false
false
true
62056_5
package com.njit.lib.domain; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; /** * 留言 * @author Administrator * */ @Entity public class Message { //>一般属性 private Long id; private String content; private Date publishTime; private int agreeCount;//赞同数 private int disagreeCount;//不赞同的数量 private boolean isAgree;//是否赞成,用来保存一个用户的评论 //>关联属性 private User user; private Set<Remark> remarks = new HashSet<Remark>(); @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getPublishTime() { return publishTime; } public void setPublishTime(Date publishTime) { this.publishTime = publishTime; } public int getAgreeCount() { return agreeCount; } public void setAgreeCount(int agreeCount) { this.agreeCount = agreeCount; } public int getDisagreeCount() { return disagreeCount; } public void setDisagreeCount(int disagreeCount) { this.disagreeCount = disagreeCount; } public boolean isAgree() { return isAgree; } public void setAgree(boolean isAgree) { this.isAgree = isAgree; } @ManyToOne public User getUser() { return user; } public void setUser(User user) { this.user = user; } @OneToMany(mappedBy="message",fetch=FetchType.EAGER,cascade=CascadeType.ALL) public Set<Remark> getRemarks() { return remarks; } public void setRemarks(Set<Remark> remarks) { this.remarks = remarks; } }
WiseWolfs/BookCMS
src/com/njit/lib/domain/Message.java
603
//>关联属性
line_comment
zh-cn
package com.njit.lib.domain; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; /** * 留言 * @author Administrator * */ @Entity public class Message { //>一般属性 private Long id; private String content; private Date publishTime; private int agreeCount;//赞同数 private int disagreeCount;//不赞同的数量 private boolean isAgree;//是否赞成,用来保存一个用户的评论 //>关 <SUF> private User user; private Set<Remark> remarks = new HashSet<Remark>(); @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getPublishTime() { return publishTime; } public void setPublishTime(Date publishTime) { this.publishTime = publishTime; } public int getAgreeCount() { return agreeCount; } public void setAgreeCount(int agreeCount) { this.agreeCount = agreeCount; } public int getDisagreeCount() { return disagreeCount; } public void setDisagreeCount(int disagreeCount) { this.disagreeCount = disagreeCount; } public boolean isAgree() { return isAgree; } public void setAgree(boolean isAgree) { this.isAgree = isAgree; } @ManyToOne public User getUser() { return user; } public void setUser(User user) { this.user = user; } @OneToMany(mappedBy="message",fetch=FetchType.EAGER,cascade=CascadeType.ALL) public Set<Remark> getRemarks() { return remarks; } public void setRemarks(Set<Remark> remarks) { this.remarks = remarks; } }
false
446
4
603
4
570
4
603
4
680
6
false
false
false
false
false
true
63368_0
package cn.banny.unidbg.android; public class personal { //标志 String name; //授权信息 String cookie; //设备信息 String miniwua; //运行期间总共偷取的能量 int allTotalEnergy; //运行期间总共帮好友收取的能量 int allTotalForFriendEnergy; personal(String name, String cookie,String miniwua){ this.name = name; this.cookie = cookie; this.miniwua = miniwua; this.allTotalEnergy = 0; this.allTotalForFriendEnergy = 0; } }
WithHades/forest
pc爬虫/personal.java
153
//授权信息
line_comment
zh-cn
package cn.banny.unidbg.android; public class personal { //标志 String name; //授权 <SUF> String cookie; //设备信息 String miniwua; //运行期间总共偷取的能量 int allTotalEnergy; //运行期间总共帮好友收取的能量 int allTotalForFriendEnergy; personal(String name, String cookie,String miniwua){ this.name = name; this.cookie = cookie; this.miniwua = miniwua; this.allTotalEnergy = 0; this.allTotalForFriendEnergy = 0; } }
false
132
3
153
3
162
3
153
3
203
9
false
false
false
false
false
true
56200_3
import java.util.ArrayList; public class Rule { private final String name, regexp; private final TokenType type; private static final ArrayList<Rule> rules = new ArrayList<>() {{ // IDENT add(new Rule("Ident", "[a-zA-Z_][_a-zA-Z0-9]*", TokenType.ident)); // 数字 add(new Rule("HexNumber", "(0x|0X)[0-9a-fA-F]+", TokenType.hexNumber)); add(new Rule("OctNumber", "0[0-9]*", TokenType.octNumber)); add(new Rule("DecNumber", "[1-9][0-9]*", TokenType.decNumber)); // 符号 add(new Rule("LBRACE", "\\(", TokenType.braceL)); add(new Rule("RBRACE", "\\)", TokenType.braceR)); add(new Rule("LBRACE_PLUS", "\\{", TokenType.braceLPlus)); add(new Rule("RBRACE_PLUS", "\\}", TokenType.braceRPlus)); add(new Rule("LBRACE_MEDIUM", "\\[", TokenType.braceLMedium)); add(new Rule("RBRACE_MEDIUM", "\\]", TokenType.braceRMedium)); add(new Rule("SEMICOLON", ";", TokenType.semicolon)); add(new Rule("EQUAL", "==", TokenType.equal)); add(new Rule("ASSIGNMENT", "=", TokenType.assignment)); add(new Rule("NOTEQUAL", "!=", TokenType.notEqual)); add(new Rule("COMMA", ",", TokenType.comma)); add(new Rule("ADD", "\\+", TokenType.add)); add(new Rule("MIN", "\\-", TokenType.mns)); add(new Rule("MUL", "\\*", TokenType.mul)); add(new Rule("DIV", "\\/", TokenType.div)); add(new Rule("MOD", "\\%", TokenType.mod)); add(new Rule("NOT", "!", TokenType.not)); add(new Rule("GTEQ", ">=", TokenType.gteq)); add(new Rule("LTEQ", "<=", TokenType.lteq)); add(new Rule("GT", ">", TokenType.gt)); add(new Rule("LT", "<", TokenType.lt)); add(new Rule("AND", "&&", TokenType.and)); add(new Rule("OR", "\\|\\|", TokenType.or)); // 关键字 add(new Rule("INT", "int", TokenType.INT)); // add(new Rule("MAIN", "main", TokenType.MAIN)); add(new Rule("RETURN", "return", TokenType.RETURN)); add(new Rule("CONST", "const", TokenType.CONST)); add(new Rule("VOID", "void", TokenType.VOID)); add(new Rule("IF", "if", TokenType.IF)); add(new Rule("ELSE", "else", TokenType.ELSE)); add(new Rule("WHILE", "while", TokenType.WHILE)); add(new Rule("BREAK", "break", TokenType.BREAK)); add(new Rule("CONTINUE", "continue", TokenType.CONTINUE)); // 空格 add(new Rule("WHITE", "[ \t\n\r]+", TokenType.WHITE)); add(new Rule("Comment", "//.*\\n?|/\\*[\\s\\S\\r\\n]*?\\*/", TokenType.COMMENT)); }}; public static ArrayList<Rule> getRules() { return rules; } public Rule(String name, String regexp, TokenType type) { this.name = name; this.regexp = regexp; this.type = type; } public String getName() { return name; } public String getRegexp() { return regexp; } public TokenType getType() { return type; } public boolean check(String str) { return str.matches(regexp); } }
Withinlover/SYSY-Compiler
src/Rule.java
858
// 关键字
line_comment
zh-cn
import java.util.ArrayList; public class Rule { private final String name, regexp; private final TokenType type; private static final ArrayList<Rule> rules = new ArrayList<>() {{ // IDENT add(new Rule("Ident", "[a-zA-Z_][_a-zA-Z0-9]*", TokenType.ident)); // 数字 add(new Rule("HexNumber", "(0x|0X)[0-9a-fA-F]+", TokenType.hexNumber)); add(new Rule("OctNumber", "0[0-9]*", TokenType.octNumber)); add(new Rule("DecNumber", "[1-9][0-9]*", TokenType.decNumber)); // 符号 add(new Rule("LBRACE", "\\(", TokenType.braceL)); add(new Rule("RBRACE", "\\)", TokenType.braceR)); add(new Rule("LBRACE_PLUS", "\\{", TokenType.braceLPlus)); add(new Rule("RBRACE_PLUS", "\\}", TokenType.braceRPlus)); add(new Rule("LBRACE_MEDIUM", "\\[", TokenType.braceLMedium)); add(new Rule("RBRACE_MEDIUM", "\\]", TokenType.braceRMedium)); add(new Rule("SEMICOLON", ";", TokenType.semicolon)); add(new Rule("EQUAL", "==", TokenType.equal)); add(new Rule("ASSIGNMENT", "=", TokenType.assignment)); add(new Rule("NOTEQUAL", "!=", TokenType.notEqual)); add(new Rule("COMMA", ",", TokenType.comma)); add(new Rule("ADD", "\\+", TokenType.add)); add(new Rule("MIN", "\\-", TokenType.mns)); add(new Rule("MUL", "\\*", TokenType.mul)); add(new Rule("DIV", "\\/", TokenType.div)); add(new Rule("MOD", "\\%", TokenType.mod)); add(new Rule("NOT", "!", TokenType.not)); add(new Rule("GTEQ", ">=", TokenType.gteq)); add(new Rule("LTEQ", "<=", TokenType.lteq)); add(new Rule("GT", ">", TokenType.gt)); add(new Rule("LT", "<", TokenType.lt)); add(new Rule("AND", "&&", TokenType.and)); add(new Rule("OR", "\\|\\|", TokenType.or)); // 关键 <SUF> add(new Rule("INT", "int", TokenType.INT)); // add(new Rule("MAIN", "main", TokenType.MAIN)); add(new Rule("RETURN", "return", TokenType.RETURN)); add(new Rule("CONST", "const", TokenType.CONST)); add(new Rule("VOID", "void", TokenType.VOID)); add(new Rule("IF", "if", TokenType.IF)); add(new Rule("ELSE", "else", TokenType.ELSE)); add(new Rule("WHILE", "while", TokenType.WHILE)); add(new Rule("BREAK", "break", TokenType.BREAK)); add(new Rule("CONTINUE", "continue", TokenType.CONTINUE)); // 空格 add(new Rule("WHITE", "[ \t\n\r]+", TokenType.WHITE)); add(new Rule("Comment", "//.*\\n?|/\\*[\\s\\S\\r\\n]*?\\*/", TokenType.COMMENT)); }}; public static ArrayList<Rule> getRules() { return rules; } public Rule(String name, String regexp, TokenType type) { this.name = name; this.regexp = regexp; this.type = type; } public String getName() { return name; } public String getRegexp() { return regexp; } public TokenType getType() { return type; } public boolean check(String str) { return str.matches(regexp); } }
false
795
5
856
4
916
4
856
4
1,080
8
false
false
false
false
false
true
23899_1
/* Young Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 271 Accepted: 108 Description Consider m natural numbers n1, n2, ..., nm with the property n1 >= n2 >= ... >= nm > 0. We define a Young table as an arrangement in a table of n1 + n2 + ... + nm natural numbers (bigger than 0 and any two different), so that the ith line has ni elements (1 <= i <= m) in ascending order from left to right, and the elements from the same column are in ascending order from bottom to top. An example of Young table for m = 4, n1 = 6, n2 = 4, n3 = 4, n4 = 1 is the following: 1 2 5 9 10 15 3 6 7 13 4 8 12 14 11 Given n1, n2, ..., nm determine the number of Young tables containing the elements 1, 2, ..., n1+n2+...+nm. Input The input has the stucture: on the first line is: the natural number m (1 <= m <= 20); on the second line are: the numbers n1, n2, ..., nm separated by a space (n1 <= 12). Output The output will contain the number of Young tables that can be built. Sample Input 2 3 2 Sample Output 5 Hint The five Young tables are: 1 3 5 1 2 3 1 2 4 2 4 4 5 3 5 1 3 4 1 2 5 2 5 3 4 */ /* 题意Overview: 给N(≤20),用1到N2的數字來填N×N的矩陣。對於矩陣上格子(i,j)的數值a(i,j),必須滿足a(i,j)<a(i−1,j)且a(i,j)<a(i,j−1)。问方案数。 题解Solution: 钩子公式秒杀之,各种神奇>_<。 对于N个格子的方案数。等于N!除以(每个格子上方和左方的格子数目+1)的积。 */ //PKU OJ 1825 import java.math.*; import java.io.*; import java.util.*; public class Main { final static int SIZE = 240; public static void main(String args[]) { Scanner input = new Scanner(System.in); BigInteger ans; int[] s = new int[SIZE]; int[][] young = new int[SIZE][SIZE]; while(input.hasNext()) { int sum = 0; int n = input.nextInt(); for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) young[i][j]=-1; } ans = BigInteger.ONE; for(int i=0;i<n;i++) { s[i]=input.nextInt(); sum+=s[i]; young[i][s[i]-1]=0; } //hook-length formula for(int i=2;i<=sum;i++) ans=ans.multiply(new BigInteger(Integer.toString(i))); for(int i=n-1;i>=0;i--) { for(int j=s[i]-1;j>=0;j--) { //A hook length hook(x) of a box x in Young diagram Y(λ) of shape λ //is the number of boxes that are in the same row to the right of it //plus those boxes in the same column below it, young[i][j]=0; if(i!=n-1) young[i][j]+=young[i+1][j]+1; ans=ans.divide(new BigInteger(Integer.toString(young[i][j]+s[i]-j))); } } //ans=n!/MUL(hook(x)) System.out.println(ans.toString()); } } }
Wizmann/ACM-ICPC
POJ/1/1825.java
1,065
/* 题意Overview: 给N(≤20),用1到N2的數字來填N×N的矩陣。對於矩陣上格子(i,j)的數值a(i,j),必須滿足a(i,j)<a(i−1,j)且a(i,j)<a(i,j−1)。问方案数。 题解Solution: 钩子公式秒杀之,各种神奇>_<。 对于N个格子的方案数。等于N!除以(每个格子上方和左方的格子数目+1)的积。 */
block_comment
zh-cn
/* Young Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 271 Accepted: 108 Description Consider m natural numbers n1, n2, ..., nm with the property n1 >= n2 >= ... >= nm > 0. We define a Young table as an arrangement in a table of n1 + n2 + ... + nm natural numbers (bigger than 0 and any two different), so that the ith line has ni elements (1 <= i <= m) in ascending order from left to right, and the elements from the same column are in ascending order from bottom to top. An example of Young table for m = 4, n1 = 6, n2 = 4, n3 = 4, n4 = 1 is the following: 1 2 5 9 10 15 3 6 7 13 4 8 12 14 11 Given n1, n2, ..., nm determine the number of Young tables containing the elements 1, 2, ..., n1+n2+...+nm. Input The input has the stucture: on the first line is: the natural number m (1 <= m <= 20); on the second line are: the numbers n1, n2, ..., nm separated by a space (n1 <= 12). Output The output will contain the number of Young tables that can be built. Sample Input 2 3 2 Sample Output 5 Hint The five Young tables are: 1 3 5 1 2 3 1 2 4 2 4 4 5 3 5 1 3 4 1 2 5 2 5 3 4 */ /* 题意O <SUF>*/ //PKU OJ 1825 import java.math.*; import java.io.*; import java.util.*; public class Main { final static int SIZE = 240; public static void main(String args[]) { Scanner input = new Scanner(System.in); BigInteger ans; int[] s = new int[SIZE]; int[][] young = new int[SIZE][SIZE]; while(input.hasNext()) { int sum = 0; int n = input.nextInt(); for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) young[i][j]=-1; } ans = BigInteger.ONE; for(int i=0;i<n;i++) { s[i]=input.nextInt(); sum+=s[i]; young[i][s[i]-1]=0; } //hook-length formula for(int i=2;i<=sum;i++) ans=ans.multiply(new BigInteger(Integer.toString(i))); for(int i=n-1;i>=0;i--) { for(int j=s[i]-1;j>=0;j--) { //A hook length hook(x) of a box x in Young diagram Y(λ) of shape λ //is the number of boxes that are in the same row to the right of it //plus those boxes in the same column below it, young[i][j]=0; if(i!=n-1) young[i][j]+=young[i+1][j]+1; ans=ans.divide(new BigInteger(Integer.toString(young[i][j]+s[i]-j))); } } //ans=n!/MUL(hook(x)) System.out.println(ans.toString()); } } }
false
918
122
1,065
156
1,029
135
1,065
156
1,260
203
false
false
false
false
false
true
4720_0
package org.wolflink.sharine.enums; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public enum UserRelationEnum { NONE(0, "原创"), FOLLOW(1, "关注"), FOLLOWED(2, "被关注"), FRIEND(3, "朋友"); /** * 状态码 */ private final Integer code; /** * 描述 */ private final String desc; }
WolfLink-DevTeam/Sharine
server/common/src/main/java/org/wolflink/sharine/enums/UserRelationEnum.java
113
/** * 状态码 */
block_comment
zh-cn
package org.wolflink.sharine.enums; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public enum UserRelationEnum { NONE(0, "原创"), FOLLOW(1, "关注"), FOLLOWED(2, "被关注"), FRIEND(3, "朋友"); /** * 状态码 <SUF>*/ private final Integer code; /** * 描述 */ private final String desc; }
false
94
9
113
8
114
9
113
8
152
11
false
false
false
false
false
true
53977_8
package car; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class M { static Scanner scanner; static Database database; public static void main(String[] args) { database = new Database(); scanner = new Scanner(System.in); String choose; System.out.println("输入1进入cms模块,输入2进入客户端:"); int enter = scanner.nextInt(); switch (enter) { case 1://进入cms模块 System.out.println("输入1查询车辆信息,输入2插入车辆信息,输入3删除车辆信息,输入4修改车辆信息:"); int enter_1 = scanner.nextInt(); switch (enter_1) { case 1://查询并显示车辆信息 System.out.println("输入1查询所有车辆信息,输入2查询所有小车信息,输入3查询所有客车信息"); int SelectCarData = scanner.nextInt(); switch (SelectCarData) { case 1: database.select(); break; case 2: MotoVehicle.Obvious(new Mcar());//向上转型,通过父类自动选择相对应的类的方法,执行子类重写的方法 break; case 3: MotoVehicle.Obvious(new Bus()); break; } System.out.println("数据查询成功"); break; case 2://插入车辆信息 insert(); break; case 3://删除车辆信息 System.out.println("输入你要删除车辆信息的车牌号:"); choose = scanner.next(); database.delete(choose, "Num"); break; case 4://修改车辆信息 System.out.println("输入车牌号选定要修改信息的车辆:"); choose = scanner.next(); database.select(choose,"Num"); System.out.println("输入要修改的信息的所在列名(车型、车牌、颜色、品牌、座位数、型号、里程、租金)"); String change = scanner.next(); System.out.println("输入要修改信息的内容"); String get_content = scanner.next(); database.change(get_content,change,choose); break; } break; case 2://进入客户端模式 Map<String, Integer> getMap = new HashMap<>(); database.select(); while (true) { System.out.println("输入心仪的车牌号进行车辆选择:"); choose = scanner.next(); database.select(choose, "Num"); String getType = database.getType();//获得车的类型 System.out.println("输入租借天数:"); int date_count = scanner.nextInt(); getMap.put(getType, date_count); System.out.println("输入1继续选择车辆,输入2结束车辆的选择:"); int over = scanner.nextInt(); if (over == 2) { break; } } new Client().CalcRent(getMap); break; } } // 插入车辆信息的方法 public static void insert() { System.out.println("输入车辆类型(小车、客车):"); String gCarType = scanner.next(); System.out.println("输入车辆车牌(6位字符串):"); String gNum = scanner.next(); System.out.println("输入车辆颜色:"); String gColor = scanner.next(); System.out.println("输入车辆品牌:"); String gBrand = scanner.next(); System.out.println("输入车辆座位数:"); int gSeacount = Integer.parseInt(scanner.next()); System.out.println("输入车辆型号:"); String gType = scanner.next(); System.out.println("输入车辆里程(km):"); int gMeleage = Integer.parseInt(scanner.next()); System.out.println("输入车辆租金:"); int gRent = scanner.nextInt(); if (gCarType.equals("小车")) { Mcar mcar = new Mcar(gCarType, gNum, gColor, gBrand, gSeacount, gType, gMeleage, gRent); System.out.println("数据插入成功"); } else if (gCarType.equals("客车")) { Bus bus = new Bus(gCarType, gNum, gColor, gBrand, gSeacount, gType, gMeleage, gRent); System.out.println("数据插入成功"); } } }
Wranglery/car_preject_java
src/car/M.java
1,076
// 插入车辆信息的方法
line_comment
zh-cn
package car; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class M { static Scanner scanner; static Database database; public static void main(String[] args) { database = new Database(); scanner = new Scanner(System.in); String choose; System.out.println("输入1进入cms模块,输入2进入客户端:"); int enter = scanner.nextInt(); switch (enter) { case 1://进入cms模块 System.out.println("输入1查询车辆信息,输入2插入车辆信息,输入3删除车辆信息,输入4修改车辆信息:"); int enter_1 = scanner.nextInt(); switch (enter_1) { case 1://查询并显示车辆信息 System.out.println("输入1查询所有车辆信息,输入2查询所有小车信息,输入3查询所有客车信息"); int SelectCarData = scanner.nextInt(); switch (SelectCarData) { case 1: database.select(); break; case 2: MotoVehicle.Obvious(new Mcar());//向上转型,通过父类自动选择相对应的类的方法,执行子类重写的方法 break; case 3: MotoVehicle.Obvious(new Bus()); break; } System.out.println("数据查询成功"); break; case 2://插入车辆信息 insert(); break; case 3://删除车辆信息 System.out.println("输入你要删除车辆信息的车牌号:"); choose = scanner.next(); database.delete(choose, "Num"); break; case 4://修改车辆信息 System.out.println("输入车牌号选定要修改信息的车辆:"); choose = scanner.next(); database.select(choose,"Num"); System.out.println("输入要修改的信息的所在列名(车型、车牌、颜色、品牌、座位数、型号、里程、租金)"); String change = scanner.next(); System.out.println("输入要修改信息的内容"); String get_content = scanner.next(); database.change(get_content,change,choose); break; } break; case 2://进入客户端模式 Map<String, Integer> getMap = new HashMap<>(); database.select(); while (true) { System.out.println("输入心仪的车牌号进行车辆选择:"); choose = scanner.next(); database.select(choose, "Num"); String getType = database.getType();//获得车的类型 System.out.println("输入租借天数:"); int date_count = scanner.nextInt(); getMap.put(getType, date_count); System.out.println("输入1继续选择车辆,输入2结束车辆的选择:"); int over = scanner.nextInt(); if (over == 2) { break; } } new Client().CalcRent(getMap); break; } } // 插入 <SUF> public static void insert() { System.out.println("输入车辆类型(小车、客车):"); String gCarType = scanner.next(); System.out.println("输入车辆车牌(6位字符串):"); String gNum = scanner.next(); System.out.println("输入车辆颜色:"); String gColor = scanner.next(); System.out.println("输入车辆品牌:"); String gBrand = scanner.next(); System.out.println("输入车辆座位数:"); int gSeacount = Integer.parseInt(scanner.next()); System.out.println("输入车辆型号:"); String gType = scanner.next(); System.out.println("输入车辆里程(km):"); int gMeleage = Integer.parseInt(scanner.next()); System.out.println("输入车辆租金:"); int gRent = scanner.nextInt(); if (gCarType.equals("小车")) { Mcar mcar = new Mcar(gCarType, gNum, gColor, gBrand, gSeacount, gType, gMeleage, gRent); System.out.println("数据插入成功"); } else if (gCarType.equals("客车")) { Bus bus = new Bus(gCarType, gNum, gColor, gBrand, gSeacount, gType, gMeleage, gRent); System.out.println("数据插入成功"); } } }
false
905
8
1,076
10
1,090
6
1,076
10
1,606
17
false
false
false
false
false
true
33215_1
package com.tile.screenoff; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; public class BinderContainer implements Parcelable { // implements Parcelable 之后,这个类就可以作为intent的附加参数了。 private final IBinder binder; public BinderContainer(IBinder binder) { this.binder = binder; } public IBinder getBinder() { //用这个函数来取出binder。其他函数都是自动生成的,只有这个函数是我自己写的。足以见得这个函数是多么的重要、多么的有技术含量 return binder; } protected BinderContainer(Parcel in) { binder = in.readStrongBinder(); } public static final Creator<BinderContainer> CREATOR = new Creator<BinderContainer>() { @Override public BinderContainer createFromParcel(Parcel in) { return new BinderContainer(in); } @Override public BinderContainer[] newArray(int size) { return new BinderContainer[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeStrongBinder(binder); } }
WuDi-ZhanShen/ScreenOff
app/src/main/java/com/tile/screenoff/BinderContainer.java
293
//用这个函数来取出binder。其他函数都是自动生成的,只有这个函数是我自己写的。足以见得这个函数是多么的重要、多么的有技术含量
line_comment
zh-cn
package com.tile.screenoff; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; public class BinderContainer implements Parcelable { // implements Parcelable 之后,这个类就可以作为intent的附加参数了。 private final IBinder binder; public BinderContainer(IBinder binder) { this.binder = binder; } public IBinder getBinder() { //用这 <SUF> return binder; } protected BinderContainer(Parcel in) { binder = in.readStrongBinder(); } public static final Creator<BinderContainer> CREATOR = new Creator<BinderContainer>() { @Override public BinderContainer createFromParcel(Parcel in) { return new BinderContainer(in); } @Override public BinderContainer[] newArray(int size) { return new BinderContainer[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeStrongBinder(binder); } }
false
252
37
290
45
293
35
290
45
390
69
false
false
false
false
false
true
4972_9
package com.kakarote.core.common.enums; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Objects; /** * 日期筛选枚举 * * @author zhangzhiwei */ @ApiModel("日期筛选枚举") public enum DateFilterEnum { /** * 自定义 */ @ApiModelProperty("自定义") CUSTOM("custom"), /** * 今天 */ @ApiModelProperty("今天") TODAY("today"), /** * 昨天 */ @ApiModelProperty("昨天") YESTERDAY("yesterday"), /** * 明天 */ @ApiModelProperty("明天") TOMORROW("tomorrow"), /** * 本周 */ @ApiModelProperty("本周") WEEK("week"), /** * 上周 */ @ApiModelProperty("上周") LAST_WEEK("lastWeek"), /** * 下周 */ @ApiModelProperty("下周") NEXT_WEEK("nextWeek"), /** * 本月 */ @ApiModelProperty("本月") MONTH("month"), /** * 上月 */ @ApiModelProperty("上月") LAST_MONTH("lastMonth"), /** * 下月 */ @ApiModelProperty("下月") NEXT_MONTH("nextMonth"), /** * 本季度 */ @ApiModelProperty("本季度") QUARTER("quarter"), /** * 上季度 */ @ApiModelProperty("上季度") LAST_QUARTER("lastQuarter"), /** * 下季度 */ @ApiModelProperty("下季度") NEXT_QUARTER("nextQuarter"), /** * 本年 */ @ApiModelProperty("本年") YEAR("year"), /** * 上一年 */ @ApiModelProperty("上一年") LAST_YEAR("lastYear"), /** * 下一年 */ @ApiModelProperty("下一年") NEXT_YEAR("nextYear"), /** * 上半年 */ FIRST_HALF_YEAR("firstHalfYear"), /** * 下半年 */ NEXT_HALF_YEAR("nextHalfYear"), /** * 过去七天 */ previous7day("previous7day"), /** * 过去30天 */ previous30day("previous30day"), /** * 未来7天 */ future7day("future7day"), /** * 未来30天 */ future30day("future30day"), ; DateFilterEnum(String value) { this.value = value; } private final String value; public String getValue() { return value; } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static DateFilterEnum parse(String value) { for (DateFilterEnum dateFilterEnum : values()) { if (Objects.equals(value, dateFilterEnum.getValue())) { return dateFilterEnum; } } return MONTH; } @Override public String toString() { return this.value; } }
WuKongOpenSource/Wukong_HRM
common/common-web/src/main/java/com/kakarote/core/common/enums/DateFilterEnum.java
737
/** * 上月 */
block_comment
zh-cn
package com.kakarote.core.common.enums; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Objects; /** * 日期筛选枚举 * * @author zhangzhiwei */ @ApiModel("日期筛选枚举") public enum DateFilterEnum { /** * 自定义 */ @ApiModelProperty("自定义") CUSTOM("custom"), /** * 今天 */ @ApiModelProperty("今天") TODAY("today"), /** * 昨天 */ @ApiModelProperty("昨天") YESTERDAY("yesterday"), /** * 明天 */ @ApiModelProperty("明天") TOMORROW("tomorrow"), /** * 本周 */ @ApiModelProperty("本周") WEEK("week"), /** * 上周 */ @ApiModelProperty("上周") LAST_WEEK("lastWeek"), /** * 下周 */ @ApiModelProperty("下周") NEXT_WEEK("nextWeek"), /** * 本月 */ @ApiModelProperty("本月") MONTH("month"), /** * 上月 <SUF>*/ @ApiModelProperty("上月") LAST_MONTH("lastMonth"), /** * 下月 */ @ApiModelProperty("下月") NEXT_MONTH("nextMonth"), /** * 本季度 */ @ApiModelProperty("本季度") QUARTER("quarter"), /** * 上季度 */ @ApiModelProperty("上季度") LAST_QUARTER("lastQuarter"), /** * 下季度 */ @ApiModelProperty("下季度") NEXT_QUARTER("nextQuarter"), /** * 本年 */ @ApiModelProperty("本年") YEAR("year"), /** * 上一年 */ @ApiModelProperty("上一年") LAST_YEAR("lastYear"), /** * 下一年 */ @ApiModelProperty("下一年") NEXT_YEAR("nextYear"), /** * 上半年 */ FIRST_HALF_YEAR("firstHalfYear"), /** * 下半年 */ NEXT_HALF_YEAR("nextHalfYear"), /** * 过去七天 */ previous7day("previous7day"), /** * 过去30天 */ previous30day("previous30day"), /** * 未来7天 */ future7day("future7day"), /** * 未来30天 */ future30day("future30day"), ; DateFilterEnum(String value) { this.value = value; } private final String value; public String getValue() { return value; } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static DateFilterEnum parse(String value) { for (DateFilterEnum dateFilterEnum : values()) { if (Objects.equals(value, dateFilterEnum.getValue())) { return dateFilterEnum; } } return MONTH; } @Override public String toString() { return this.value; } }
false
678
8
737
7
807
9
737
7
1,029
10
false
false
false
false
false
true
63658_4
package com.kakarote.work.service; import com.alibaba.fastjson.JSONObject; import com.kakarote.common.result.BasePage; import com.kakarote.common.servlet.BaseService; import com.kakarote.work.common.project.BatchSetTaskBO; import com.kakarote.work.common.project.ProjectTaskUserSortBO; import com.kakarote.work.common.project.ProjectUserTaskQueryBO; import com.kakarote.work.entity.BO.*; import com.kakarote.work.entity.PO.ProjectTask; import com.kakarote.work.entity.VO.*; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * <p> * 任务表 服务类 * </p> * * @author bai * @since 2022-09-08 */ public interface IProjectTaskService extends BaseService<ProjectTask> { public void saveProjectTask(ProjectTask projectTask); public ProjectTask queryProjectTaskById(Long projectTaskId); public Boolean updateProjectTask(ProjectTask projectTask); public BasePage<ProjectTask> queryProjectTaskList(ProjectTaskQueryBO projectTaskQueryBO); public ProjectTaskCountVO getProjectByTime(ProjectTaskCountBO projectTaskQueryBO); public ProjectTaskCountVO getTaskByTime(ProjectTaskCountBO projectTaskQueryBO); public List<ProjectTaskBurnoutVO> getTaskBurnout(ProjectTaskCountBO projectTaskQueryBO); public ProjectTaskEventCountVO getProjectTaskEvent(ProjectTaskCountBO projectTaskCountBO); public BasePage<ProjectTask> getAllMatters(@RequestBody ProjectTaskQueryBO projectTaskQueryBO); public BasePage<ProjectTask> getAllMattersByTaskId(@RequestBody ProjectTaskQueryBO projectTaskQueryBO); /** * 功能描述: 待规划列表 * 〈〉 * * @Param: * @Return: * @Author: guole * @Date: 2022/9/28 20:33 */ public BasePage<ProjectTask> queryProjectPlanTaskList(ProjectTaskQueryBO projectTaskQueryBO); /** * 功能描述: 迭代列表 * 〈〉 * * @Param: * @Return: * @Author: guole * @Date: 2022/9/28 20:33 */ public BasePage<ProjectTask> queryProjectIterationTaskList(ProjectTaskQueryBO projectTaskQueryBO); /** * 功能描述: 待规划列表 * 〈〉 * * @Param: * @Return: * @Author: guole * @Date: 2022/9/28 20:33 */ public BasePage<ProjectTask> queryProjectTaskChildList(ProjectTaskQueryBO projectTaskQueryBO); void relevancyChildTask(RelevancyChildTaskBO relevancyChildTaskBO); ProjectTask getProjectTaskDetails(Long taskId); void relevancyBelongIteration(RelevancyBelongIterationBO relevancyBelongIterationBO); void relevancyRelatedDemand(RelevancyRelatedDemandIdBO relatedDemandIdBO); JSONObject excelImport(MultipartFile file, Long projectId, Integer taskType) throws IOException; public void downloadExcel(HttpServletResponse response, Integer taskType) ; public void projectTaskExport( ProjectTaskExportBO taskExportBO, HttpServletResponse response) ; List<JSONObject> projectTaskExportColumn(Integer taskType); /** * 删除任务 */ void deleteTask(Long taskId); /** * 迭代,需求,任务下的看板任务列表 */ List<ProjectBoardVO> queryProjectTaskChildBoardList(ProjectTaskQueryBO projectTaskQueryBO); /** * 对待办事项进行排序 */ void sortBackLog(ProjectTaskUserSortBO pojectTaskUserSortBO); /** * 功能描述: 查询当前用户的任务列表 * 〈〉 * @Param: * @Return: * @Author: guole * @Date: 2023/2/25 15:53 */ public BasePage<ProjectTask> queryUserTaskList(ProjectUserTaskQueryBO userTaskQueryBO); Boolean setProgress( ProjectTask projectTask); Boolean setPriority( ProjectTask projectTask); void setProjectTaskMainUser(@RequestBody ProjectTask projectTask); void batchSetProjectTask(BatchSetTaskBO batchSetTaskBO); void updateProjectTaskTime( ProjectTask projectTask); /** * 功能描述: <br> * 〈查询工作台中各类型数量〉 * @param userTaskQueryBO * @author zyh */ ProjectUserTaskCountVO queryUserTaskCount(ProjectUserTaskQueryBO userTaskQueryBO); void projectTaskSetName(ProjectTaskNameBO projectTaskNameBO); }
WuKongOpenSource/Wukong_ProjectManagement
work/src/main/java/com/kakarote/work/service/IProjectTaskService.java
1,176
/** * 删除任务 */
block_comment
zh-cn
package com.kakarote.work.service; import com.alibaba.fastjson.JSONObject; import com.kakarote.common.result.BasePage; import com.kakarote.common.servlet.BaseService; import com.kakarote.work.common.project.BatchSetTaskBO; import com.kakarote.work.common.project.ProjectTaskUserSortBO; import com.kakarote.work.common.project.ProjectUserTaskQueryBO; import com.kakarote.work.entity.BO.*; import com.kakarote.work.entity.PO.ProjectTask; import com.kakarote.work.entity.VO.*; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * <p> * 任务表 服务类 * </p> * * @author bai * @since 2022-09-08 */ public interface IProjectTaskService extends BaseService<ProjectTask> { public void saveProjectTask(ProjectTask projectTask); public ProjectTask queryProjectTaskById(Long projectTaskId); public Boolean updateProjectTask(ProjectTask projectTask); public BasePage<ProjectTask> queryProjectTaskList(ProjectTaskQueryBO projectTaskQueryBO); public ProjectTaskCountVO getProjectByTime(ProjectTaskCountBO projectTaskQueryBO); public ProjectTaskCountVO getTaskByTime(ProjectTaskCountBO projectTaskQueryBO); public List<ProjectTaskBurnoutVO> getTaskBurnout(ProjectTaskCountBO projectTaskQueryBO); public ProjectTaskEventCountVO getProjectTaskEvent(ProjectTaskCountBO projectTaskCountBO); public BasePage<ProjectTask> getAllMatters(@RequestBody ProjectTaskQueryBO projectTaskQueryBO); public BasePage<ProjectTask> getAllMattersByTaskId(@RequestBody ProjectTaskQueryBO projectTaskQueryBO); /** * 功能描述: 待规划列表 * 〈〉 * * @Param: * @Return: * @Author: guole * @Date: 2022/9/28 20:33 */ public BasePage<ProjectTask> queryProjectPlanTaskList(ProjectTaskQueryBO projectTaskQueryBO); /** * 功能描述: 迭代列表 * 〈〉 * * @Param: * @Return: * @Author: guole * @Date: 2022/9/28 20:33 */ public BasePage<ProjectTask> queryProjectIterationTaskList(ProjectTaskQueryBO projectTaskQueryBO); /** * 功能描述: 待规划列表 * 〈〉 * * @Param: * @Return: * @Author: guole * @Date: 2022/9/28 20:33 */ public BasePage<ProjectTask> queryProjectTaskChildList(ProjectTaskQueryBO projectTaskQueryBO); void relevancyChildTask(RelevancyChildTaskBO relevancyChildTaskBO); ProjectTask getProjectTaskDetails(Long taskId); void relevancyBelongIteration(RelevancyBelongIterationBO relevancyBelongIterationBO); void relevancyRelatedDemand(RelevancyRelatedDemandIdBO relatedDemandIdBO); JSONObject excelImport(MultipartFile file, Long projectId, Integer taskType) throws IOException; public void downloadExcel(HttpServletResponse response, Integer taskType) ; public void projectTaskExport( ProjectTaskExportBO taskExportBO, HttpServletResponse response) ; List<JSONObject> projectTaskExportColumn(Integer taskType); /** * 删除任 <SUF>*/ void deleteTask(Long taskId); /** * 迭代,需求,任务下的看板任务列表 */ List<ProjectBoardVO> queryProjectTaskChildBoardList(ProjectTaskQueryBO projectTaskQueryBO); /** * 对待办事项进行排序 */ void sortBackLog(ProjectTaskUserSortBO pojectTaskUserSortBO); /** * 功能描述: 查询当前用户的任务列表 * 〈〉 * @Param: * @Return: * @Author: guole * @Date: 2023/2/25 15:53 */ public BasePage<ProjectTask> queryUserTaskList(ProjectUserTaskQueryBO userTaskQueryBO); Boolean setProgress( ProjectTask projectTask); Boolean setPriority( ProjectTask projectTask); void setProjectTaskMainUser(@RequestBody ProjectTask projectTask); void batchSetProjectTask(BatchSetTaskBO batchSetTaskBO); void updateProjectTaskTime( ProjectTask projectTask); /** * 功能描述: <br> * 〈查询工作台中各类型数量〉 * @param userTaskQueryBO * @author zyh */ ProjectUserTaskCountVO queryUserTaskCount(ProjectUserTaskQueryBO userTaskQueryBO); void projectTaskSetName(ProjectTaskNameBO projectTaskNameBO); }
false
1,075
8
1,176
7
1,201
9
1,176
7
1,418
12
false
false
false
false
false
true
7225_1
package com.wuxiaolong.wewin.model; /** * Created by Administrator * on 2016/11/3. */ public class TngouNewsDetailModel extends BaseModel { /** * count : 675 * description : 原标题:【图】广东高速公路收费调整哪些车涨价哪些车降价据悉由于广东省高速公路6月底前将接入全国ETC联网,因此6月底起高速收费将要调整 * fcount : 0 * fromname : 人们政协网 * fromurl : http://www.rmzxb.com.cn/sqmy/nywy/2015/06/11/515590.shtml * id : 100 * img : /top/default.jpg * keywords : 广东高速收费将调整 * message : <p> </p> <p> <strong>  原标题:【图】广东高速公路收费调整 哪些车涨价哪些车降价</strong></p> <p>   据悉由于<a target='_blank' href='http://www.tngou.net/news/list/40'>广东省</a>高速公路6月底前将接入全国ETC联网,因此6月底起高速收费将要调整。那么届时哪些车收费降价,哪些车收费升价?</p> <p> &nbsp;</p> <p> <img alt="1" title="1"></p> <p> &nbsp;</p> <p>   伊秀新闻讯,6月11日,广东高速公路收费调整哪些车涨价哪些车降价。据悉由于广东省高速公路6月底前将接入全国ETC联网,因此6月底起高速收费将要调整。那么届时哪些车收费降价,哪些车收费升价?</p> <p>   据悉届时大部分小车的通行费不变,但也有一部分车自费调整。上升的有:车头高度小于1.3米,座位数大于或等于8的小轿车由原一类车上升为二类;40座及以上的大型客车由原三类车上升为四类。但是上调为四类车的40座以上大型客车实施降档收费,即按三类车收费。</p> <p>   下调的有:车头高度大于或等于1.3米的,但座位数小于7座的面包车和小型客车由原二类车下调为一类,单车收费额下降1/3;2轴6轮,10座及以上、19座以下的中型客车,19座大型客车由原三类车下调为二类,单车收费额下降1/4.而货车全部计重收费,总体降价1.7%.一些网友表示,这次降价调整不痛不痒,并没有想象中那么强大啊。而大部分网友还是表示支持,有得降一点就不错了,还想怎么样?</p> <p> &nbsp;</p> * rcount : 0 * time : 1434002582000 * title : 【图】广东高速公路收费调整 哪些车涨价哪些车降价 * topclass : 1 * url : http://www.tngou.net/top/show/100 */ private int count; private String description; private int fcount; private String fromname; private String fromurl; private int id; private String img; private String keywords; private String message; private int rcount; private long time; private String title; private int topclass; private String url; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getFcount() { return fcount; } public void setFcount(int fcount) { this.fcount = fcount; } public String getFromname() { return fromname; } public void setFromname(String fromname) { this.fromname = fromname; } public String getFromurl() { return fromurl; } public void setFromurl(String fromurl) { this.fromurl = fromurl; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getRcount() { return rcount; } public void setRcount(int rcount) { this.rcount = rcount; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getTopclass() { return topclass; } public void setTopclass(int topclass) { this.topclass = topclass; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
WuXiaolong/WeWin
app/src/main/java/com/wuxiaolong/wewin/model/TngouNewsDetailModel.java
1,458
/** * count : 675 * description : 原标题:【图】广东高速公路收费调整哪些车涨价哪些车降价据悉由于广东省高速公路6月底前将接入全国ETC联网,因此6月底起高速收费将要调整 * fcount : 0 * fromname : 人们政协网 * fromurl : http://www.rmzxb.com.cn/sqmy/nywy/2015/06/11/515590.shtml * id : 100 * img : /top/default.jpg * keywords : 广东高速收费将调整 * message : <p> </p> <p> <strong>  原标题:【图】广东高速公路收费调整 哪些车涨价哪些车降价</strong></p> <p>   据悉由于<a target='_blank' href='http://www.tngou.net/news/list/40'>广东省</a>高速公路6月底前将接入全国ETC联网,因此6月底起高速收费将要调整。那么届时哪些车收费降价,哪些车收费升价?</p> <p> &nbsp;</p> <p> <img alt="1" title="1"></p> <p> &nbsp;</p> <p>   伊秀新闻讯,6月11日,广东高速公路收费调整哪些车涨价哪些车降价。据悉由于广东省高速公路6月底前将接入全国ETC联网,因此6月底起高速收费将要调整。那么届时哪些车收费降价,哪些车收费升价?</p> <p>   据悉届时大部分小车的通行费不变,但也有一部分车自费调整。上升的有:车头高度小于1.3米,座位数大于或等于8的小轿车由原一类车上升为二类;40座及以上的大型客车由原三类车上升为四类。但是上调为四类车的40座以上大型客车实施降档收费,即按三类车收费。</p> <p>   下调的有:车头高度大于或等于1.3米的,但座位数小于7座的面包车和小型客车由原二类车下调为一类,单车收费额下降1/3;2轴6轮,10座及以上、19座以下的中型客车,19座大型客车由原三类车下调为二类,单车收费额下降1/4.而货车全部计重收费,总体降价1.7%.一些网友表示,这次降价调整不痛不痒,并没有想象中那么强大啊。而大部分网友还是表示支持,有得降一点就不错了,还想怎么样?</p> <p> &nbsp;</p> * rcount : 0 * time : 1434002582000 * title : 【图】广东高速公路收费调整 哪些车涨价哪些车降价 * topclass : 1 * url : http://www.tngou.net/top/show/100 */
block_comment
zh-cn
package com.wuxiaolong.wewin.model; /** * Created by Administrator * on 2016/11/3. */ public class TngouNewsDetailModel extends BaseModel { /** * cou <SUF>*/ private int count; private String description; private int fcount; private String fromname; private String fromurl; private int id; private String img; private String keywords; private String message; private int rcount; private long time; private String title; private int topclass; private String url; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getFcount() { return fcount; } public void setFcount(int fcount) { this.fcount = fcount; } public String getFromname() { return fromname; } public void setFromname(String fromname) { this.fromname = fromname; } public String getFromurl() { return fromurl; } public void setFromurl(String fromurl) { this.fromurl = fromurl; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getRcount() { return rcount; } public void setRcount(int rcount) { this.rcount = rcount; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getTopclass() { return topclass; } public void setTopclass(int topclass) { this.topclass = topclass; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
false
1,247
689
1,458
855
1,431
740
1,458
855
1,937
1,194
true
true
true
true
true
false
47053_15
package lr; import algorithm.FirstSet; import algorithm.LeftCommonFactor; import algorithm.LeftRecursion; import cfg.CFG; import cfg.production.Production; import cfg.production.SubItem; import cfg.production.SubItemType; import fin.BufferIO; import fin.Fin; import fout.Fout; import fout.attr.ColumnAttr; import fout.attr.FoutGravity; import logger.Log; import slr.ProductionIdGenerate; import java.util.*; public class LR { private CFG cfg; private ProductionIdGenerate idGenerate; private ItemCollection lrItemCollection; // key是项集符号,value是<终结符或非终结符,动作> private Map<Integer, Map<String, Action>> actionTables; // key是项集编号,value是<终结符或非终结符,产生式编号> private Map<Integer, Map<String, Integer>> gotoTables; private BufferIO buffer; private Stack<Integer> itemSetIdStack; public LR(CFG cfg) { this.cfg = cfg.copy(); // 提取左公因子,消除左递归 cfg = new LeftCommonFactor(cfg).extract(); cfg = new LeftRecursion(cfg).eliminate(); // 获取项集族 lrItemCollection = new ItemCollection(this.cfg, new FirstSet(cfg)); lrItemCollection.generateItemCollection(); lrItemCollection.resetId(); idGenerate = lrItemCollection.getIdGenerate(); this.actionTables = new LinkedHashMap<>(); this.gotoTables = new LinkedHashMap<>(); this.cfg.printProduction(); lrItemCollection.printItemCollection(); Fin utils = Fin.getInstance(); this.buffer = new BufferIO.Builder().setFilePath(utils.getProjectPath() + "/src/data/input/input.i").build(); this.buffer.reset(); this.itemSetIdStack = new Stack<>(); // 将开始项集的编号加入到栈中 this.itemSetIdStack.push(lrItemCollection.getStartItemSet().getId()); } public void construct() { // 对项集族遍历 var collection = lrItemCollection.getLrItemSets(); for (ItemSet itemSet : collection) { Map<String, Action> singleAction = new HashMap<>(); Map<String, Integer> singleGoto = new HashMap<>(); actionTables.put(itemSet.getId(), singleAction); gotoTables.put(itemSet.getId(), singleGoto); // 项,也是产生式 for (Item item : itemSet.getLrItems()) { SubItem subItem = item.getExpectSubItem(); if (subItem != null) { var itemSetGotoTable = itemSet.getGotoTables(); if (subItem.getType() == SubItemType.nonTerminal) { // add gotoTables int jmpItemSetId = itemSetGotoTable.get(subItem.getValue()).getId(); singleGoto.put(subItem.getValue(), jmpItemSetId); } else { // add actionTables int jmpItemSetId = itemSetGotoTable.get(subItem.getValue()).getId(); Action action = new Action(ActionType.shift, jmpItemSetId); singleAction.put(subItem.getValue(), action); } } else { // 获取产生式头部,然后找到Follow(head) String head = item.getProductionHead(); if (head.equals(this.cfg.getStartSymbol())) { Action action = new Action(ActionType.accept, -1); singleAction.put("$", action); continue; } for (String s : item.getLookheads()) { Action action = new Action(ActionType.reduce, item.getProductionId()); singleAction.put(s, action); } } } var itsGoto = itemSet.getGotoTables().entrySet(); for (var item : itsGoto) { if (cfg.getTerminals().contains(item.getKey())) continue; singleGoto.put(item.getKey(), item.getValue().getId()); } } } /** * 一个项集对应一个Action集 */ class Action { // 一个Action包含动作类型和项集编号 ActionType type; int id; public Action(ActionType type, int id) { this.type = type; this.id = id; } } enum ActionType { shift, // 移入 reduce, // 归约 accept, // 接受 error; // 报错 public static String convert(ActionType type) { switch (type) { case shift: return "s"; case reduce: return "r"; case accept: return "acc"; case error: return "error"; } return ""; } } public void execute() { Fout fout = new Fout(); fout.addColumn(new ColumnAttr("Stack", FoutGravity.LEFT)); fout.addColumn(new ColumnAttr("Symbol", FoutGravity.LEFT)); fout.addColumn(new ColumnAttr("Input", FoutGravity.RIGHT)); fout.addColumn(new ColumnAttr("Action", FoutGravity.LEFT)); String inputStr = getNextInput(); String actionStr = ""; List<String> symbolList = new ArrayList<>(); StringBuilder symbolStr; String morphemeStr = ""; StringBuilder stackStr; while (true) { Integer peekId = itemSetIdStack.peek(); Action action = actionTables.get(peekId).get(inputStr); stackStr = new StringBuilder(); symbolStr = new StringBuilder(); if (action.type == ActionType.shift) { for (int item : itemSetIdStack) { stackStr.append(item).append(" "); } for (String str : symbolList) { symbolStr.append(str).append(" "); } actionStr = "Shift -> " + action.id; symbolList.add(inputStr); itemSetIdStack.push(action.id); morphemeStr = inputStr + buffer.getCurrentBufferString(); inputStr = getNextInput(); } else if (action.type == ActionType.reduce) { for (int item : itemSetIdStack) { stackStr.append(item).append(" "); } for (String str : symbolList) { symbolStr.append(str).append(" "); } morphemeStr = inputStr + buffer.getCurrentBufferString(); // 弹出归约个数个符号 Production p = idGenerate.getProduction(action.id); int num = p.getSubItems().size(); //产生式编号 for (int i = num; i > 0; i--) { itemSetIdStack.pop(); } // 将Goto[t, A]压入 peekId = itemSetIdStack.peek(); // 项集编号 String head = idGenerate.getProductionHead(action.id); // 产生式编号 var singleGoto = gotoTables.get(peekId); if (singleGoto.containsKey(head)) { int itemSetId = singleGoto.get(head); itemSetIdStack.push(itemSetId); } else { Log.error("not found head error!"); } actionStr = "According to [" + idGenerate.getProductionHead(action.id) + " -> " + p.getProductionStr() + "] reduce."; for (int i = num, j = symbolList.size() - 1; i > 0; i--, j--) { symbolList.remove(j); } symbolList.add(head); } else if (action.type == ActionType.accept) { for (int item : itemSetIdStack) { stackStr.append(item).append(" "); } for (String str : symbolList) { symbolStr.append(str).append(" "); } Log.debug("success!"); fout.insertln(stackStr.toString(), symbolStr.toString(), morphemeStr, "Accept!"); break; } else if (action.type == ActionType.error) { Log.error("identify error!"); } fout.insertln(stackStr.toString(), symbolStr.toString(), morphemeStr, actionStr); } fout.fout(); } private String getNextInput() { char c = buffer.nextChar(); if (c == ' ' || c == '\t' || c == '\n') { while (c == ' ' || c == '\t' || c == '\n') c = buffer.nextChar(); buffer.nextMorpheme(); } while (true) { if (BufferIO.stopLexicalAnalysis) break; c = buffer.nextChar(); if (c == ' ' || c == '\t' || c == '\n') break; } return buffer.nextMorpheme(); } public void printActionAndGoto() { Fout fout = new Fout(ColumnAttr.qCreate("State", "Action", "Goto")); String[] terminals = null; if (cfg.getTerminals().contains("ε")) { terminals = new String[cfg.getTerminals().size()]; } else terminals = new String[cfg.getTerminals().size() + 1]; cfg.getTerminals().toArray(terminals); boolean hasDollar = false; for (int i = 0; i < terminals.length; i++) { if (String.valueOf(terminals[i]).equals("ε")) { terminals[i] = "$"; hasDollar = true; } } if (!hasDollar) terminals[terminals.length - 1] = "$"; fout.addSubColumn("Action", ColumnAttr.qCreate(terminals)); Object[] nonTerminals = cfg.getNonTerminals().toArray(); fout.addSubColumn("Goto", ColumnAttr.qCreate(nonTerminals)); for (int i = 0; i <= ItemSet.itemSetIdCount; i++) { Map<String, Action> singleAction = actionTables.get(i); Map<String, Integer> singleGoto = gotoTables.get(i); fout.insert(i); String str = ""; for (Object terminal : terminals) { Action action = singleAction.get(String.valueOf(terminal)); if (action == null) str = ""; else { if (action.type == ActionType.accept || action.type == ActionType.error) { str = ActionType.convert(action.type); } else { str = ActionType.convert(action.type) + action.id; } } fout.insert(str); } for (Object nonTerminal : nonTerminals) { if (singleGoto.containsKey(String.valueOf(nonTerminal))) { str = String.valueOf(singleGoto.get(String.valueOf(nonTerminal))); } else { str = ""; } fout.insert(str); } } fout.fout(); } }
Wwqf/Parsing
src/lr/LR.java
2,750
// 项集编号
line_comment
zh-cn
package lr; import algorithm.FirstSet; import algorithm.LeftCommonFactor; import algorithm.LeftRecursion; import cfg.CFG; import cfg.production.Production; import cfg.production.SubItem; import cfg.production.SubItemType; import fin.BufferIO; import fin.Fin; import fout.Fout; import fout.attr.ColumnAttr; import fout.attr.FoutGravity; import logger.Log; import slr.ProductionIdGenerate; import java.util.*; public class LR { private CFG cfg; private ProductionIdGenerate idGenerate; private ItemCollection lrItemCollection; // key是项集符号,value是<终结符或非终结符,动作> private Map<Integer, Map<String, Action>> actionTables; // key是项集编号,value是<终结符或非终结符,产生式编号> private Map<Integer, Map<String, Integer>> gotoTables; private BufferIO buffer; private Stack<Integer> itemSetIdStack; public LR(CFG cfg) { this.cfg = cfg.copy(); // 提取左公因子,消除左递归 cfg = new LeftCommonFactor(cfg).extract(); cfg = new LeftRecursion(cfg).eliminate(); // 获取项集族 lrItemCollection = new ItemCollection(this.cfg, new FirstSet(cfg)); lrItemCollection.generateItemCollection(); lrItemCollection.resetId(); idGenerate = lrItemCollection.getIdGenerate(); this.actionTables = new LinkedHashMap<>(); this.gotoTables = new LinkedHashMap<>(); this.cfg.printProduction(); lrItemCollection.printItemCollection(); Fin utils = Fin.getInstance(); this.buffer = new BufferIO.Builder().setFilePath(utils.getProjectPath() + "/src/data/input/input.i").build(); this.buffer.reset(); this.itemSetIdStack = new Stack<>(); // 将开始项集的编号加入到栈中 this.itemSetIdStack.push(lrItemCollection.getStartItemSet().getId()); } public void construct() { // 对项集族遍历 var collection = lrItemCollection.getLrItemSets(); for (ItemSet itemSet : collection) { Map<String, Action> singleAction = new HashMap<>(); Map<String, Integer> singleGoto = new HashMap<>(); actionTables.put(itemSet.getId(), singleAction); gotoTables.put(itemSet.getId(), singleGoto); // 项,也是产生式 for (Item item : itemSet.getLrItems()) { SubItem subItem = item.getExpectSubItem(); if (subItem != null) { var itemSetGotoTable = itemSet.getGotoTables(); if (subItem.getType() == SubItemType.nonTerminal) { // add gotoTables int jmpItemSetId = itemSetGotoTable.get(subItem.getValue()).getId(); singleGoto.put(subItem.getValue(), jmpItemSetId); } else { // add actionTables int jmpItemSetId = itemSetGotoTable.get(subItem.getValue()).getId(); Action action = new Action(ActionType.shift, jmpItemSetId); singleAction.put(subItem.getValue(), action); } } else { // 获取产生式头部,然后找到Follow(head) String head = item.getProductionHead(); if (head.equals(this.cfg.getStartSymbol())) { Action action = new Action(ActionType.accept, -1); singleAction.put("$", action); continue; } for (String s : item.getLookheads()) { Action action = new Action(ActionType.reduce, item.getProductionId()); singleAction.put(s, action); } } } var itsGoto = itemSet.getGotoTables().entrySet(); for (var item : itsGoto) { if (cfg.getTerminals().contains(item.getKey())) continue; singleGoto.put(item.getKey(), item.getValue().getId()); } } } /** * 一个项集对应一个Action集 */ class Action { // 一个Action包含动作类型和项集编号 ActionType type; int id; public Action(ActionType type, int id) { this.type = type; this.id = id; } } enum ActionType { shift, // 移入 reduce, // 归约 accept, // 接受 error; // 报错 public static String convert(ActionType type) { switch (type) { case shift: return "s"; case reduce: return "r"; case accept: return "acc"; case error: return "error"; } return ""; } } public void execute() { Fout fout = new Fout(); fout.addColumn(new ColumnAttr("Stack", FoutGravity.LEFT)); fout.addColumn(new ColumnAttr("Symbol", FoutGravity.LEFT)); fout.addColumn(new ColumnAttr("Input", FoutGravity.RIGHT)); fout.addColumn(new ColumnAttr("Action", FoutGravity.LEFT)); String inputStr = getNextInput(); String actionStr = ""; List<String> symbolList = new ArrayList<>(); StringBuilder symbolStr; String morphemeStr = ""; StringBuilder stackStr; while (true) { Integer peekId = itemSetIdStack.peek(); Action action = actionTables.get(peekId).get(inputStr); stackStr = new StringBuilder(); symbolStr = new StringBuilder(); if (action.type == ActionType.shift) { for (int item : itemSetIdStack) { stackStr.append(item).append(" "); } for (String str : symbolList) { symbolStr.append(str).append(" "); } actionStr = "Shift -> " + action.id; symbolList.add(inputStr); itemSetIdStack.push(action.id); morphemeStr = inputStr + buffer.getCurrentBufferString(); inputStr = getNextInput(); } else if (action.type == ActionType.reduce) { for (int item : itemSetIdStack) { stackStr.append(item).append(" "); } for (String str : symbolList) { symbolStr.append(str).append(" "); } morphemeStr = inputStr + buffer.getCurrentBufferString(); // 弹出归约个数个符号 Production p = idGenerate.getProduction(action.id); int num = p.getSubItems().size(); //产生式编号 for (int i = num; i > 0; i--) { itemSetIdStack.pop(); } // 将Goto[t, A]压入 peekId = itemSetIdStack.peek(); // 项集 <SUF> String head = idGenerate.getProductionHead(action.id); // 产生式编号 var singleGoto = gotoTables.get(peekId); if (singleGoto.containsKey(head)) { int itemSetId = singleGoto.get(head); itemSetIdStack.push(itemSetId); } else { Log.error("not found head error!"); } actionStr = "According to [" + idGenerate.getProductionHead(action.id) + " -> " + p.getProductionStr() + "] reduce."; for (int i = num, j = symbolList.size() - 1; i > 0; i--, j--) { symbolList.remove(j); } symbolList.add(head); } else if (action.type == ActionType.accept) { for (int item : itemSetIdStack) { stackStr.append(item).append(" "); } for (String str : symbolList) { symbolStr.append(str).append(" "); } Log.debug("success!"); fout.insertln(stackStr.toString(), symbolStr.toString(), morphemeStr, "Accept!"); break; } else if (action.type == ActionType.error) { Log.error("identify error!"); } fout.insertln(stackStr.toString(), symbolStr.toString(), morphemeStr, actionStr); } fout.fout(); } private String getNextInput() { char c = buffer.nextChar(); if (c == ' ' || c == '\t' || c == '\n') { while (c == ' ' || c == '\t' || c == '\n') c = buffer.nextChar(); buffer.nextMorpheme(); } while (true) { if (BufferIO.stopLexicalAnalysis) break; c = buffer.nextChar(); if (c == ' ' || c == '\t' || c == '\n') break; } return buffer.nextMorpheme(); } public void printActionAndGoto() { Fout fout = new Fout(ColumnAttr.qCreate("State", "Action", "Goto")); String[] terminals = null; if (cfg.getTerminals().contains("ε")) { terminals = new String[cfg.getTerminals().size()]; } else terminals = new String[cfg.getTerminals().size() + 1]; cfg.getTerminals().toArray(terminals); boolean hasDollar = false; for (int i = 0; i < terminals.length; i++) { if (String.valueOf(terminals[i]).equals("ε")) { terminals[i] = "$"; hasDollar = true; } } if (!hasDollar) terminals[terminals.length - 1] = "$"; fout.addSubColumn("Action", ColumnAttr.qCreate(terminals)); Object[] nonTerminals = cfg.getNonTerminals().toArray(); fout.addSubColumn("Goto", ColumnAttr.qCreate(nonTerminals)); for (int i = 0; i <= ItemSet.itemSetIdCount; i++) { Map<String, Action> singleAction = actionTables.get(i); Map<String, Integer> singleGoto = gotoTables.get(i); fout.insert(i); String str = ""; for (Object terminal : terminals) { Action action = singleAction.get(String.valueOf(terminal)); if (action == null) str = ""; else { if (action.type == ActionType.accept || action.type == ActionType.error) { str = ActionType.convert(action.type); } else { str = ActionType.convert(action.type) + action.id; } } fout.insert(str); } for (Object nonTerminal : nonTerminals) { if (singleGoto.containsKey(String.valueOf(nonTerminal))) { str = String.valueOf(singleGoto.get(String.valueOf(nonTerminal))); } else { str = ""; } fout.insert(str); } } fout.fout(); } }
false
2,329
5
2,750
5
2,693
5
2,750
5
3,551
6
false
false
false
false
false
true
44139_5
package com.example.utils; import com.example.domain.Person; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * @Decription TODO * @Author wxm * @Date 2019/3/6 16:07 **/ @Component public class Schedule { public static void main(String[] args) { SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar aa = Calendar.getInstance(); Calendar bb = Calendar.getInstance(); Calendar cc = Calendar.getInstance(); Calendar today = Calendar.getInstance(); SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss"); System.out.println(dateFormat.format(today.getTime())); Person a=new Person(); a.setName("王晓梅"); a.setRelative("自己"); aa.set(2017,3,8); a.setBirth(aa); Person b=new Person(); b.setName("都泓憬"); b.setRelative("儿子"); bb.set(2017,3,7); b.setBirth(bb); Person c=new Person(); c.setName("都德"); c.setRelative("老公"); cc.set(2017,4,9); c.setBirth(cc); List<Person> list=new ArrayList<>(); list.add(a); list.add(b); list.add(c); Date now=new Date(); // a.getBirth().set(Calendar.YEAR,today.get(Calendar.YEAR)); System.out.println("c的生日"+c.getBirth().get(Calendar.DAY_OF_YEAR)); System.out.println("a日期:"+a.getBirth().get(Calendar.DAY_OF_YEAR)); System.out.println("b的生日"+b.getBirth().get(Calendar.DAY_OF_YEAR)); System.out.println("现在的日期:"+today.get(Calendar.DAY_OF_YEAR)); int days; if (a.getBirth().get(Calendar.DAY_OF_YEAR) < b.getBirth().get(Calendar.DAY_OF_YEAR)) { // 生日已经过了,要算明年的了 days = today.getActualMaximum(Calendar.DAY_OF_YEAR) - b.getBirth().get(Calendar.DAY_OF_YEAR); days += a.getBirth().get(Calendar.DAY_OF_YEAR); } else { // 生日还没过 days = a.getBirth().get(Calendar.DAY_OF_YEAR) - b.getBirth().get(Calendar.DAY_OF_YEAR); } if (days == 0) { System.out.println("今天生日"); } else { System.out.println("距离生日还有:" + days + "天"); } // System.out.println((now.getTime()-c.getBirth().getTime())/(60*60*24)); } //秒(0-59),分(0-59),时(0-23),日期天/日(1-31),月份)(1-12),星期(1-7,1表示星晴天,7表示星期六) @Scheduled(cron="0 0/2 * * * * ")//代表每二分钟执行一次 public void start() { /* Person a=new Person(); a.setName("王晓梅"); a.setRelative("自己"); a.setBirth(new Date("2018-03-08")); Person b=new Person(); b.setName("都泓憬"); b.setRelative("儿子"); b.setBirth(new Date("2018-03-09")); Person c=new Person(); c.setName("都德"); c.setRelative("老公"); c.setBirth(new Date("2018-04-08"));*/ List<Person> list = new ArrayList<>(); /* list.add(a); list.add(b); list.add(c);*/ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String aa = "2018-03-09"; String bb = "2018-03-01"; String today = "2018-03-07"; System.out.println(aa); } }
WxmDe/WeChatProgram
miniPro/src/main/java/com/example/utils/Schedule.java
1,118
//秒(0-59),分(0-59),时(0-23),日期天/日(1-31),月份)(1-12),星期(1-7,1表示星晴天,7表示星期六)
line_comment
zh-cn
package com.example.utils; import com.example.domain.Person; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * @Decription TODO * @Author wxm * @Date 2019/3/6 16:07 **/ @Component public class Schedule { public static void main(String[] args) { SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar aa = Calendar.getInstance(); Calendar bb = Calendar.getInstance(); Calendar cc = Calendar.getInstance(); Calendar today = Calendar.getInstance(); SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss"); System.out.println(dateFormat.format(today.getTime())); Person a=new Person(); a.setName("王晓梅"); a.setRelative("自己"); aa.set(2017,3,8); a.setBirth(aa); Person b=new Person(); b.setName("都泓憬"); b.setRelative("儿子"); bb.set(2017,3,7); b.setBirth(bb); Person c=new Person(); c.setName("都德"); c.setRelative("老公"); cc.set(2017,4,9); c.setBirth(cc); List<Person> list=new ArrayList<>(); list.add(a); list.add(b); list.add(c); Date now=new Date(); // a.getBirth().set(Calendar.YEAR,today.get(Calendar.YEAR)); System.out.println("c的生日"+c.getBirth().get(Calendar.DAY_OF_YEAR)); System.out.println("a日期:"+a.getBirth().get(Calendar.DAY_OF_YEAR)); System.out.println("b的生日"+b.getBirth().get(Calendar.DAY_OF_YEAR)); System.out.println("现在的日期:"+today.get(Calendar.DAY_OF_YEAR)); int days; if (a.getBirth().get(Calendar.DAY_OF_YEAR) < b.getBirth().get(Calendar.DAY_OF_YEAR)) { // 生日已经过了,要算明年的了 days = today.getActualMaximum(Calendar.DAY_OF_YEAR) - b.getBirth().get(Calendar.DAY_OF_YEAR); days += a.getBirth().get(Calendar.DAY_OF_YEAR); } else { // 生日还没过 days = a.getBirth().get(Calendar.DAY_OF_YEAR) - b.getBirth().get(Calendar.DAY_OF_YEAR); } if (days == 0) { System.out.println("今天生日"); } else { System.out.println("距离生日还有:" + days + "天"); } // System.out.println((now.getTime()-c.getBirth().getTime())/(60*60*24)); } //秒( <SUF> @Scheduled(cron="0 0/2 * * * * ")//代表每二分钟执行一次 public void start() { /* Person a=new Person(); a.setName("王晓梅"); a.setRelative("自己"); a.setBirth(new Date("2018-03-08")); Person b=new Person(); b.setName("都泓憬"); b.setRelative("儿子"); b.setBirth(new Date("2018-03-09")); Person c=new Person(); c.setName("都德"); c.setRelative("老公"); c.setBirth(new Date("2018-04-08"));*/ List<Person> list = new ArrayList<>(); /* list.add(a); list.add(b); list.add(c);*/ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String aa = "2018-03-09"; String bb = "2018-03-01"; String today = "2018-03-07"; System.out.println(aa); } }
false
896
57
1,118
61
1,155
56
1,118
61
1,329
74
false
false
false
false
false
true
60352_0
package cn.xy.algorithm.BinaryTree.treeDP; import java.util.ArrayList; import java.util.List; /** * @author XiangYu * @create2021-03-29-22:17 * * * 与Code_09_MaxDistanceInTree是一种类型的题 树形DP * * * 一个公司的上下节关系是一棵多叉树, 这个公司要举办晚会, 你作为组织者已经摸清了大家的心理: 一个员工的直 * 接上级如果到场, 这个员工肯定不会来。 每个员工都有一个活跃度的值, 决定谁来你会给这个员工发邀请函, 怎么 * 让舞会的气氛最活跃? 返回最大的活跃值。 * 举例: * 给定一个矩阵来表述这种关系 * matrix = * { 1 * ,6 * 1,5 * 1,4 * } 这 * 个矩阵的含义是: * matrix[0] = {1 , 6}, 表示0这个员工的直接上级为1,0这个员工自己的活跃度为6 * matrix[1] = {1 , 5}, 表示1这个员工的直接上级为1(他自己是这个公司的最大boss) ,1这个员工自己的活跃度 * 为5 * matrix[2] = {1 , 4}, 表示2这个员工的直接上级为1,2这个员工自己的活跃度为4 * 为了让晚会活跃度最大, 应该让1不来, 0和2来。 最后返回活跃度为10 * * * 信息体:头节点来的最大活跃度 头节点不来的最大活跃度 * */ public class Code_03_MaxHappy { public static class Node{ public int huo; public List<Node> next; public Node(int huo){ this.huo = huo; next = new ArrayList<>(); } } public static class ReturnData{ public int lai_huo; public int bu_lai_huo; public ReturnData(int lai_huo,int bu_lai_huo){ this.lai_huo = lai_huo; this.bu_lai_huo = bu_lai_huo; } } public static int getMaxHappy(Node head){ ReturnData data = process(head); return Math.max(data.lai_huo,data.bu_lai_huo); } public static ReturnData process(Node head){ int lai_huo = head.huo ; int bu_lai_huo = 0; for (int i = 0; i < head.next.size(); i++) { Node next = head.next.get(i); ReturnData nextData = process(next); lai_huo += nextData.bu_lai_huo; bu_lai_huo += Math.max(nextData.lai_huo,nextData.bu_lai_huo); } return new ReturnData(lai_huo,bu_lai_huo); } public static int maxHappy(int[][] matrix) { int[][] dp = new int[matrix.length][2]; boolean[] visited = new boolean[matrix.length]; int root = 0; for (int i = 0; i < matrix.length; i++) { if (i == matrix[i][0]) { root = i; } } process(matrix, dp, visited, root); return Math.max(dp[root][0], dp[root][1]); } public static void process(int[][] matrix, int[][] dp, boolean[] visited, int root) { visited[root] = true; dp[root][1] = matrix[root][1]; for (int i = 0; i < matrix.length; i++) { if (matrix[i][0] == root && !visited[i]) { process(matrix, dp, visited, i); dp[root][1] += dp[i][0]; dp[root][0] += Math.max(dp[i][1], dp[i][0]); } } } public static void main(String[] args) { int[][] matrix = { { 1, 8 }, { 1, 9 }, { 1, 10 } }; System.out.println(maxHappy(matrix)); } }
X-Leonidas/FUCK_LeetCode
src/main/cn/xy/algorithm/BinaryTree/treeDP/Code_03_MaxHappy.java
1,117
/** * @author XiangYu * @create2021-03-29-22:17 * * * 与Code_09_MaxDistanceInTree是一种类型的题 树形DP * * * 一个公司的上下节关系是一棵多叉树, 这个公司要举办晚会, 你作为组织者已经摸清了大家的心理: 一个员工的直 * 接上级如果到场, 这个员工肯定不会来。 每个员工都有一个活跃度的值, 决定谁来你会给这个员工发邀请函, 怎么 * 让舞会的气氛最活跃? 返回最大的活跃值。 * 举例: * 给定一个矩阵来表述这种关系 * matrix = * { 1 * ,6 * 1,5 * 1,4 * } 这 * 个矩阵的含义是: * matrix[0] = {1 , 6}, 表示0这个员工的直接上级为1,0这个员工自己的活跃度为6 * matrix[1] = {1 , 5}, 表示1这个员工的直接上级为1(他自己是这个公司的最大boss) ,1这个员工自己的活跃度 * 为5 * matrix[2] = {1 , 4}, 表示2这个员工的直接上级为1,2这个员工自己的活跃度为4 * 为了让晚会活跃度最大, 应该让1不来, 0和2来。 最后返回活跃度为10 * * * 信息体:头节点来的最大活跃度 头节点不来的最大活跃度 * */
block_comment
zh-cn
package cn.xy.algorithm.BinaryTree.treeDP; import java.util.ArrayList; import java.util.List; /** * @au <SUF>*/ public class Code_03_MaxHappy { public static class Node{ public int huo; public List<Node> next; public Node(int huo){ this.huo = huo; next = new ArrayList<>(); } } public static class ReturnData{ public int lai_huo; public int bu_lai_huo; public ReturnData(int lai_huo,int bu_lai_huo){ this.lai_huo = lai_huo; this.bu_lai_huo = bu_lai_huo; } } public static int getMaxHappy(Node head){ ReturnData data = process(head); return Math.max(data.lai_huo,data.bu_lai_huo); } public static ReturnData process(Node head){ int lai_huo = head.huo ; int bu_lai_huo = 0; for (int i = 0; i < head.next.size(); i++) { Node next = head.next.get(i); ReturnData nextData = process(next); lai_huo += nextData.bu_lai_huo; bu_lai_huo += Math.max(nextData.lai_huo,nextData.bu_lai_huo); } return new ReturnData(lai_huo,bu_lai_huo); } public static int maxHappy(int[][] matrix) { int[][] dp = new int[matrix.length][2]; boolean[] visited = new boolean[matrix.length]; int root = 0; for (int i = 0; i < matrix.length; i++) { if (i == matrix[i][0]) { root = i; } } process(matrix, dp, visited, root); return Math.max(dp[root][0], dp[root][1]); } public static void process(int[][] matrix, int[][] dp, boolean[] visited, int root) { visited[root] = true; dp[root][1] = matrix[root][1]; for (int i = 0; i < matrix.length; i++) { if (matrix[i][0] == root && !visited[i]) { process(matrix, dp, visited, i); dp[root][1] += dp[i][0]; dp[root][0] += Math.max(dp[i][1], dp[i][0]); } } } public static void main(String[] args) { int[][] matrix = { { 1, 8 }, { 1, 9 }, { 1, 10 } }; System.out.println(maxHappy(matrix)); } }
false
954
370
1,117
431
1,056
361
1,117
431
1,364
574
true
true
true
true
true
false
52193_8
package com.Utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author 13049 */ public class TokenUtil { private static final long EXPIRE_TIME = 1000 * 60 * 60 * 2; //token过期时间为2小时 private static final String PRIVATE_KEY = "darling"; //密钥 /** * 签名生成 * @param * @return */ public static String sign(String id,int auth,int signin){ String token = ""; Map<String,Object> header = new HashMap<>(); header.put("typ","JWT"); header.put("alg","HS256"); Map<String,Object> claims = new HashMap<>(); //自定义有效载荷部分 claims.put("openId",id); claims.put("auth",auth); claims.put("signin",signin); token = Jwts.builder() //发证人 .setIssuer("auth") //Jwt头 .setHeader(header) //有效载荷 .setClaims(claims) //设定签发时间 .setIssuedAt(new Date()) //设定过期时间 .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME)) //使用HS256算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS256,PRIVATE_KEY) .compact(); return token; } /** * @param token * @return 用户的openId */ public static String getOpenId(String token){ Claims claims = Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return claims.get("openId").toString(); } /** * @param token * @return 用户的角色位 */ public static int getAuth(String token){ Claims claims = Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return (int) claims.get("auth"); } /** * @param token * @return 用户的登录渠道 */ public static int getSignin(String token){ Claims claims = Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return (int) claims.get("signin"); } /** * 验证 token信息 是否正确 * @param token 被解析 JWT * @return 是否正确 */ public static boolean verify(String token){ try{ Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return true; }catch (Exception e){ return false; } } }
X1304951263/User-dynamic-publishing-platform
weChat2.0/src/main/java/com/Utils/TokenUtil.java
752
//设定过期时间
line_comment
zh-cn
package com.Utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author 13049 */ public class TokenUtil { private static final long EXPIRE_TIME = 1000 * 60 * 60 * 2; //token过期时间为2小时 private static final String PRIVATE_KEY = "darling"; //密钥 /** * 签名生成 * @param * @return */ public static String sign(String id,int auth,int signin){ String token = ""; Map<String,Object> header = new HashMap<>(); header.put("typ","JWT"); header.put("alg","HS256"); Map<String,Object> claims = new HashMap<>(); //自定义有效载荷部分 claims.put("openId",id); claims.put("auth",auth); claims.put("signin",signin); token = Jwts.builder() //发证人 .setIssuer("auth") //Jwt头 .setHeader(header) //有效载荷 .setClaims(claims) //设定签发时间 .setIssuedAt(new Date()) //设定 <SUF> .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME)) //使用HS256算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS256,PRIVATE_KEY) .compact(); return token; } /** * @param token * @return 用户的openId */ public static String getOpenId(String token){ Claims claims = Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return claims.get("openId").toString(); } /** * @param token * @return 用户的角色位 */ public static int getAuth(String token){ Claims claims = Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return (int) claims.get("auth"); } /** * @param token * @return 用户的登录渠道 */ public static int getSignin(String token){ Claims claims = Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return (int) claims.get("signin"); } /** * 验证 token信息 是否正确 * @param token 被解析 JWT * @return 是否正确 */ public static boolean verify(String token){ try{ Jwts.parser() //设置 密钥 .setSigningKey(PRIVATE_KEY) //设置需要解析的 token .parseClaimsJws(token).getBody(); return true; }catch (Exception e){ return false; } } }
false
706
5
752
6
797
4
752
6
988
7
false
false
false
false
false
true
52804_4
package com.hongjie.konggu.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.hongjie.konggu.common.ErrorCode; import com.hongjie.konggu.exception.BusinessException; import com.hongjie.konggu.model.domain.Post; import com.hongjie.konggu.model.domain.Tag; import com.hongjie.konggu.model.domain.Users; import com.hongjie.konggu.model.dto.UserDTO; import com.hongjie.konggu.model.request.PostAddRequest; import com.hongjie.konggu.service.PostService; import com.hongjie.konggu.mapper.PostMapper; import com.hongjie.konggu.service.PostTagService; import com.hongjie.konggu.service.UsersService; import com.hongjie.konggu.utils.UserHolder; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.stream.Collectors; /** * @author WHJ * @description 针对表【post(帖子表)】的数据库操作Service实现 * @createDate 2023-06-17 16:31:33 */ @Service @Slf4j public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService{ @Resource private UsersService usersService; @Resource private PostTagService postTagService; /** * 不雅词汇数组 */ private static final String[] PROFANITY_WORDS = { "操你妈", "滚你妈", "吃屎", "去死", "鸡巴", }; /** * 发布帖子 * * @param postAddRequest 帖子信息 * @return {@link Long} */ @Override public Long addPost(PostAddRequest postAddRequest) { // 1. 检查用户是否登录 // 1. 从线程中获取当前用户 UserDTO user = UserHolder.getUser(); if (user == null) { throw new BusinessException(ErrorCode.NOT_LOGIN); } // 2. 获取帖子内容和发布用户ID Post post = new Post(); post.setContent(postAddRequest.getContent()); post.setUserId(user.getId()); // 3. 检查帖子是否合法 validPost(post); // 4. 保存帖子 boolean saveResult = this.save(post); // 5. 返回结果 if(!saveResult){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子信息保存失败"); } return post.getId(); } /** * 查询用户帖子(仅管理员) * * @param userId 用户ID * @return {@link List}<{@link Post}> */ @Override public List<Post> searchPosts(Long userId) { QueryWrapper<Post> queryWrapper = new QueryWrapper<>(); queryWrapper.like("userId",userId); List<Post> postList = list(queryWrapper); if (postList == null) { throw new BusinessException(ErrorCode.NO_FOUND_ERROR); } return postList; } /** * 查询通过审核的帖子 * * @return {@link List}<{@link Post}> */ @Override public List<Post> listByUser() { // 只显示通过审核的 QueryWrapper<Post> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("reviewStatus",1); queryWrapper.orderByDesc("createTime"); List<Post> postList = list(queryWrapper); List<Object> objectList = postList.stream().map(post -> { Users user = usersService.getById(post.getUserId()); Users safetyUser = usersService.getSafetyUser(user); post.setUser(safetyUser); Long postId = post.getId(); List<Tag> tagList = postTagService.searchByPostId(postId); post.setTagList(tagList); return null; }).collect(Collectors.toList()); log.info("STREAM LIST:{}",objectList); return postList; } /** * 检查帖子是否合法 * * @param post 帖子 */ @Override public void validPost(Post post) { String content = post.getContent(); if(StringUtils.isAnyBlank(post.getContent())) { throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子内容不能为空"); } if(content.length() > 8192){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子内容过长"); } if(containsProfanity(content)){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请文明发言"); } } /** * 检测是否包含不文明词汇 * * @param content 帖子内容 * @return 是否包含非法内容 */ @Override public boolean containsProfanity(String content) { for (String word : PROFANITY_WORDS) { if (content.toLowerCase().contains(word)) { return true; } } return false; } }
XCGB/KongGu-background.
src/main/java/com/hongjie/konggu/service/impl/PostServiceImpl.java
1,310
// 1. 从线程中获取当前用户
line_comment
zh-cn
package com.hongjie.konggu.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.hongjie.konggu.common.ErrorCode; import com.hongjie.konggu.exception.BusinessException; import com.hongjie.konggu.model.domain.Post; import com.hongjie.konggu.model.domain.Tag; import com.hongjie.konggu.model.domain.Users; import com.hongjie.konggu.model.dto.UserDTO; import com.hongjie.konggu.model.request.PostAddRequest; import com.hongjie.konggu.service.PostService; import com.hongjie.konggu.mapper.PostMapper; import com.hongjie.konggu.service.PostTagService; import com.hongjie.konggu.service.UsersService; import com.hongjie.konggu.utils.UserHolder; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.stream.Collectors; /** * @author WHJ * @description 针对表【post(帖子表)】的数据库操作Service实现 * @createDate 2023-06-17 16:31:33 */ @Service @Slf4j public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService{ @Resource private UsersService usersService; @Resource private PostTagService postTagService; /** * 不雅词汇数组 */ private static final String[] PROFANITY_WORDS = { "操你妈", "滚你妈", "吃屎", "去死", "鸡巴", }; /** * 发布帖子 * * @param postAddRequest 帖子信息 * @return {@link Long} */ @Override public Long addPost(PostAddRequest postAddRequest) { // 1. 检查用户是否登录 // 1. <SUF> UserDTO user = UserHolder.getUser(); if (user == null) { throw new BusinessException(ErrorCode.NOT_LOGIN); } // 2. 获取帖子内容和发布用户ID Post post = new Post(); post.setContent(postAddRequest.getContent()); post.setUserId(user.getId()); // 3. 检查帖子是否合法 validPost(post); // 4. 保存帖子 boolean saveResult = this.save(post); // 5. 返回结果 if(!saveResult){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子信息保存失败"); } return post.getId(); } /** * 查询用户帖子(仅管理员) * * @param userId 用户ID * @return {@link List}<{@link Post}> */ @Override public List<Post> searchPosts(Long userId) { QueryWrapper<Post> queryWrapper = new QueryWrapper<>(); queryWrapper.like("userId",userId); List<Post> postList = list(queryWrapper); if (postList == null) { throw new BusinessException(ErrorCode.NO_FOUND_ERROR); } return postList; } /** * 查询通过审核的帖子 * * @return {@link List}<{@link Post}> */ @Override public List<Post> listByUser() { // 只显示通过审核的 QueryWrapper<Post> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("reviewStatus",1); queryWrapper.orderByDesc("createTime"); List<Post> postList = list(queryWrapper); List<Object> objectList = postList.stream().map(post -> { Users user = usersService.getById(post.getUserId()); Users safetyUser = usersService.getSafetyUser(user); post.setUser(safetyUser); Long postId = post.getId(); List<Tag> tagList = postTagService.searchByPostId(postId); post.setTagList(tagList); return null; }).collect(Collectors.toList()); log.info("STREAM LIST:{}",objectList); return postList; } /** * 检查帖子是否合法 * * @param post 帖子 */ @Override public void validPost(Post post) { String content = post.getContent(); if(StringUtils.isAnyBlank(post.getContent())) { throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子内容不能为空"); } if(content.length() > 8192){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子内容过长"); } if(containsProfanity(content)){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请文明发言"); } } /** * 检测是否包含不文明词汇 * * @param content 帖子内容 * @return 是否包含非法内容 */ @Override public boolean containsProfanity(String content) { for (String word : PROFANITY_WORDS) { if (content.toLowerCase().contains(word)) { return true; } } return false; } }
false
1,106
12
1,310
10
1,322
10
1,310
10
1,646
15
false
false
false
false
false
true
31726_6
package Day18.com.hspedu.single_; public class SingleTon01 { public static void main(String[] args) { // Girlfriend girlfriend1 = new Girlfriend("小红");//new 一个对象 // Girlfriend girlfriend2 = new Girlfriend("小花");//再new 一个对象 Girlfriend instance1=Girlfriend.getInstance();//这里就体现出了 // 要把Girlfriend类的 对象 和 返回对象的方法 设成静态的原因 //在不创建实例对象的情况下就能调用这个类里的方法 System.out.println(instance1); System.out.println("=======这两个是同一个对象(地址相同)=============================="); Girlfriend instance2=Girlfriend.getInstance();//因为只在类加载的时候 初始化静态对象, System.out.println(instance2); } } class Girlfriend{//定义 女朋友 类 private String name; //因为要被公共的静态方法获取,所以 这个对象要是静态的 private static Girlfriend girlfriend1 = new Girlfriend("小花"); /**【饿汉式 单例设计模式】,饿汉式可能造成创建了但是没使用对象的尴尬 * * 如何保证我们只能创建一个Girlfriend对象 * 1.将构造器私有化 * 2.在类 的内部 new对象 , 但主方法里还是不能使用这个私有的静态对象 * 3.提供一个公共的static方法,用来返回这个对象 * 当加载了Girlfriend类时,就创建对象 */ //构造器私有化 之后 ,无法在主方法里new对象 private Girlfriend(String name) { this.name = name; } public static Girlfriend getInstance(){//公共的静态的返回对象的方法,便于主方法调用 return girlfriend1; } @Override public String toString() { return "Girlfriend{" + "name='" + name + '\'' + '}'; } }
XCodeRoot/chapter10
src/Day18/com/hspedu/single_/SingleTon01.java
501
//定义 女朋友 类
line_comment
zh-cn
package Day18.com.hspedu.single_; public class SingleTon01 { public static void main(String[] args) { // Girlfriend girlfriend1 = new Girlfriend("小红");//new 一个对象 // Girlfriend girlfriend2 = new Girlfriend("小花");//再new 一个对象 Girlfriend instance1=Girlfriend.getInstance();//这里就体现出了 // 要把Girlfriend类的 对象 和 返回对象的方法 设成静态的原因 //在不创建实例对象的情况下就能调用这个类里的方法 System.out.println(instance1); System.out.println("=======这两个是同一个对象(地址相同)=============================="); Girlfriend instance2=Girlfriend.getInstance();//因为只在类加载的时候 初始化静态对象, System.out.println(instance2); } } class Girlfriend{//定义 <SUF> private String name; //因为要被公共的静态方法获取,所以 这个对象要是静态的 private static Girlfriend girlfriend1 = new Girlfriend("小花"); /**【饿汉式 单例设计模式】,饿汉式可能造成创建了但是没使用对象的尴尬 * * 如何保证我们只能创建一个Girlfriend对象 * 1.将构造器私有化 * 2.在类 的内部 new对象 , 但主方法里还是不能使用这个私有的静态对象 * 3.提供一个公共的static方法,用来返回这个对象 * 当加载了Girlfriend类时,就创建对象 */ //构造器私有化 之后 ,无法在主方法里new对象 private Girlfriend(String name) { this.name = name; } public static Girlfriend getInstance(){//公共的静态的返回对象的方法,便于主方法调用 return girlfriend1; } @Override public String toString() { return "Girlfriend{" + "name='" + name + '\'' + '}'; } }
false
424
7
501
9
448
5
501
9
661
11
false
false
false
false
false
true
56614_13
package org.xjcraft.plot.plot.entity; import lombok.Data; import lombok.Getter; import lombok.experimental.Accessors; import java.time.LocalDateTime; /** * 地块 */ @Data @Accessors(chain = true) public class Plot { /** * 地块编号 */ private Integer id; /** * 所在世界的名称 */ private String worldName; /** * 地块 x 坐标中较小的数字 */ private Integer x1; /** * 地块 z 坐标中较小的数字 */ private Integer z1; /** * 地块 x 坐标中较大的数字 */ private Integer x2; /** * 地块 z 坐标中较大的数字 */ private Integer z2; /** * 地块的创建时间 */ private LocalDateTime addtime; /** * 出售方式 */ private SellType sellType; /** * 出售方式 - 价格 */ private Integer sellPrice; /** * 出售方式 */ public enum SellType { /** * 未定义 (不允许出售) */ UNDEFINED("暂不出售"), /** * 租赁 */ LEASE("租赁"), /** * 一口价 */ PERMANENT("一口价"), /** * 福利地块 (免费) */ FREE("福利(免费)"); /** * 显示名称 - 对玩家友好的名称 */ @Getter private final String displayName; SellType(String displayName) { this.displayName = displayName; } } }
XJcraft/XJCraftPlot
src/main/java/org/xjcraft/plot/plot/entity/Plot.java
395
/** * 一口价 */
block_comment
zh-cn
package org.xjcraft.plot.plot.entity; import lombok.Data; import lombok.Getter; import lombok.experimental.Accessors; import java.time.LocalDateTime; /** * 地块 */ @Data @Accessors(chain = true) public class Plot { /** * 地块编号 */ private Integer id; /** * 所在世界的名称 */ private String worldName; /** * 地块 x 坐标中较小的数字 */ private Integer x1; /** * 地块 z 坐标中较小的数字 */ private Integer z1; /** * 地块 x 坐标中较大的数字 */ private Integer x2; /** * 地块 z 坐标中较大的数字 */ private Integer z2; /** * 地块的创建时间 */ private LocalDateTime addtime; /** * 出售方式 */ private SellType sellType; /** * 出售方式 - 价格 */ private Integer sellPrice; /** * 出售方式 */ public enum SellType { /** * 未定义 (不允许出售) */ UNDEFINED("暂不出售"), /** * 租赁 */ LEASE("租赁"), /** * 一口价 <SUF>*/ PERMANENT("一口价"), /** * 福利地块 (免费) */ FREE("福利(免费)"); /** * 显示名称 - 对玩家友好的名称 */ @Getter private final String displayName; SellType(String displayName) { this.displayName = displayName; } } }
false
374
9
395
8
421
10
395
8
582
13
false
false
false
false
false
true