blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
ab51fc0597bcd89e407044c9d1f206d547612f40
27,797,028,342,579
f7a59c1977d78afc909b59d1199f903a907fc95f
/Server/src/main/java/com/magic/terry/server_magic/Connectadmin.java
c7b082c992726df20211faccfb2bb0acb17ab059
[ "Apache-2.0" ]
permissive
terry-gjt/Magic_link_android
https://github.com/terry-gjt/Magic_link_android
cf44da96a9ffb67e6725d41f271e2788e38fe88c
e01b9da48e92d430460caf41469375304b81f1ea
refs/heads/master
2020-05-16T15:35:10.659000
2019-05-14T09:52:14
2019-05-14T09:52:14
183,135,946
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.magic.terry.server_magic; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.util.Enumeration; /** * Created by terry on 2018-05-20. */ public class Connectadmin extends Thread{ public ServerSocket adminserverSocket; public boolean serverRunning=false; private Handler shandler; private boolean isConnecting = false; private Socket mSocketServer = null; private PrintWriter mPrintWriterServer = null; private String []mesage=new String[10]; private int front=0, rear=0; BufferedReader mBufferedReaderServer; String MessageServer=""; public void sethandler(Handler h){ shandler=h; } public void stopadmin() { if(serverRunning) { serverRunning = false; try { if(mSocketServer!=null) { mSocketServer.close(); mSocketServer = null; mPrintWriterServer.close(); mPrintWriterServer = null; Log.i("线程关闭","正常关闭线程"); } }catch (IOException e) { Log.i("线程结束异常","出现异常"+e.getMessage()); } try { if(adminserverSocket!=null) adminserverSocket.close(); } catch (IOException e) { Log.i("线程结束异常","adminserverSocket关闭异常"+e.getMessage()); } this.interrupt(); }else { Log.i("线程关闭","线程不在运行"); } } public void startadmin(){ if (!serverRunning){ serverRunning=true; this.start(); } else Log.i("线程启动","线程已经运行了"); } public boolean sendstring(String ss) { if(isConnecting) { if(ss.length()<=0) { Log.i("线程connecadmin","发送内容不能为空!"); }else { try { mPrintWriterServer.print(ss); mPrintWriterServer.flush(); Log.i("线程connecadmin","成功发送:"+ss); return true; }catch (Exception e) { Log.i("线程connecadmin","发送异常:"+e.getMessage()); } } }else { Log.i("线程connecadmin","没有连接"); } return false; } private void receivemess(String ss){//收到消息 if(shandler!=null){ mesage[rear]=ss;//放入消息 if(rear<9)rear++; else { rear=0; } Message msg = new Message(); msg.what = 5; shandler.sendMessage(msg); } } public String getmess(){ String s=mesage[front]; mesage[front]=null; if(front<9)front++; else { front=0; } return s; } public boolean isConnecting(){ return isConnecting; } private String getInfoBuff(char[] buff, int count) { char[] temp = new char[count]; for(int i=0; i<count; i++) { temp[i] = buff[i]; } return new String(temp); } @Override public void run() { try { try { adminserverSocket = new ServerSocket(55544); getLocalAddress(adminserverSocket); } catch (IOException e) { Log.i("线程connecadmin","本机55544端口被占用,请退出冲突程序"); e.printStackTrace(); } SocketAddress address = null; if(!adminserverSocket.isBound()) { adminserverSocket.bind(address,0); } mSocketServer=adminserverSocket.accept(); mBufferedReaderServer=new BufferedReader(new InputStreamReader(mSocketServer.getInputStream())); mPrintWriterServer=new PrintWriter(mSocketServer.getOutputStream(),true); isConnecting=true; receivemess("管理员已连接"); Log.i("线程connecadmin","管理员已连接!"); }catch (IOException e) { Log.i("线程connecadmin","管理员连接异常:" + e.getMessage()/* + e.toString()*/); return; } char[] buffer = new char[256]; int count = 0; while(serverRunning) { try { if((count=mBufferedReaderServer.read(buffer))>0); { MessageServer = getInfoBuff(buffer, count);//消息换行 receivemess(MessageServer); } } catch (Exception e){ Log.i("线程connecadmin","其他异常:" + e.getMessage()); isConnecting=false; return; } } } public String getLocalAddress(ServerSocket adminserverSocket){ String MessageServer=""; try { for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for(Enumeration<InetAddress> enumIPAddr = intf.getInetAddresses(); enumIPAddr.hasMoreElements();) { InetAddress inetAddress = enumIPAddr.nextElement(); String ipstr=inetAddress.getHostAddress(); int start = ipstr.indexOf("192.168"); if((start!=-1)&&(start+1<ipstr.length())){ Log.i("密码测试","密码为"+ipstr); MessageServer="管理员密钥为:"+encipher(ipstr); Log.i("密码测试",MessageServer); } // MessageServer += "请连接IP:"+inetAddress.getHostAddress()+"\n"; } } }catch (SocketException ex) { Log.i("线程admin","获取IP地址异常:" + ex.getMessage()); } if("".equals(MessageServer)) receivemess("获取IP地址异常"); else receivemess(MessageServer); return null; } private String encipher(String s){ int start = s.indexOf("192.168.");//正常返回0 if((start!=-1)&&(start+1<s.length())){ String sPort = s.substring(8);//获取剩余字符串 start = sPort.indexOf("."); if((start!=-1)&&(start+1<sPort.length())) { String sIP = sPort.substring(0, start); int port1 = Integer.parseInt(sIP); port1+=226; sIP = sPort.substring(start + 1); int port2 = Integer.parseInt(sIP); port1+=port2; port2+=119; s = ""+port1+port2; } } return s; } }
UTF-8
Java
7,388
java
Connectadmin.java
Java
[ { "context": ";\nimport java.util.Enumeration;\n\n/**\n * Created by terry on 2018-05-20.\n */\n\npublic class Connectadmin ext", "end": 475, "score": 0.9973722696304321, "start": 470, "tag": "USERNAME", "value": "terry" }, { "context": ");\n int start = ipstr.indexOf(\"192.168\");\n if((start!=-1)&&(start+1<i", "end": 5714, "score": 0.9985035061836243, "start": 5707, "tag": "IP_ADDRESS", "value": "192.168" }, { "context": "ncipher(String s){\n int start = s.indexOf(\"192.168.\");//正常返回0\n if((start!=-1)&&(start+1<s.length(", "end": 6426, "score": 0.8890917897224426, "start": 6419, "tag": "IP_ADDRESS", "value": "192.168" } ]
null
[]
package com.magic.terry.server_magic; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.util.Enumeration; /** * Created by terry on 2018-05-20. */ public class Connectadmin extends Thread{ public ServerSocket adminserverSocket; public boolean serverRunning=false; private Handler shandler; private boolean isConnecting = false; private Socket mSocketServer = null; private PrintWriter mPrintWriterServer = null; private String []mesage=new String[10]; private int front=0, rear=0; BufferedReader mBufferedReaderServer; String MessageServer=""; public void sethandler(Handler h){ shandler=h; } public void stopadmin() { if(serverRunning) { serverRunning = false; try { if(mSocketServer!=null) { mSocketServer.close(); mSocketServer = null; mPrintWriterServer.close(); mPrintWriterServer = null; Log.i("线程关闭","正常关闭线程"); } }catch (IOException e) { Log.i("线程结束异常","出现异常"+e.getMessage()); } try { if(adminserverSocket!=null) adminserverSocket.close(); } catch (IOException e) { Log.i("线程结束异常","adminserverSocket关闭异常"+e.getMessage()); } this.interrupt(); }else { Log.i("线程关闭","线程不在运行"); } } public void startadmin(){ if (!serverRunning){ serverRunning=true; this.start(); } else Log.i("线程启动","线程已经运行了"); } public boolean sendstring(String ss) { if(isConnecting) { if(ss.length()<=0) { Log.i("线程connecadmin","发送内容不能为空!"); }else { try { mPrintWriterServer.print(ss); mPrintWriterServer.flush(); Log.i("线程connecadmin","成功发送:"+ss); return true; }catch (Exception e) { Log.i("线程connecadmin","发送异常:"+e.getMessage()); } } }else { Log.i("线程connecadmin","没有连接"); } return false; } private void receivemess(String ss){//收到消息 if(shandler!=null){ mesage[rear]=ss;//放入消息 if(rear<9)rear++; else { rear=0; } Message msg = new Message(); msg.what = 5; shandler.sendMessage(msg); } } public String getmess(){ String s=mesage[front]; mesage[front]=null; if(front<9)front++; else { front=0; } return s; } public boolean isConnecting(){ return isConnecting; } private String getInfoBuff(char[] buff, int count) { char[] temp = new char[count]; for(int i=0; i<count; i++) { temp[i] = buff[i]; } return new String(temp); } @Override public void run() { try { try { adminserverSocket = new ServerSocket(55544); getLocalAddress(adminserverSocket); } catch (IOException e) { Log.i("线程connecadmin","本机55544端口被占用,请退出冲突程序"); e.printStackTrace(); } SocketAddress address = null; if(!adminserverSocket.isBound()) { adminserverSocket.bind(address,0); } mSocketServer=adminserverSocket.accept(); mBufferedReaderServer=new BufferedReader(new InputStreamReader(mSocketServer.getInputStream())); mPrintWriterServer=new PrintWriter(mSocketServer.getOutputStream(),true); isConnecting=true; receivemess("管理员已连接"); Log.i("线程connecadmin","管理员已连接!"); }catch (IOException e) { Log.i("线程connecadmin","管理员连接异常:" + e.getMessage()/* + e.toString()*/); return; } char[] buffer = new char[256]; int count = 0; while(serverRunning) { try { if((count=mBufferedReaderServer.read(buffer))>0); { MessageServer = getInfoBuff(buffer, count);//消息换行 receivemess(MessageServer); } } catch (Exception e){ Log.i("线程connecadmin","其他异常:" + e.getMessage()); isConnecting=false; return; } } } public String getLocalAddress(ServerSocket adminserverSocket){ String MessageServer=""; try { for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for(Enumeration<InetAddress> enumIPAddr = intf.getInetAddresses(); enumIPAddr.hasMoreElements();) { InetAddress inetAddress = enumIPAddr.nextElement(); String ipstr=inetAddress.getHostAddress(); int start = ipstr.indexOf("192.168"); if((start!=-1)&&(start+1<ipstr.length())){ Log.i("密码测试","密码为"+ipstr); MessageServer="管理员密钥为:"+encipher(ipstr); Log.i("密码测试",MessageServer); } // MessageServer += "请连接IP:"+inetAddress.getHostAddress()+"\n"; } } }catch (SocketException ex) { Log.i("线程admin","获取IP地址异常:" + ex.getMessage()); } if("".equals(MessageServer)) receivemess("获取IP地址异常"); else receivemess(MessageServer); return null; } private String encipher(String s){ int start = s.indexOf("192.168.");//正常返回0 if((start!=-1)&&(start+1<s.length())){ String sPort = s.substring(8);//获取剩余字符串 start = sPort.indexOf("."); if((start!=-1)&&(start+1<sPort.length())) { String sIP = sPort.substring(0, start); int port1 = Integer.parseInt(sIP); port1+=226; sIP = sPort.substring(start + 1); int port2 = Integer.parseInt(sIP); port1+=port2; port2+=119; s = ""+port1+port2; } } return s; } }
7,388
0.50271
0.492584
224
30.308035
20.472078
114
false
false
0
0
0
0
0
0
0.620536
false
false
15
1e8056e3fdc86842a7aa2b2d1ac11af3874ad15a
9,844,065,104,160
d0c77686746a667d830c8d2b5d777f133f3b83f5
/JavaBase/ObjectOriented/40. 多态:到底调用的哪个方法?/code/src/com/geekbang/PolymorphismAppMainSimple.java
c1ae0b9708062100a70b5f74e284eb971ea50385
[ "MIT" ]
permissive
xiang12835/JavaLearning
https://github.com/xiang12835/JavaLearning
ba8a473bb20ba8462b676b954c7fcc790e3c1bce
c86c2014b512c1ddaeb51e82dcb49367ed86235b
refs/heads/master
2023-03-15T20:15:35.191000
2022-04-23T13:36:40
2022-04-23T13:36:40
195,542,607
0
0
MIT
false
2023-03-08T17:35:10
2019-07-06T13:29:25
2022-03-04T04:52:25
2023-03-08T17:35:10
60,063
0
0
38
Java
false
false
package com.geekbang; import com.geekbang.supermarket.LittleSuperMarket; public class PolymorphismAppMainSimple { public static void main(String[] args) { LittleSuperMarket superMarket = new LittleSuperMarket("大卖场", "世纪大道1号", 500, 600, 100); // >> TODO 虽然是用的父类的引用指向的不同类型的对象,调用getName方法时,实际执行的方法取决于对象的类型,而非引用的类型 // >> TODO 也就是说,能调用哪些方法,是引用决定的,具体执行哪个类的方法,是引用指向的对象决定的。 // TODO 这就是覆盖的精髓。覆盖是多态的一种,是最重要的一种。 // >> TODO 以getName为例,父类里有这个方法,所以肯定都可以调用,但是Phone覆盖了父类的getName方法 // TODO 之前我们使用子类的引用指向子类的对象,调用子类里覆盖父类的方法,比如getName,执行的是子类的getName方法,我们觉得很自然。 // TODO 这里变换的是,我们用父类的引用指向子类的对象,调用被子类覆盖的方法,实际执行的还是子类里的getName方法 // TODO 当我们用父类的引用指向一个Phone的实例,并调用getName方法时,实际调用的就是Phone类里定义的getName方法 System.out.println(superMarket.getMerchandiseOf(0).getName()); System.out.println(); System.out.println(superMarket.getMerchandiseOf(10).getName()); // TODO 如果子类里没有覆盖这个方法,就去父类里找,父类里没有,就去父类的父类找。反之只要能让一个引用指向这个对象 // TODO 就说明这个对象肯定是这个类型或者其子类的的一个实例(否则赋值会发生ClassCastException),总归有父类兜底。 System.out.println(); System.out.println(superMarket.getMerchandiseOf(100).getName()); } }
UTF-8
Java
1,988
java
PolymorphismAppMainSimple.java
Java
[]
null
[]
package com.geekbang; import com.geekbang.supermarket.LittleSuperMarket; public class PolymorphismAppMainSimple { public static void main(String[] args) { LittleSuperMarket superMarket = new LittleSuperMarket("大卖场", "世纪大道1号", 500, 600, 100); // >> TODO 虽然是用的父类的引用指向的不同类型的对象,调用getName方法时,实际执行的方法取决于对象的类型,而非引用的类型 // >> TODO 也就是说,能调用哪些方法,是引用决定的,具体执行哪个类的方法,是引用指向的对象决定的。 // TODO 这就是覆盖的精髓。覆盖是多态的一种,是最重要的一种。 // >> TODO 以getName为例,父类里有这个方法,所以肯定都可以调用,但是Phone覆盖了父类的getName方法 // TODO 之前我们使用子类的引用指向子类的对象,调用子类里覆盖父类的方法,比如getName,执行的是子类的getName方法,我们觉得很自然。 // TODO 这里变换的是,我们用父类的引用指向子类的对象,调用被子类覆盖的方法,实际执行的还是子类里的getName方法 // TODO 当我们用父类的引用指向一个Phone的实例,并调用getName方法时,实际调用的就是Phone类里定义的getName方法 System.out.println(superMarket.getMerchandiseOf(0).getName()); System.out.println(); System.out.println(superMarket.getMerchandiseOf(10).getName()); // TODO 如果子类里没有覆盖这个方法,就去父类里找,父类里没有,就去父类的父类找。反之只要能让一个引用指向这个对象 // TODO 就说明这个对象肯定是这个类型或者其子类的的一个实例(否则赋值会发生ClassCastException),总归有父类兜底。 System.out.println(); System.out.println(superMarket.getMerchandiseOf(100).getName()); } }
1,988
0.716306
0.702995
26
45.23077
29.506594
86
false
false
0
0
0
0
0
0
0.461538
false
false
15
ddcf3d33e74b6d33c3b6c41ea24a871a21e04cd2
3,126,736,247,260
900ee1a1fb7e206a9d68d3a6c50513038c67aeef
/app/src/main/java/com/goqual/mercury/service/SyncDataService.java
c302db918d1ac73bb8db158a44931af6eba0869d
[]
no_license
goqual-kdj/OUTSOURCING_MERCURY
https://github.com/goqual-kdj/OUTSOURCING_MERCURY
c2a7baa558938435921a913879960fb42df4d0b0
8577e9caff12ceb19256fcb469aa8c72c9342876
refs/heads/master
2021-01-10T10:53:59.198000
2016-02-23T14:46:54
2016-02-23T14:46:54
52,252,722
0
2
null
false
2016-02-23T14:46:55
2016-02-22T06:42:31
2016-02-22T08:37:18
2016-02-23T14:46:55
88
0
1
0
Java
null
null
package com.goqual.mercury.service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import com.goqual.mercury.data.DataManager; import com.goqual.mercury.data.local.dto.FeedDTO; import com.goqual.mercury.receiver.SyncDataOnConnectionAvailable; import com.goqual.mercury.util.AndroidComponentUtil; import com.goqual.mercury.util.Common; import com.goqual.mercury.util.NetworkUtil; import rx.Observer; import rx.Subscription; import rx.schedulers.Schedulers; /** * Created by ladmusician on 2/23/16. */ public class SyncDataService extends Service { private final String TAG = "MERCURY_SYNC_DATA_SERVICE"; private Subscription mSubscription; private DataManager mDataManager; public static Intent getStartIntent(Context context) { return new Intent(context, SyncDataService.class); } @Override public int onStartCommand(Intent intent, int flags, final int startId) { if (!NetworkUtil.isNetworkConnected(this)) { Common.log(TAG, "Sync canceled, connection not available"); AndroidComponentUtil.toggleComponent(this, SyncDataOnConnectionAvailable.class, true); stopSelf(startId); return START_NOT_STICKY; } if (mSubscription != null && !mSubscription.isUnsubscribed()) mSubscription.unsubscribe(); Common.log(TAG, "THREAD ID : " + Thread.currentThread().getId()); mSubscription = getDataManager() .syncFeeds() .subscribeOn(Schedulers.io()) .subscribe(new Observer<FeedDTO>() { @Override public void onCompleted() { Common.log(TAG, "SYNC SUCCESSFULLY!"); stopSelf(startId); } @Override public void onError(Throwable e) { Common.log(TAG, e.getMessage()); Common.log(TAG, "Error syncing!"); stopSelf(startId); } @Override public void onNext(FeedDTO feedDTO) { } }); return START_STICKY; } @Override public void onDestroy() { if (mSubscription != null) mSubscription.unsubscribe(); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private DataManager getDataManager() { if (mDataManager == null) mDataManager = new DataManager(); return mDataManager; } }
UTF-8
Java
2,712
java
SyncDataService.java
Java
[ { "context": "mport rx.schedulers.Schedulers;\n\n/**\n * Created by ladmusician on 2/23/16.\n */\npublic class SyncDataService exte", "end": 604, "score": 0.9995982050895691, "start": 593, "tag": "USERNAME", "value": "ladmusician" } ]
null
[]
package com.goqual.mercury.service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import com.goqual.mercury.data.DataManager; import com.goqual.mercury.data.local.dto.FeedDTO; import com.goqual.mercury.receiver.SyncDataOnConnectionAvailable; import com.goqual.mercury.util.AndroidComponentUtil; import com.goqual.mercury.util.Common; import com.goqual.mercury.util.NetworkUtil; import rx.Observer; import rx.Subscription; import rx.schedulers.Schedulers; /** * Created by ladmusician on 2/23/16. */ public class SyncDataService extends Service { private final String TAG = "MERCURY_SYNC_DATA_SERVICE"; private Subscription mSubscription; private DataManager mDataManager; public static Intent getStartIntent(Context context) { return new Intent(context, SyncDataService.class); } @Override public int onStartCommand(Intent intent, int flags, final int startId) { if (!NetworkUtil.isNetworkConnected(this)) { Common.log(TAG, "Sync canceled, connection not available"); AndroidComponentUtil.toggleComponent(this, SyncDataOnConnectionAvailable.class, true); stopSelf(startId); return START_NOT_STICKY; } if (mSubscription != null && !mSubscription.isUnsubscribed()) mSubscription.unsubscribe(); Common.log(TAG, "THREAD ID : " + Thread.currentThread().getId()); mSubscription = getDataManager() .syncFeeds() .subscribeOn(Schedulers.io()) .subscribe(new Observer<FeedDTO>() { @Override public void onCompleted() { Common.log(TAG, "SYNC SUCCESSFULLY!"); stopSelf(startId); } @Override public void onError(Throwable e) { Common.log(TAG, e.getMessage()); Common.log(TAG, "Error syncing!"); stopSelf(startId); } @Override public void onNext(FeedDTO feedDTO) { } }); return START_STICKY; } @Override public void onDestroy() { if (mSubscription != null) mSubscription.unsubscribe(); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private DataManager getDataManager() { if (mDataManager == null) mDataManager = new DataManager(); return mDataManager; } }
2,712
0.612094
0.610251
87
30.172413
23.25679
98
false
false
0
0
0
0
0
0
0.551724
false
false
15
a22c44e63a8cde8ce2ae6b3676d941be056142cb
2,070,174,240,816
087afee81e50fcf87619f386c40651da4cb61850
/CaesarCypher/src/ie/gmit/sw/CaesarCypher.java
840f6808d905814f1506362a4c8d1b9a6ca6b89d
[]
no_license
ross39/-CaesarCypher
https://github.com/ross39/-CaesarCypher
fa59c1f0dab3c044e02b2afc0bbfd64ca82c99be
545382bbd15a03e4dbbd06f075745fb28078732a
refs/heads/master
2020-08-02T14:04:13.497000
2019-09-27T18:38:25
2019-09-27T18:38:25
211,380,789
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ie.gmit.sw; public class CaesarCypher extends AbstractCypher implements Cypherable, CypherKey { private CypherKey key; public CaesarCypher(int key) throws CypherException { super(); setKey(key + ""); // TODO Auto-generated constructor stub } @Override public byte encrypt(byte b) throws CypherException { return (byte) (b + Integer.parseInt(key.getKey())); } @Override public byte decrypt(byte b) throws CypherException { return (byte) (b - Integer.parseInt(key.getKey())); } public void setKey(String key) throws CypherException { this.key = new CypherKeyImpl(key); } public String getKey() { return key.getKey(); } @Override protected void finalize() throws Throwable { super.finalize(); } public class CypherKeyImpl implements CypherKey{ private int key; public CypherKeyImpl(String key) { super(); this.key = Integer.parseInt(key); } @Override public void setKey(String key) throws CypherException { this.key = Integer.parseInt(key); //CaesarCypher.this.key } @Override public String getKey() { return this.key + ""; } } }
UTF-8
Java
1,122
java
CaesarCypher.java
Java
[]
null
[]
package ie.gmit.sw; public class CaesarCypher extends AbstractCypher implements Cypherable, CypherKey { private CypherKey key; public CaesarCypher(int key) throws CypherException { super(); setKey(key + ""); // TODO Auto-generated constructor stub } @Override public byte encrypt(byte b) throws CypherException { return (byte) (b + Integer.parseInt(key.getKey())); } @Override public byte decrypt(byte b) throws CypherException { return (byte) (b - Integer.parseInt(key.getKey())); } public void setKey(String key) throws CypherException { this.key = new CypherKeyImpl(key); } public String getKey() { return key.getKey(); } @Override protected void finalize() throws Throwable { super.finalize(); } public class CypherKeyImpl implements CypherKey{ private int key; public CypherKeyImpl(String key) { super(); this.key = Integer.parseInt(key); } @Override public void setKey(String key) throws CypherException { this.key = Integer.parseInt(key); //CaesarCypher.this.key } @Override public String getKey() { return this.key + ""; } } }
1,122
0.697861
0.697861
58
18.344828
20.761827
83
false
false
0
0
0
0
0
0
1.5
false
false
15
1d21bca9a49bb34aa14d6856d9d70b5ef61bfd4d
19,043,885,000,390
cc0f28bfbf9d7779c9b09ba73c3b77e42e81a652
/app/src/androidTest/java/com/example/mynews/Controllers/Activities/NotificationsActivityTest.java
e1f11083b0307d303878237ed3ca31935c4b75a9
[]
no_license
letelSyl/MyNews
https://github.com/letelSyl/MyNews
80a90aa68dd8c8b30711ab712b274e8819eece6b
2f1841bb25c795f7c7f77a2895f9d7750d56a96f
refs/heads/master
2020-09-27T11:41:24.861000
2020-06-05T12:49:52
2020-06-05T12:49:52
226,494,157
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mynews.Controllers.Activities; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import com.example.mynews.R; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsInstanceOf; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.espresso.ViewInteraction; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; @LargeTest @RunWith(AndroidJUnit4.class) public class NotificationsActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void notificationsActivityTest() { ViewInteraction overflowMenuButton = onView( allOf(withContentDescription("More options"), childAtPosition( childAtPosition( withId(R.id.main_include), 2), 1), isDisplayed())); overflowMenuButton.perform(click()); ViewInteraction appCompatTextView = onView( allOf(withId(R.id.title), withText("Notifications"), childAtPosition( childAtPosition( withId(R.id.content), 0), 0), isDisplayed())); appCompatTextView.perform(click()); ViewInteraction appCompatAutoCompleteTextView = onView( allOf(withId(R.id.notifications_tv), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( withClassName(is("androidx.constraintlayout.widget.ConstraintLayout")), 1)), 0), isDisplayed())); appCompatAutoCompleteTextView.perform(replaceText("Trump"), closeSoftKeyboard()); ViewInteraction appCompatAutoCompleteTextView2 = onView( allOf(withId(R.id.notifications_tv), withText("Trump"), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( withClassName(is("androidx.constraintlayout.widget.ConstraintLayout")), 1)), 0), isDisplayed())); appCompatAutoCompleteTextView2.perform(click()); ViewInteraction appCompatCheckBox = onView( allOf(withId(R.id.politics_checkBox), withText("Politics"), childAtPosition( allOf(withId(R.id.ConstraintLayout), childAtPosition( withId(R.id.notifications_checkBoxes), 0)), 1), isDisplayed())); appCompatCheckBox.perform(click()); ViewInteraction appCompatCheckBox2 = onView( allOf(withId(R.id.travel_checkBox), withText("Travel"), childAtPosition( allOf(withId(R.id.ConstraintLayout3), childAtPosition( withId(R.id.notifications_checkBoxes), 2)), 1), isDisplayed())); appCompatCheckBox2.perform(click()); ViewInteraction appCompatCheckBox3 = onView( allOf(withId(R.id.business_checkBox), withText("Business"), childAtPosition( allOf(withId(R.id.ConstraintLayout2), childAtPosition( withId(R.id.notifications_checkBoxes), 1)), 0), isDisplayed())); appCompatCheckBox3.perform(click()); ViewInteraction switch_ = onView( allOf(withId(R.id.notifications_switch), withText("Enable notifications (once per day)"), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( withClassName(is("androidx.constraintlayout.widget.ConstraintLayout")), 1)), 2), isDisplayed())); switch_.perform(click()); ViewInteraction switch_2 = onView( allOf(withId(R.id.notifications_switch), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( IsInstanceOf.<View>instanceOf(android.view.ViewGroup.class), 1)), 2), isDisplayed())); switch_2.check(matches(isDisplayed())); } private static Matcher<View> childAtPosition( final Matcher<View> parentMatcher, final int position) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("Child at position " + position + " in parent "); parentMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { ViewParent parent = view.getParent(); return parent instanceof ViewGroup && parentMatcher.matches(parent) && view.equals(((ViewGroup) parent).getChildAt(position)); } }; } }
UTF-8
Java
7,273
java
NotificationsActivityTest.java
Java
[]
null
[]
package com.example.mynews.Controllers.Activities; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import com.example.mynews.R; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsInstanceOf; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.espresso.ViewInteraction; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; @LargeTest @RunWith(AndroidJUnit4.class) public class NotificationsActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void notificationsActivityTest() { ViewInteraction overflowMenuButton = onView( allOf(withContentDescription("More options"), childAtPosition( childAtPosition( withId(R.id.main_include), 2), 1), isDisplayed())); overflowMenuButton.perform(click()); ViewInteraction appCompatTextView = onView( allOf(withId(R.id.title), withText("Notifications"), childAtPosition( childAtPosition( withId(R.id.content), 0), 0), isDisplayed())); appCompatTextView.perform(click()); ViewInteraction appCompatAutoCompleteTextView = onView( allOf(withId(R.id.notifications_tv), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( withClassName(is("androidx.constraintlayout.widget.ConstraintLayout")), 1)), 0), isDisplayed())); appCompatAutoCompleteTextView.perform(replaceText("Trump"), closeSoftKeyboard()); ViewInteraction appCompatAutoCompleteTextView2 = onView( allOf(withId(R.id.notifications_tv), withText("Trump"), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( withClassName(is("androidx.constraintlayout.widget.ConstraintLayout")), 1)), 0), isDisplayed())); appCompatAutoCompleteTextView2.perform(click()); ViewInteraction appCompatCheckBox = onView( allOf(withId(R.id.politics_checkBox), withText("Politics"), childAtPosition( allOf(withId(R.id.ConstraintLayout), childAtPosition( withId(R.id.notifications_checkBoxes), 0)), 1), isDisplayed())); appCompatCheckBox.perform(click()); ViewInteraction appCompatCheckBox2 = onView( allOf(withId(R.id.travel_checkBox), withText("Travel"), childAtPosition( allOf(withId(R.id.ConstraintLayout3), childAtPosition( withId(R.id.notifications_checkBoxes), 2)), 1), isDisplayed())); appCompatCheckBox2.perform(click()); ViewInteraction appCompatCheckBox3 = onView( allOf(withId(R.id.business_checkBox), withText("Business"), childAtPosition( allOf(withId(R.id.ConstraintLayout2), childAtPosition( withId(R.id.notifications_checkBoxes), 1)), 0), isDisplayed())); appCompatCheckBox3.perform(click()); ViewInteraction switch_ = onView( allOf(withId(R.id.notifications_switch), withText("Enable notifications (once per day)"), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( withClassName(is("androidx.constraintlayout.widget.ConstraintLayout")), 1)), 2), isDisplayed())); switch_.perform(click()); ViewInteraction switch_2 = onView( allOf(withId(R.id.notifications_switch), childAtPosition( allOf(withId(R.id.linear_layout), childAtPosition( IsInstanceOf.<View>instanceOf(android.view.ViewGroup.class), 1)), 2), isDisplayed())); switch_2.check(matches(isDisplayed())); } private static Matcher<View> childAtPosition( final Matcher<View> parentMatcher, final int position) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("Child at position " + position + " in parent "); parentMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { ViewParent parent = view.getParent(); return parent instanceof ViewGroup && parentMatcher.matches(parent) && view.equals(((ViewGroup) parent).getChildAt(position)); } }; } }
7,273
0.516018
0.511893
161
44.173912
26.736015
119
false
false
0
0
0
0
0
0
0.639752
false
false
15
f5f8ac6cdabaccbfc62089aeeb535e7154b26531
19,043,885,004,251
843bb39930829954bcc6a2195773f30714d34831
/src/main/java/my/revolut/task/domain/transfer/MoneyTransferRepository.java
78da0f8567a9ccacad8df3390640d5d7a75ce787
[]
no_license
dominik-sze/moneyTransfer
https://github.com/dominik-sze/moneyTransfer
1e46094d07977b01d703f75988b6f299b5a6e352
694654ee381d2f07b87629d91bbe645d46a4c930
refs/heads/master
2022-12-01T23:07:54.126000
2019-10-06T17:52:16
2019-10-06T17:52:16
213,215,402
0
0
null
false
2022-11-15T23:31:45
2019-10-06T17:47:43
2019-10-06T17:52:22
2022-11-15T23:31:42
20
0
0
2
Java
false
false
package my.revolut.task.domain.transfer; import com.google.inject.Singleton; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @Singleton class MoneyTransferRepository implements TransferRepository { private final Map<UUID, Transfer> transfers = new ConcurrentHashMap<>(); @Override public void save(Transfer transfer) { transfers.put(transfer.getTransferId(), transfer); } @Override public Transfer getById(UUID transferId) { return transfers.get(transferId); } }
UTF-8
Java
523
java
MoneyTransferRepository.java
Java
[]
null
[]
package my.revolut.task.domain.transfer; import com.google.inject.Singleton; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @Singleton class MoneyTransferRepository implements TransferRepository { private final Map<UUID, Transfer> transfers = new ConcurrentHashMap<>(); @Override public void save(Transfer transfer) { transfers.put(transfer.getTransferId(), transfer); } @Override public Transfer getById(UUID transferId) { return transfers.get(transferId); } }
523
0.785851
0.785851
22
22.772728
22.399132
73
false
false
0
0
0
0
0
0
0.954545
false
false
15
8c562e21d5caeda3f2a5f3afb01bb82057fe5e52
8,675,833,992,880
de41aa5003bebf0ce26c3fbd8d6759c267426f6d
/src/main/java/com/capstone/service/ShoppingCartService.java
c15cb951b44818273a194e4f064435154d424ed1
[]
no_license
smitha-hatti/capstoneproject-HerokuCloud
https://github.com/smitha-hatti/capstoneproject-HerokuCloud
339bb8a0c57506cd89c7bcfc9e1fa8ebcddb5628
89974bf727f0d583992999c6e62ba7f4400a6987
refs/heads/master
2020-04-26T02:55:59.880000
2019-03-03T20:38:06
2019-03-03T20:38:06
173,250,029
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.capstone.service; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import com.capstone.model.Cart; public interface ShoppingCartService { Cart addItem(String userId, int itemsId, String itemsName, BigDecimal itemsPrice, String sizeOrdered, int qty); Optional<Cart> findById(int cartid); List<Cart> findByUserId(String userId); void removeItem(int cartID); }
UTF-8
Java
423
java
ShoppingCartService.java
Java
[]
null
[]
package com.capstone.service; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import com.capstone.model.Cart; public interface ShoppingCartService { Cart addItem(String userId, int itemsId, String itemsName, BigDecimal itemsPrice, String sizeOrdered, int qty); Optional<Cart> findById(int cartid); List<Cart> findByUserId(String userId); void removeItem(int cartID); }
423
0.765957
0.765957
18
22.5
26.329641
112
false
false
0
0
0
0
0
0
1.111111
false
false
15
61071353dd4e905f2961cc5cb6f4df48903d12b3
30,485,677,934,771
86505462601eae6007bef6c9f0f4eeb9fcdd1e7b
/bin/modules/sap-synchronous-order-management/sapordermgmtb2bfacades/src/de/hybris/platform/sap/sapordermgmtb2bfacades/order/impl/DefaultSapCartFacade.java
bea818c0054ab4cca7d895a89cafdbf18109ef2d
[]
no_license
jp-developer0/hybrisTrail
https://github.com/jp-developer0/hybrisTrail
82165c5b91352332a3d471b3414faee47bdb6cee
a0208ffee7fee5b7f83dd982e372276492ae83d4
refs/heads/master
2020-12-03T19:53:58.652000
2020-01-02T18:02:34
2020-01-02T18:02:34
231,430,332
0
4
null
false
2020-08-05T22:46:23
2020-01-02T17:39:15
2020-01-02T19:06:34
2020-08-05T22:46:21
1,073,803
0
1
2
null
false
false
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.sap.sapordermgmtb2bfacades.order.impl; import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.commercefacades.order.data.CartModificationData; import de.hybris.platform.commercefacades.order.data.CartRestorationData; import de.hybris.platform.commercefacades.order.data.OrderEntryData; import de.hybris.platform.commercefacades.order.impl.DefaultCartFacade; import de.hybris.platform.commercefacades.product.data.ProductData; import de.hybris.platform.commercefacades.user.data.CountryData; import de.hybris.platform.commerceservices.order.CommerceCartMergingException; import de.hybris.platform.commerceservices.order.CommerceCartModificationException; import de.hybris.platform.commerceservices.order.CommerceCartRestorationException; import de.hybris.platform.core.model.user.UserModel; import de.hybris.platform.sap.core.common.exceptions.ApplicationBaseRuntimeException; import de.hybris.platform.sap.sapordermgmtb2bfacades.ProductImageHelper; import de.hybris.platform.sap.sapordermgmtb2bfacades.cart.CartRestorationFacade; import de.hybris.platform.sap.sapordermgmtb2bfacades.hook.SapCartFacadeHook; import de.hybris.platform.sap.sapordermgmtservices.BackendAvailabilityService; import de.hybris.platform.sap.sapordermgmtservices.cart.CartService; import de.hybris.platform.sap.sapordermgmtservices.constants.SapordermgmtservicesConstants; import de.hybris.platform.servicelayer.i18n.I18NService; import de.hybris.platform.servicelayer.session.SessionService; import de.hybris.platform.store.services.BaseStoreService; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Required; import org.springframework.context.MessageSource; /** * Implementation for {@link CartFacade}. Delivers main functionality for cart. */ public class DefaultSapCartFacade extends DefaultCartFacade { private static final Logger LOG = Logger.getLogger(DefaultSapCartFacade.class); private CartService sapCartService; private BackendAvailabilityService backendAvailabilityService; private BaseStoreService baseStoreService; private ProductImageHelper productImageHelper; private CartRestorationFacade cartRestorationFacade; private List<SapCartFacadeHook> sapCartFacadeHooks; private SessionService sessionService; private I18NService i18nService; private MessageSource messageSource; /** * @return the i18nService */ public I18NService getI18nService() { return i18nService; } /** * @param i18nService * the i18nService to set */ public void setI18nService(final I18NService i18nService) { this.i18nService = i18nService; } /** * @return the messageSource */ public MessageSource getMessageSource() { return messageSource; } /** * @param messageSource * the messageSource to set */ public void setMessageSource(final MessageSource messageSource) { this.messageSource = messageSource; } @Override public boolean hasSessionCart() { if (!isSyncOrdermgmtEnabled()) { return super.hasSessionCart(); } if (isBackendDown()) { return super.hasSessionCart(); } return getSapCartService().hasSessionCart(); } @Override public CartData getMiniCart() { if (!isSyncOrdermgmtEnabled()) { return super.getSessionCart(); } return getSessionCart(); } @Override public CartData getSessionCart() { if (!isSyncOrdermgmtEnabled()) { return super.getSessionCart(); } if (LOG.isDebugEnabled()) { LOG.debug("getSessionCart"); } if (isBackendDown()) { addErrorMessages(); final CartData cartWhenSessionDown = super.getSessionCart(); cartWhenSessionDown.setBackendDown(true); cartWhenSessionDown.getTotalPrice().setFormattedValue(""); return cartWhenSessionDown; } else { if (!isUserLoggedOn()) { return createEmptyCart(); } final CartData sessionCart = getSapCartService().getSessionCart(); if (sessionCart.getTotalUnitCount() == null) { sessionCart.setTotalUnitCount(Integer.valueOf(0)); } sessionCart.setCode(super.getSessionCart().getCode()); productImageHelper.enrichWithProductImages(sessionCart); return sessionCart; } } @Override public CartData getSessionCartWithEntryOrdering(final boolean recentlyAddedFirst) { if (!isSyncOrdermgmtEnabled()) { return super.getSessionCartWithEntryOrdering(recentlyAddedFirst); } if (LOG.isDebugEnabled()) { LOG.debug("getSessionCartWithEntryOrdering called with: " + recentlyAddedFirst); } if (isBackendDown()) { final CartData cartWhenSessionDown = super.getSessionCartWithEntryOrdering(recentlyAddedFirst); cartWhenSessionDown.setBackendDown(true); cartWhenSessionDown.getTotalPrice().setFormattedValue(""); return cartWhenSessionDown; } else { if (!isUserLoggedOn()) { return createEmptyCart(); } final CartData sessionCart = getSapCartService().getSessionCart(recentlyAddedFirst); sessionCart.setCode(super.getSessionCart().getCode()); productImageHelper.enrichWithProductImages(sessionCart); return sessionCart; } } @Override public CartModificationData addToCart(final String code, final long quantity) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.addToCart(code, quantity); } if (isBackendDown()) { addErrorMessages(); final CartModificationData cartModificationBackendDown = super.addToCart(code, quantity); final OrderEntryData entry = cartModificationBackendDown.getEntry(); entry.setBackendDown(true); return cartModificationBackendDown; } else { final CartModificationData cartModification = getSapCartService().addToCart(code, quantity); productImageHelper.enrichWithProductImages(cartModification.getEntry()); if (getCartRestorationFacade() != null) { getCartRestorationFacade().setSavedCart(getSapCartService().getSessionCart()); } return cartModification; } } /** * */ private void addErrorMessages() { final List<CartModificationData> modifications = new ArrayList<>(); final CartModificationData modificationData = new CartModificationData(); final OrderEntryData entryMsg = new OrderEntryData(); final ProductData product = new ProductData(); product.setName( getMessageSource().getMessage("sap.checkout.backend.offline.message", null, getI18nService().getCurrentLocale())); entryMsg.setProduct(product); modificationData.setStatusMessage( getMessageSource().getMessage("sap.checkout.backend.offline.message", null, getI18nService().getCurrentLocale())); modificationData.setEntry(entryMsg); modificationData.setStatusCode(SapordermgmtservicesConstants.STATUS_SAP_ERROR); modifications.add(modificationData); getSessionService().setAttribute("validations", modifications); } @Override public CartModificationData addToCart(final String code, final long quantity, final String storeId) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.addToCart(code, quantity, storeId); } LOG.info("addToCart called with store ID, ignoring: " + storeId); return this.addToCart(code, quantity); } /** * Add quick order entries to cart * * @param cartEntries * list of cart entries * @return cart modification data * @throws CommerceCartModificationException * exception */ public List<CartModificationData> addItemsToCart(final List<OrderEntryData> cartEntries) throws CommerceCartModificationException { List<CartModificationData> modificationDataList; modificationDataList = getSapCartService().addEntriesToCart(cartEntries); return modificationDataList; } @Override public List<CartModificationData> validateCartData() throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.validateCartData(); } return getSapCartService().validateCartData(); } @Override public CartModificationData updateCartEntry(final long entryNumber, final long quantity) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.updateCartEntry(entryNumber, quantity); } if (isBackendDown()) { final List<OrderEntryData> entries = getSessionCart().getEntries(); beforeCartEntryUpdate(quantity, entryNumber, entries); return super.updateCartEntry(entryNumber, quantity); } else { final CartModificationData cartModification = getSapCartService().updateCartEntry(entryNumber, quantity); if (this.cartRestorationFacade != null) { this.cartRestorationFacade.setSavedCart(getSapCartService().getSessionCart()); } return cartModification; } } /** * @param quantity * @param entryNumber * @param entries */ private void beforeCartEntryUpdate(final long quantity, final long entryNumber, final List<OrderEntryData> entries) { if (getSapCartFacadeHooks() != null) { for (final SapCartFacadeHook defaultSapCartFacadeHook : getSapCartFacadeHooks()) { defaultSapCartFacadeHook.beforeCartEntryUpdate(quantity, entryNumber, entries); } } } protected boolean isSyncOrdermgmtEnabled() { return (getBaseStoreService().getCurrentBaseStore().getSAPConfiguration() != null) && (getBaseStoreService().getCurrentBaseStore().getSAPConfiguration().isSapordermgmt_enabled()); } /** * @return the baseStoreService */ public BaseStoreService getBaseStoreService() { return baseStoreService; } /** * @param baseStoreService * the baseStoreService to set */ @Required public void setBaseStoreService(final BaseStoreService baseStoreService) { this.baseStoreService = baseStoreService; } /** * @return the sapCartService */ public CartService getSapCartService() { return sapCartService; } /** * @param sapCartService * the sapCartService to set */ @Required public void setSapCartService(final CartService sapCartService) { this.sapCartService = sapCartService; } /** * @return the backendAvailabilityService */ public BackendAvailabilityService getBackendAvailabilityService() { return backendAvailabilityService; } /** * @param backendAvailabilityService * the backendAvailabilityService to set */ @Required public void setBackendAvailabilityService(final BackendAvailabilityService backendAvailabilityService) { this.backendAvailabilityService = backendAvailabilityService; } private boolean isUserLoggedOn() { final UserModel userModel = super.getUserService().getCurrentUser(); return !super.getUserService().isAnonymousUser(userModel); } /** * @return the productImageHelper */ public ProductImageHelper getProductImageHelper() { return productImageHelper; } /** * @param productImageHelper * the productImageHelper to set */ @Required public void setProductImageHelper(final ProductImageHelper productImageHelper) { this.productImageHelper = productImageHelper; } /** * @return Is Backend down? */ private boolean isBackendDown() { return backendAvailabilityService.isBackendDown(); } /** * @return the cartRestorationFacade */ public CartRestorationFacade getCartRestorationFacade() { return cartRestorationFacade; } /** * @param cartRestorationFacade * the cartRestorationFacade to set */ @Required public void setCartRestorationFacade(final CartRestorationFacade cartRestorationFacade) { this.cartRestorationFacade = cartRestorationFacade; } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#updateCartEntry(long, java.lang.String) */ @Override public CartModificationData updateCartEntry(final long entryNumber, final String storeId) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.updateCartEntry(entryNumber, storeId); } throw new ApplicationBaseRuntimeException("Not supported: updateCartEntry(final long entryNumber, final String storeId)"); } @Override public CartRestorationData restoreSavedCart(final String code) throws CommerceCartRestorationException { if (!isSyncOrdermgmtEnabled()) { return super.restoreSavedCart(code); } if (isBackendDown()) { return super.restoreSavedCart(code); } else { if (this.cartRestorationFacade != null) { return this.cartRestorationFacade.restoreSavedCart(code, super.getUserService().getCurrentUser()); } return null; } } @Override public List<CountryData> getDeliveryCountries() { if (!isSyncOrdermgmtEnabled()) { return super.getDeliveryCountries(); } //No delivery countries available, only choosing from existing addresses supported return Collections.emptyList(); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#estimateExternalTaxes(java.lang.String, * java.lang.String) */ @Override public CartData estimateExternalTaxes(final String deliveryZipCode, final String countryIsoCode) { if (!isSyncOrdermgmtEnabled()) { return super.estimateExternalTaxes(deliveryZipCode, countryIsoCode); } //We cannot support this, as the delivery costs are based on the ship-to party address in the ERP case throw new ApplicationBaseRuntimeException("Not supported: estimateExternalTaxes"); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#removeStaleCarts() */ @Override public void removeStaleCarts() { if (!isSyncOrdermgmtEnabled()) { super.removeStaleCarts(); return; } //No stale carts in this scenario } @Override public CartRestorationData restoreAnonymousCartAndTakeOwnership(final String guid) throws CommerceCartRestorationException { if (!isSyncOrdermgmtEnabled()) { return super.restoreAnonymousCartAndTakeOwnership(guid); } //No anonymous carts in our scenario return null; } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#removeSessionCart() */ @Override public void removeSessionCart() { if (!isSyncOrdermgmtEnabled()) { super.removeSessionCart(); return; } if (this.cartRestorationFacade != null) { this.cartRestorationFacade.removeSavedCart(); } getSapCartService().removeSessionCart(); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#getCartsForCurrentUser() */ @Override public List<CartData> getCartsForCurrentUser() { if (!isSyncOrdermgmtEnabled()) { return super.getCartsForCurrentUser(); } return Arrays.asList(getSessionCart()); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#restoreAnonymousCartAndMerge(java.lang.String, * java.lang.String) */ @Override public CartRestorationData restoreAnonymousCartAndMerge(final String fromAnonumousCartGuid, final String toUserCartGuid) throws CommerceCartMergingException, CommerceCartRestorationException { if (!isSyncOrdermgmtEnabled()) { return super.restoreAnonymousCartAndMerge(fromAnonumousCartGuid, toUserCartGuid); } throw new ApplicationBaseRuntimeException("restoreAnonymousCartAndMerge not supported"); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#restoreCartAndMerge(java.lang.String, * java.lang.String) */ @Override public CartRestorationData restoreCartAndMerge(final String fromUserCartGuid, final String toUserCartGuid) throws CommerceCartRestorationException, CommerceCartMergingException { if (!isSyncOrdermgmtEnabled()) { return super.restoreCartAndMerge(fromUserCartGuid, toUserCartGuid); } throw new ApplicationBaseRuntimeException("restoreCartAndMerge not supported"); } @Override public boolean hasEntries() { if (!isSyncOrdermgmtEnabled()) { return super.hasEntries(); } if (isBackendDown()) { return super.hasEntries(); } else { final CartData sessionCart = getSapCartService().getSessionCart(); if (sessionCart != null && sessionCart.getEntries() != null) { return !sessionCart.getEntries().isEmpty(); } return false; } } /** * @return the sapCartFacadeHooks */ public List<SapCartFacadeHook> getSapCartFacadeHooks() { return sapCartFacadeHooks; } /** * @param sapCartFacadeHooks * the sapCartFacadeHooks to set */ public void setSapCartFacadeHooks(final List<SapCartFacadeHook> sapCartFacadeHooks) { this.sapCartFacadeHooks = sapCartFacadeHooks; } /** * @return the sessionService */ public SessionService getSessionService() { return sessionService; } /** * @param sessionService * the sessionService to set */ public void setSessionService(final SessionService sessionService) { this.sessionService = sessionService; } }
UTF-8
Java
17,478
java
DefaultSapCartFacade.java
Java
[]
null
[]
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.sap.sapordermgmtb2bfacades.order.impl; import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.commercefacades.order.data.CartModificationData; import de.hybris.platform.commercefacades.order.data.CartRestorationData; import de.hybris.platform.commercefacades.order.data.OrderEntryData; import de.hybris.platform.commercefacades.order.impl.DefaultCartFacade; import de.hybris.platform.commercefacades.product.data.ProductData; import de.hybris.platform.commercefacades.user.data.CountryData; import de.hybris.platform.commerceservices.order.CommerceCartMergingException; import de.hybris.platform.commerceservices.order.CommerceCartModificationException; import de.hybris.platform.commerceservices.order.CommerceCartRestorationException; import de.hybris.platform.core.model.user.UserModel; import de.hybris.platform.sap.core.common.exceptions.ApplicationBaseRuntimeException; import de.hybris.platform.sap.sapordermgmtb2bfacades.ProductImageHelper; import de.hybris.platform.sap.sapordermgmtb2bfacades.cart.CartRestorationFacade; import de.hybris.platform.sap.sapordermgmtb2bfacades.hook.SapCartFacadeHook; import de.hybris.platform.sap.sapordermgmtservices.BackendAvailabilityService; import de.hybris.platform.sap.sapordermgmtservices.cart.CartService; import de.hybris.platform.sap.sapordermgmtservices.constants.SapordermgmtservicesConstants; import de.hybris.platform.servicelayer.i18n.I18NService; import de.hybris.platform.servicelayer.session.SessionService; import de.hybris.platform.store.services.BaseStoreService; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Required; import org.springframework.context.MessageSource; /** * Implementation for {@link CartFacade}. Delivers main functionality for cart. */ public class DefaultSapCartFacade extends DefaultCartFacade { private static final Logger LOG = Logger.getLogger(DefaultSapCartFacade.class); private CartService sapCartService; private BackendAvailabilityService backendAvailabilityService; private BaseStoreService baseStoreService; private ProductImageHelper productImageHelper; private CartRestorationFacade cartRestorationFacade; private List<SapCartFacadeHook> sapCartFacadeHooks; private SessionService sessionService; private I18NService i18nService; private MessageSource messageSource; /** * @return the i18nService */ public I18NService getI18nService() { return i18nService; } /** * @param i18nService * the i18nService to set */ public void setI18nService(final I18NService i18nService) { this.i18nService = i18nService; } /** * @return the messageSource */ public MessageSource getMessageSource() { return messageSource; } /** * @param messageSource * the messageSource to set */ public void setMessageSource(final MessageSource messageSource) { this.messageSource = messageSource; } @Override public boolean hasSessionCart() { if (!isSyncOrdermgmtEnabled()) { return super.hasSessionCart(); } if (isBackendDown()) { return super.hasSessionCart(); } return getSapCartService().hasSessionCart(); } @Override public CartData getMiniCart() { if (!isSyncOrdermgmtEnabled()) { return super.getSessionCart(); } return getSessionCart(); } @Override public CartData getSessionCart() { if (!isSyncOrdermgmtEnabled()) { return super.getSessionCart(); } if (LOG.isDebugEnabled()) { LOG.debug("getSessionCart"); } if (isBackendDown()) { addErrorMessages(); final CartData cartWhenSessionDown = super.getSessionCart(); cartWhenSessionDown.setBackendDown(true); cartWhenSessionDown.getTotalPrice().setFormattedValue(""); return cartWhenSessionDown; } else { if (!isUserLoggedOn()) { return createEmptyCart(); } final CartData sessionCart = getSapCartService().getSessionCart(); if (sessionCart.getTotalUnitCount() == null) { sessionCart.setTotalUnitCount(Integer.valueOf(0)); } sessionCart.setCode(super.getSessionCart().getCode()); productImageHelper.enrichWithProductImages(sessionCart); return sessionCart; } } @Override public CartData getSessionCartWithEntryOrdering(final boolean recentlyAddedFirst) { if (!isSyncOrdermgmtEnabled()) { return super.getSessionCartWithEntryOrdering(recentlyAddedFirst); } if (LOG.isDebugEnabled()) { LOG.debug("getSessionCartWithEntryOrdering called with: " + recentlyAddedFirst); } if (isBackendDown()) { final CartData cartWhenSessionDown = super.getSessionCartWithEntryOrdering(recentlyAddedFirst); cartWhenSessionDown.setBackendDown(true); cartWhenSessionDown.getTotalPrice().setFormattedValue(""); return cartWhenSessionDown; } else { if (!isUserLoggedOn()) { return createEmptyCart(); } final CartData sessionCart = getSapCartService().getSessionCart(recentlyAddedFirst); sessionCart.setCode(super.getSessionCart().getCode()); productImageHelper.enrichWithProductImages(sessionCart); return sessionCart; } } @Override public CartModificationData addToCart(final String code, final long quantity) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.addToCart(code, quantity); } if (isBackendDown()) { addErrorMessages(); final CartModificationData cartModificationBackendDown = super.addToCart(code, quantity); final OrderEntryData entry = cartModificationBackendDown.getEntry(); entry.setBackendDown(true); return cartModificationBackendDown; } else { final CartModificationData cartModification = getSapCartService().addToCart(code, quantity); productImageHelper.enrichWithProductImages(cartModification.getEntry()); if (getCartRestorationFacade() != null) { getCartRestorationFacade().setSavedCart(getSapCartService().getSessionCart()); } return cartModification; } } /** * */ private void addErrorMessages() { final List<CartModificationData> modifications = new ArrayList<>(); final CartModificationData modificationData = new CartModificationData(); final OrderEntryData entryMsg = new OrderEntryData(); final ProductData product = new ProductData(); product.setName( getMessageSource().getMessage("sap.checkout.backend.offline.message", null, getI18nService().getCurrentLocale())); entryMsg.setProduct(product); modificationData.setStatusMessage( getMessageSource().getMessage("sap.checkout.backend.offline.message", null, getI18nService().getCurrentLocale())); modificationData.setEntry(entryMsg); modificationData.setStatusCode(SapordermgmtservicesConstants.STATUS_SAP_ERROR); modifications.add(modificationData); getSessionService().setAttribute("validations", modifications); } @Override public CartModificationData addToCart(final String code, final long quantity, final String storeId) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.addToCart(code, quantity, storeId); } LOG.info("addToCart called with store ID, ignoring: " + storeId); return this.addToCart(code, quantity); } /** * Add quick order entries to cart * * @param cartEntries * list of cart entries * @return cart modification data * @throws CommerceCartModificationException * exception */ public List<CartModificationData> addItemsToCart(final List<OrderEntryData> cartEntries) throws CommerceCartModificationException { List<CartModificationData> modificationDataList; modificationDataList = getSapCartService().addEntriesToCart(cartEntries); return modificationDataList; } @Override public List<CartModificationData> validateCartData() throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.validateCartData(); } return getSapCartService().validateCartData(); } @Override public CartModificationData updateCartEntry(final long entryNumber, final long quantity) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.updateCartEntry(entryNumber, quantity); } if (isBackendDown()) { final List<OrderEntryData> entries = getSessionCart().getEntries(); beforeCartEntryUpdate(quantity, entryNumber, entries); return super.updateCartEntry(entryNumber, quantity); } else { final CartModificationData cartModification = getSapCartService().updateCartEntry(entryNumber, quantity); if (this.cartRestorationFacade != null) { this.cartRestorationFacade.setSavedCart(getSapCartService().getSessionCart()); } return cartModification; } } /** * @param quantity * @param entryNumber * @param entries */ private void beforeCartEntryUpdate(final long quantity, final long entryNumber, final List<OrderEntryData> entries) { if (getSapCartFacadeHooks() != null) { for (final SapCartFacadeHook defaultSapCartFacadeHook : getSapCartFacadeHooks()) { defaultSapCartFacadeHook.beforeCartEntryUpdate(quantity, entryNumber, entries); } } } protected boolean isSyncOrdermgmtEnabled() { return (getBaseStoreService().getCurrentBaseStore().getSAPConfiguration() != null) && (getBaseStoreService().getCurrentBaseStore().getSAPConfiguration().isSapordermgmt_enabled()); } /** * @return the baseStoreService */ public BaseStoreService getBaseStoreService() { return baseStoreService; } /** * @param baseStoreService * the baseStoreService to set */ @Required public void setBaseStoreService(final BaseStoreService baseStoreService) { this.baseStoreService = baseStoreService; } /** * @return the sapCartService */ public CartService getSapCartService() { return sapCartService; } /** * @param sapCartService * the sapCartService to set */ @Required public void setSapCartService(final CartService sapCartService) { this.sapCartService = sapCartService; } /** * @return the backendAvailabilityService */ public BackendAvailabilityService getBackendAvailabilityService() { return backendAvailabilityService; } /** * @param backendAvailabilityService * the backendAvailabilityService to set */ @Required public void setBackendAvailabilityService(final BackendAvailabilityService backendAvailabilityService) { this.backendAvailabilityService = backendAvailabilityService; } private boolean isUserLoggedOn() { final UserModel userModel = super.getUserService().getCurrentUser(); return !super.getUserService().isAnonymousUser(userModel); } /** * @return the productImageHelper */ public ProductImageHelper getProductImageHelper() { return productImageHelper; } /** * @param productImageHelper * the productImageHelper to set */ @Required public void setProductImageHelper(final ProductImageHelper productImageHelper) { this.productImageHelper = productImageHelper; } /** * @return Is Backend down? */ private boolean isBackendDown() { return backendAvailabilityService.isBackendDown(); } /** * @return the cartRestorationFacade */ public CartRestorationFacade getCartRestorationFacade() { return cartRestorationFacade; } /** * @param cartRestorationFacade * the cartRestorationFacade to set */ @Required public void setCartRestorationFacade(final CartRestorationFacade cartRestorationFacade) { this.cartRestorationFacade = cartRestorationFacade; } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#updateCartEntry(long, java.lang.String) */ @Override public CartModificationData updateCartEntry(final long entryNumber, final String storeId) throws CommerceCartModificationException { if (!isSyncOrdermgmtEnabled()) { return super.updateCartEntry(entryNumber, storeId); } throw new ApplicationBaseRuntimeException("Not supported: updateCartEntry(final long entryNumber, final String storeId)"); } @Override public CartRestorationData restoreSavedCart(final String code) throws CommerceCartRestorationException { if (!isSyncOrdermgmtEnabled()) { return super.restoreSavedCart(code); } if (isBackendDown()) { return super.restoreSavedCart(code); } else { if (this.cartRestorationFacade != null) { return this.cartRestorationFacade.restoreSavedCart(code, super.getUserService().getCurrentUser()); } return null; } } @Override public List<CountryData> getDeliveryCountries() { if (!isSyncOrdermgmtEnabled()) { return super.getDeliveryCountries(); } //No delivery countries available, only choosing from existing addresses supported return Collections.emptyList(); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#estimateExternalTaxes(java.lang.String, * java.lang.String) */ @Override public CartData estimateExternalTaxes(final String deliveryZipCode, final String countryIsoCode) { if (!isSyncOrdermgmtEnabled()) { return super.estimateExternalTaxes(deliveryZipCode, countryIsoCode); } //We cannot support this, as the delivery costs are based on the ship-to party address in the ERP case throw new ApplicationBaseRuntimeException("Not supported: estimateExternalTaxes"); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#removeStaleCarts() */ @Override public void removeStaleCarts() { if (!isSyncOrdermgmtEnabled()) { super.removeStaleCarts(); return; } //No stale carts in this scenario } @Override public CartRestorationData restoreAnonymousCartAndTakeOwnership(final String guid) throws CommerceCartRestorationException { if (!isSyncOrdermgmtEnabled()) { return super.restoreAnonymousCartAndTakeOwnership(guid); } //No anonymous carts in our scenario return null; } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#removeSessionCart() */ @Override public void removeSessionCart() { if (!isSyncOrdermgmtEnabled()) { super.removeSessionCart(); return; } if (this.cartRestorationFacade != null) { this.cartRestorationFacade.removeSavedCart(); } getSapCartService().removeSessionCart(); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#getCartsForCurrentUser() */ @Override public List<CartData> getCartsForCurrentUser() { if (!isSyncOrdermgmtEnabled()) { return super.getCartsForCurrentUser(); } return Arrays.asList(getSessionCart()); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#restoreAnonymousCartAndMerge(java.lang.String, * java.lang.String) */ @Override public CartRestorationData restoreAnonymousCartAndMerge(final String fromAnonumousCartGuid, final String toUserCartGuid) throws CommerceCartMergingException, CommerceCartRestorationException { if (!isSyncOrdermgmtEnabled()) { return super.restoreAnonymousCartAndMerge(fromAnonumousCartGuid, toUserCartGuid); } throw new ApplicationBaseRuntimeException("restoreAnonymousCartAndMerge not supported"); } /* * (non-Javadoc) * * @see de.hybris.platform.commercefacades.order.impl.DefaultCartFacade#restoreCartAndMerge(java.lang.String, * java.lang.String) */ @Override public CartRestorationData restoreCartAndMerge(final String fromUserCartGuid, final String toUserCartGuid) throws CommerceCartRestorationException, CommerceCartMergingException { if (!isSyncOrdermgmtEnabled()) { return super.restoreCartAndMerge(fromUserCartGuid, toUserCartGuid); } throw new ApplicationBaseRuntimeException("restoreCartAndMerge not supported"); } @Override public boolean hasEntries() { if (!isSyncOrdermgmtEnabled()) { return super.hasEntries(); } if (isBackendDown()) { return super.hasEntries(); } else { final CartData sessionCart = getSapCartService().getSessionCart(); if (sessionCart != null && sessionCart.getEntries() != null) { return !sessionCart.getEntries().isEmpty(); } return false; } } /** * @return the sapCartFacadeHooks */ public List<SapCartFacadeHook> getSapCartFacadeHooks() { return sapCartFacadeHooks; } /** * @param sapCartFacadeHooks * the sapCartFacadeHooks to set */ public void setSapCartFacadeHooks(final List<SapCartFacadeHook> sapCartFacadeHooks) { this.sapCartFacadeHooks = sapCartFacadeHooks; } /** * @return the sessionService */ public SessionService getSessionService() { return sessionService; } /** * @param sessionService * the sessionService to set */ public void setSessionService(final SessionService sessionService) { this.sessionService = sessionService; } }
17,478
0.757467
0.754949
710
23.616901
29.503302
124
false
false
0
0
0
0
0
0
1.577465
false
false
15
487f8f05e24685ff4df628de83e8e56d646957a2
10,788,957,849,087
267e16c0a14dbf5c7c76260d9d79e393f846d0aa
/src/com/feiyue/dao/C_countDao.java
41fedd574a03bef7def192044190b1914c950c12
[ "MIT" ]
permissive
lanshanxiang/CMSys
https://github.com/lanshanxiang/CMSys
fae1b11dfec6b379c079283fbcf0d4626aa28a13
3f219bafa396dd39fe5f309ce9dc8a11d2846de5
refs/heads/master
2020-04-01T00:53:48.375000
2018-10-22T02:02:49
2018-10-22T02:02:49
152,717,830
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.feiyue.dao; import java.util.List; import com.feiyue.entiy.B_count; import com.feiyue.entiy.C_count; /** * * @author Administrator * */ public interface C_countDao { //查询所有 public List<C_count> queryAll(); }
UTF-8
Java
255
java
C_countDao.java
Java
[ { "context": "rt com.feiyue.entiy.C_count;\r\n/**\r\n * \r\n * @author Administrator\r\n *\r\n */\r\npublic interface C_countDao {\r\n\t//查询所有\r", "end": 155, "score": 0.9613720774650574, "start": 142, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.feiyue.dao; import java.util.List; import com.feiyue.entiy.B_count; import com.feiyue.entiy.C_count; /** * * @author Administrator * */ public interface C_countDao { //查询所有 public List<C_count> queryAll(); }
255
0.647773
0.647773
15
14.466666
13.455441
36
false
false
0
0
0
0
0
0
0.4
false
false
15
232cf5d03df11322e7a3e5ba0a99de518f696e91
22,686,017,319,296
cc66060096e7a173e641e330ff21c3085ae826e7
/src/Piece.java
d75f8969fec3704a1e7dae77e59c6eef272208b3
[]
no_license
TestSubject06/JTetris
https://github.com/TestSubject06/JTetris
f5057eaec6ccd1329838dc3cb86741eda21fb5b0
034d56259cd4cc203f0c752d4b7e61364e97d442
refs/heads/master
2016-09-05T21:23:10.374000
2014-09-06T14:33:47
2014-09-06T14:33:47
23,736,406
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * The base class for all pieces. Contains most of the logic. * @author Zack */ public class Piece { //These are all needed by subclasses. protected int x, y; //i tiles, of the top left of the model protected int rotation, tileID; protected int[][] rotation1, rotation2, rotation3, rotation4; protected int[][] currentRotation; protected int[] lows, highs, lefts, rights; /** * Creates a new Piece. * @param x the X coordinate in tiles * @param y the Y coordinate in tiles * @param tileID the unique ID for use with rendering on the board */ public Piece(int x, int y, int tileID){ this.x = x; this.y = y; this.tileID = tileID; rotation = 3; lefts = new int[4]; rights = new int[4]; highs = new int[4]; lows = new int[4]; } /** * Attempts to move in a given direction. * @param dir The direction to move in. 0 = Down; 1 = Left; 2 = Right * @return Returns whether or not the move was a success */ public boolean move(int dir){ boolean canMove = true; switch(dir){ case 0: for(int i = 0; i < 4; i++){ if(lows[i] != -1) if(!PlayingField.getPlayingField().isTileVacant(x+i,y+lows[i]+1)) canMove = false; } if(canMove){ y++; for(int i = 0; i < 4; i++){ if(highs[i] != -1) PlayingField.getPlayingField().setTile(x+i, y+highs[i]-1, 0); if(lows[i] != -1) PlayingField.getPlayingField().setTile(x+i, y+lows[i], tileID); } return true; } break; case 1: for(int i = 0; i < 4; i++){ if(lefts[i] != -1) if(!PlayingField.getPlayingField().isTileVacant(x+lefts[i]-1,y+i)) canMove = false; } if(canMove){ x--; for(int i = 0; i < 4; i++){ if(rights[i] != -1) PlayingField.getPlayingField().setTile(x+rights[i]+1, y+i, 0); if(lefts[i] != -1) PlayingField.getPlayingField().setTile(x+lefts[i], y+i, tileID); } return true; } break; case 2: for(int i = 0; i < 4; i++){ if(rights[i] != -1) if(!PlayingField.getPlayingField().isTileVacant(x+rights[i]+1,y+i)) canMove = false; } if(canMove){ x++; for(int i = 0; i < 4; i++){ if(lefts[i] != -1) PlayingField.getPlayingField().setTile(x+lefts[i]-1, y+i, 0); if(rights[i] != -1) PlayingField.getPlayingField().setTile(x+rights[i], y+i, tileID); } return true; } break; } return false; } /** * Phases the block out of existence. This is useful for getting the state * of the board without the activePiece. */ public void phaseOut(){ for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) PlayingField.getPlayingField().setTile(x+i, y+k, 0); } } } /** * Phases the piece back onto the board. This is used when bringing a piece * back after a phaseOut. */ public void phaseIn(){ for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) PlayingField.getPlayingField().setTile(x+i, y+k, tileID); } } } /** * Attempts to rotate in the given direction. * @param dir The direction to rotate in. 0 = Clockwise; 1 = Counter-Clockwise * @return whether the rotate was successful or not */ public boolean rotate(int dir){ //Let's get a wall kick rolling here. phaseOut(); if(dir == 0){ rotation--; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; }else{ rotation++; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; } boolean rotationWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) rotationWorks = false; } } if(!rotationWorks){ x++; //Move to the right one rotationWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) rotationWorks = false; } } if(!rotationWorks){ x-=2; //Move to the left one from the original rotationWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) rotationWorks = false; } } if(!rotationWorks){ x++; //All have failed, go home. if(dir == 0){ rotation++; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; }else{ rotation--; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; } phaseIn(); return false; } } } registerEdges(); phaseIn(); return true; } /** * Moves the piece down until it can no longer move down. * (Essentially slams the piece into the board) */ public void settle(){ while(move(0)){ //just spam it till it isn't true. } } // //The following are used to construct the collision edges for the pieces. //They only work on solid, convex shapes (Which luckily is all the tetroids) // /** * Returns the last 1 found in terms of Y * @param col the column to check * @return the last 1 found. */ public int checkColumnDown(int[] col){ int ret = -1; for(int i = 0; i<col.length; i++){ if(col[i] == 1) ret = i; } return ret; } /** * Returns the first 1 found in terms of Y * @param col the column to check * @return the first 1 found. */ public int checkColumnUp(int[] col){ for(int i = 0; i<col.length; i++){ if(col[i] == 1) return i; } return -1; } /** * Returns the last 1 found in terms of X * @param row the row to check * @param twoD the model array * @return the last 1 found */ public int checkRowRight(int row, int[][] twoD){ int ret = -1; for(int i = 0; i<twoD.length; i++){ if(twoD[i][row] == 1) ret = i; } return ret; } /** * Returns the first 1 found in terms of X * @param row the row to check * @param twoD the model array * @return the first 1 found */ public int checkRowLeft(int row, int[][] twoD){ for(int i = 0; i<twoD.length; i++){ if(twoD[i][row] == 1) return i; } return -1; } /** * Registers all of the edges of the piece. * called when a piece rotates, spawns, or is otherwise changed. */ public void registerEdges(){ lows[0] = checkColumnDown(currentRotation[0]); lows[1] = checkColumnDown(currentRotation[1]); lows[2] = checkColumnDown(currentRotation[2]); lows[3] = checkColumnDown(currentRotation[3]); highs[0] = checkColumnUp(currentRotation[0]); highs[1] = checkColumnUp(currentRotation[1]); highs[2] = checkColumnUp(currentRotation[2]); highs[3] = checkColumnUp(currentRotation[3]); lefts[0] = checkRowLeft(0, currentRotation); lefts[1] = checkRowLeft(1, currentRotation); lefts[2] = checkRowLeft(2, currentRotation); lefts[3] = checkRowLeft(3, currentRotation); rights[0] = checkRowRight(0, currentRotation); rights[1] = checkRowRight(1, currentRotation); rights[2] = checkRowRight(2, currentRotation); rights[3] = checkRowRight(3, currentRotation); } /** * Checks to see if a piece is offscreen, by checking the lows. * @return */ public boolean checkOffscreen(){ for(int i = 0; i < 4; i++){ if(lows[i] != -1) if(y+lows[i] <= 0) return true; } return false; } /** * Checks to see if the spawn area is safe for the piece, if there is a collision on spawn */ public void checkSpawn(){ boolean spawnWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) spawnWorks = false; } } if(!spawnWorks){ PlayingField.getPlayingField().endGame(); //GameOver. } } }
UTF-8
Java
11,725
java
Piece.java
Java
[ { "context": "all pieces. Contains most of the logic.\n * @author Zack\n */\npublic class Piece {\n \n //These are all", "end": 83, "score": 0.9917287826538086, "start": 79, "tag": "NAME", "value": "Zack" } ]
null
[]
/** * The base class for all pieces. Contains most of the logic. * @author Zack */ public class Piece { //These are all needed by subclasses. protected int x, y; //i tiles, of the top left of the model protected int rotation, tileID; protected int[][] rotation1, rotation2, rotation3, rotation4; protected int[][] currentRotation; protected int[] lows, highs, lefts, rights; /** * Creates a new Piece. * @param x the X coordinate in tiles * @param y the Y coordinate in tiles * @param tileID the unique ID for use with rendering on the board */ public Piece(int x, int y, int tileID){ this.x = x; this.y = y; this.tileID = tileID; rotation = 3; lefts = new int[4]; rights = new int[4]; highs = new int[4]; lows = new int[4]; } /** * Attempts to move in a given direction. * @param dir The direction to move in. 0 = Down; 1 = Left; 2 = Right * @return Returns whether or not the move was a success */ public boolean move(int dir){ boolean canMove = true; switch(dir){ case 0: for(int i = 0; i < 4; i++){ if(lows[i] != -1) if(!PlayingField.getPlayingField().isTileVacant(x+i,y+lows[i]+1)) canMove = false; } if(canMove){ y++; for(int i = 0; i < 4; i++){ if(highs[i] != -1) PlayingField.getPlayingField().setTile(x+i, y+highs[i]-1, 0); if(lows[i] != -1) PlayingField.getPlayingField().setTile(x+i, y+lows[i], tileID); } return true; } break; case 1: for(int i = 0; i < 4; i++){ if(lefts[i] != -1) if(!PlayingField.getPlayingField().isTileVacant(x+lefts[i]-1,y+i)) canMove = false; } if(canMove){ x--; for(int i = 0; i < 4; i++){ if(rights[i] != -1) PlayingField.getPlayingField().setTile(x+rights[i]+1, y+i, 0); if(lefts[i] != -1) PlayingField.getPlayingField().setTile(x+lefts[i], y+i, tileID); } return true; } break; case 2: for(int i = 0; i < 4; i++){ if(rights[i] != -1) if(!PlayingField.getPlayingField().isTileVacant(x+rights[i]+1,y+i)) canMove = false; } if(canMove){ x++; for(int i = 0; i < 4; i++){ if(lefts[i] != -1) PlayingField.getPlayingField().setTile(x+lefts[i]-1, y+i, 0); if(rights[i] != -1) PlayingField.getPlayingField().setTile(x+rights[i], y+i, tileID); } return true; } break; } return false; } /** * Phases the block out of existence. This is useful for getting the state * of the board without the activePiece. */ public void phaseOut(){ for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) PlayingField.getPlayingField().setTile(x+i, y+k, 0); } } } /** * Phases the piece back onto the board. This is used when bringing a piece * back after a phaseOut. */ public void phaseIn(){ for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) PlayingField.getPlayingField().setTile(x+i, y+k, tileID); } } } /** * Attempts to rotate in the given direction. * @param dir The direction to rotate in. 0 = Clockwise; 1 = Counter-Clockwise * @return whether the rotate was successful or not */ public boolean rotate(int dir){ //Let's get a wall kick rolling here. phaseOut(); if(dir == 0){ rotation--; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; }else{ rotation++; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; } boolean rotationWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) rotationWorks = false; } } if(!rotationWorks){ x++; //Move to the right one rotationWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) rotationWorks = false; } } if(!rotationWorks){ x-=2; //Move to the left one from the original rotationWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) rotationWorks = false; } } if(!rotationWorks){ x++; //All have failed, go home. if(dir == 0){ rotation++; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; }else{ rotation--; rotation = rotation%4; if(rotation == -1) rotation = 3; if(rotation == 0) currentRotation = rotation1; if(rotation == 1) currentRotation = rotation2; if(rotation == 2) currentRotation = rotation3; if(rotation == 3) currentRotation = rotation4; } phaseIn(); return false; } } } registerEdges(); phaseIn(); return true; } /** * Moves the piece down until it can no longer move down. * (Essentially slams the piece into the board) */ public void settle(){ while(move(0)){ //just spam it till it isn't true. } } // //The following are used to construct the collision edges for the pieces. //They only work on solid, convex shapes (Which luckily is all the tetroids) // /** * Returns the last 1 found in terms of Y * @param col the column to check * @return the last 1 found. */ public int checkColumnDown(int[] col){ int ret = -1; for(int i = 0; i<col.length; i++){ if(col[i] == 1) ret = i; } return ret; } /** * Returns the first 1 found in terms of Y * @param col the column to check * @return the first 1 found. */ public int checkColumnUp(int[] col){ for(int i = 0; i<col.length; i++){ if(col[i] == 1) return i; } return -1; } /** * Returns the last 1 found in terms of X * @param row the row to check * @param twoD the model array * @return the last 1 found */ public int checkRowRight(int row, int[][] twoD){ int ret = -1; for(int i = 0; i<twoD.length; i++){ if(twoD[i][row] == 1) ret = i; } return ret; } /** * Returns the first 1 found in terms of X * @param row the row to check * @param twoD the model array * @return the first 1 found */ public int checkRowLeft(int row, int[][] twoD){ for(int i = 0; i<twoD.length; i++){ if(twoD[i][row] == 1) return i; } return -1; } /** * Registers all of the edges of the piece. * called when a piece rotates, spawns, or is otherwise changed. */ public void registerEdges(){ lows[0] = checkColumnDown(currentRotation[0]); lows[1] = checkColumnDown(currentRotation[1]); lows[2] = checkColumnDown(currentRotation[2]); lows[3] = checkColumnDown(currentRotation[3]); highs[0] = checkColumnUp(currentRotation[0]); highs[1] = checkColumnUp(currentRotation[1]); highs[2] = checkColumnUp(currentRotation[2]); highs[3] = checkColumnUp(currentRotation[3]); lefts[0] = checkRowLeft(0, currentRotation); lefts[1] = checkRowLeft(1, currentRotation); lefts[2] = checkRowLeft(2, currentRotation); lefts[3] = checkRowLeft(3, currentRotation); rights[0] = checkRowRight(0, currentRotation); rights[1] = checkRowRight(1, currentRotation); rights[2] = checkRowRight(2, currentRotation); rights[3] = checkRowRight(3, currentRotation); } /** * Checks to see if a piece is offscreen, by checking the lows. * @return */ public boolean checkOffscreen(){ for(int i = 0; i < 4; i++){ if(lows[i] != -1) if(y+lows[i] <= 0) return true; } return false; } /** * Checks to see if the spawn area is safe for the piece, if there is a collision on spawn */ public void checkSpawn(){ boolean spawnWorks = true; for(int i = 0; i < 4; i++){ for(int k = 0; k <4; k++){ if(currentRotation[i][k] == 1) if (!PlayingField.getPlayingField().isTileVacant(x+i, y+k)) spawnWorks = false; } } if(!spawnWorks){ PlayingField.getPlayingField().endGame(); //GameOver. } } }
11,725
0.444094
0.428571
348
32.689655
21.474422
94
false
false
0
0
0
0
0
0
0.597701
false
false
15
300502f08e8ef4fab726494276804e0fd948e14b
27,350,351,802,854
f4423d042d20d725cc00b32c082279033f1ba37f
/src/main/java/com/lzw/servers/UserServer.java
e3fd7c80de73cb0f800602b43d9cb1d5694d6b3c
[]
no_license
L-Jim/SsmDemo
https://github.com/L-Jim/SsmDemo
d3700991465bc9990a94e37109025c67b5880d54
c56ec53224c2c70cac304a8858b3c05473958d1b
refs/heads/master
2021-01-21T09:33:46.214000
2018-10-18T01:36:00
2018-10-18T01:36:00
91,657,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lzw.servers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lzw.mapper.User; import com.lzw.mapper.UserMapper; @Service public class UserServer { @Autowired UserMapper userMapper; public PageInfo getuser(Integer i) { PageHelper.startPage(i, 3); List<User> users= userMapper.selectAll(); PageInfo<User> page = new PageInfo<User> (users); return page; } }
UTF-8
Java
702
java
UserServer.java
Java
[]
null
[]
package com.lzw.servers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lzw.mapper.User; import com.lzw.mapper.UserMapper; @Service public class UserServer { @Autowired UserMapper userMapper; public PageInfo getuser(Integer i) { PageHelper.startPage(i, 3); List<User> users= userMapper.selectAll(); PageInfo<User> page = new PageInfo<User> (users); return page; } }
702
0.749288
0.747863
30
21.4
19.341837
62
false
false
0
0
0
0
0
0
1.166667
false
false
15
5f6abdb66655f156247e6a4ec1f3e404fb5d68e3
12,034,498,371,608
01a72c8c2ae2bac870c274b6376cb9ce027411ab
/vote-app-api/src/main/java/com/leoyon/vote/repair/RepairServiceImp.java
5ecbe954e01fb77ecb061815c509406606ce51aa
[]
no_license
346294202/vote
https://github.com/346294202/vote
14fe8a75a9258663a5d89ba87d56f5c8889f11ae
1ac64e97f46562bde918ed4d5857d584ebacca8f
refs/heads/master
2021-05-02T02:38:42.658000
2018-03-13T06:50:10
2018-03-13T06:50:10
120,885,801
0
2
null
false
2018-02-23T06:23:28
2018-02-09T09:31:13
2018-02-13T06:41:31
2018-02-23T06:23:28
248
0
0
0
Java
false
null
package com.leoyon.vote.repair; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.leoyon.vote.FindPagedRequest; import com.leoyon.vote.house.HouseService; import com.leoyon.vote.house.dao.HouseDao; import com.leoyon.vote.repair.dao.RepairDao; @Service public class RepairServiceImp implements RepairService { @Autowired private RepairDao dao; @Autowired private HouseDao houseDao; @Override public Collection<Repair> find(FindPagedRequest rqst) { Collection<Repair> ret = dao.find(rqst); ret.forEach(i -> { i.setPictures(dao.getPictures(i.getId())); }); return ret; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) public void add(Repair entity) { dao.add(entity); dao.addPictures(entity); } }
UTF-8
Java
1,007
java
RepairServiceImp.java
Java
[]
null
[]
package com.leoyon.vote.repair; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.leoyon.vote.FindPagedRequest; import com.leoyon.vote.house.HouseService; import com.leoyon.vote.house.dao.HouseDao; import com.leoyon.vote.repair.dao.RepairDao; @Service public class RepairServiceImp implements RepairService { @Autowired private RepairDao dao; @Autowired private HouseDao houseDao; @Override public Collection<Repair> find(FindPagedRequest rqst) { Collection<Repair> ret = dao.find(rqst); ret.forEach(i -> { i.setPictures(dao.getPictures(i.getId())); }); return ret; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) public void add(Repair entity) { dao.add(entity); dao.addPictures(entity); } }
1,007
0.783515
0.783515
40
24.174999
22.862511
84
false
false
0
0
0
0
0
0
1.2
false
false
15
174cd29b4c7b1b6bda2b18c2aff2e42c4aef997e
16,698,832,911,991
d312ffae3a5c7dae52753b77da90f44a12e4fd9e
/src/main/java/com/gilmarcarlos/developer/gcursos/model/usuarios/exceptions/EscolaridadeExisteException.java
5aaf5f90e1a1d139e2dd4596bb565bb2315316a2
[]
no_license
gilmardeveloper/java-cursos
https://github.com/gilmardeveloper/java-cursos
46b42502914d1c953f904a0508238192a5b72963
ed2a9543365bf995896487bcaf957b5a746204df
refs/heads/master
2020-04-03T11:45:40.593000
2018-10-29T15:21:45
2018-10-29T15:21:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gilmarcarlos.developer.gcursos.model.usuarios.exceptions; /** * Classe para lançar excessões na validação de escolaridades * * @author Gilmar Carlos * */ public class EscolaridadeExisteException extends Exception{ /** * */ private static final long serialVersionUID = 1L; public EscolaridadeExisteException() { super("opção não pode ser deletada"); } public EscolaridadeExisteException(String msg) { super(msg); } }
UTF-8
Java
463
java
EscolaridadeExisteException.java
Java
[ { "context": "ssões na validação de escolaridades\n * \n * @author Gilmar Carlos\n *\n */\npublic class EscolaridadeExisteException e", "end": 165, "score": 0.9998685717582703, "start": 152, "tag": "NAME", "value": "Gilmar Carlos" } ]
null
[]
package com.gilmarcarlos.developer.gcursos.model.usuarios.exceptions; /** * Classe para lançar excessões na validação de escolaridades * * @author <NAME> * */ public class EscolaridadeExisteException extends Exception{ /** * */ private static final long serialVersionUID = 1L; public EscolaridadeExisteException() { super("opção não pode ser deletada"); } public EscolaridadeExisteException(String msg) { super(msg); } }
456
0.734649
0.732456
24
18
23.153473
69
false
false
0
0
0
0
0
0
0.75
false
false
15
f910ded53919bfd930db027ac222213a4bcdcf31
13,134,010,008,794
cdc280838fb4421ce674438fc670975bd3f70dc6
/developer-parvathy/VolunteerApp/src/main/java/com/kef/org/rest/service/AdminService.java
4e3fa9abfd049bc306642c61e83fdcfbfe5cd66c
[]
no_license
ApneSaathi/ApneSaathiBackend
https://github.com/ApneSaathi/ApneSaathiBackend
f41479cfcdaf08a8524bf3462f7b93fe6d571cee
2e703d537cbce5d186bdb98a520f19f0237c010e
refs/heads/master
2022-12-14T00:57:22.904000
2020-09-30T15:31:36
2020-09-30T15:31:36
271,623,928
0
1
null
false
2020-07-29T06:52:51
2020-06-11T18:51:47
2020-07-29T06:31:41
2020-07-29T06:52:50
109
0
1
0
Java
false
false
package com.kef.org.rest.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kef.org.rest.interfaces.AdminInterface; import com.kef.org.rest.model.Admin; import com.kef.org.rest.repository.AdminRepository; @Service("adminService") public class AdminService implements AdminInterface{ @Autowired private AdminRepository adminRespository; @Override public Admin fetchAdminDetails(String mobileNo) { return adminRespository.fetchAdminDetails(mobileNo); } @Override public Integer findAdminId(String mobileNo) { return adminRespository.fetchByphoneNumber(mobileNo); } }
UTF-8
Java
698
java
AdminService.java
Java
[]
null
[]
package com.kef.org.rest.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kef.org.rest.interfaces.AdminInterface; import com.kef.org.rest.model.Admin; import com.kef.org.rest.repository.AdminRepository; @Service("adminService") public class AdminService implements AdminInterface{ @Autowired private AdminRepository adminRespository; @Override public Admin fetchAdminDetails(String mobileNo) { return adminRespository.fetchAdminDetails(mobileNo); } @Override public Integer findAdminId(String mobileNo) { return adminRespository.fetchByphoneNumber(mobileNo); } }
698
0.777937
0.777937
28
22.928572
22.886253
62
false
false
0
0
0
0
0
0
0.928571
false
false
15
9516ad1dd8685061a39007e3eb62109d3b4c3f9b
28,673,201,692,977
78794df9daa412a5373c15aa0e7f3b13e2919030
/keyboard-base/src/main/java/org/geogebra/keyboard/base/Resource.java
21c40bf58ee68b44a4a3a688e0c0f9faf080e110
[]
no_license
marcelomata/geogebra
https://github.com/marcelomata/geogebra
08c78480ce14a21806dc9bdbe9878f0970412a62
e721a043c7e22c45760d178a734f72d89f95952a
refs/heads/master
2021-01-11T05:50:21.745000
2017-06-20T13:36:50
2017-06-20T13:36:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.geogebra.keyboard.base; /** * The items correspond to {@link ResourceType#DEFINED_CONSTANT}. */ public enum Resource { POWA2, POWAB, EMPTY_IMAGE, BACKSPACE_DELETE, RETURN_ENTER, LEFT_ARROW, RIGHT_ARROW, LOG_10, LOG_B, POWE_X, POW10_X, N_ROOT, A_N, CAPS_LOCK, CAPS_LOCK_ENABLED, INTEGRAL, DERIVATIVE, ROOT, LANGUAGE }
UTF-8
Java
339
java
Resource.java
Java
[]
null
[]
package org.geogebra.keyboard.base; /** * The items correspond to {@link ResourceType#DEFINED_CONSTANT}. */ public enum Resource { POWA2, POWAB, EMPTY_IMAGE, BACKSPACE_DELETE, RETURN_ENTER, LEFT_ARROW, RIGHT_ARROW, LOG_10, LOG_B, POWE_X, POW10_X, N_ROOT, A_N, CAPS_LOCK, CAPS_LOCK_ENABLED, INTEGRAL, DERIVATIVE, ROOT, LANGUAGE }
339
0.719764
0.705015
9
36.777779
39.921528
110
false
false
0
0
0
0
0
0
2.111111
false
false
15
3331cd8ad02ef0d59a67d7c4302d9b9baa43e45a
111,669,191,551
c4a8e3562befeb564d21c02e25d13163b478c809
/plugin/src/main/java/com/denizenscript/denizen/scripts/commands/entity/FollowCommand.java
505b484ab26ccfd8213df2a29246c5d113832920
[ "MIT" ]
permissive
CounterCrysis/Denizen
https://github.com/CounterCrysis/Denizen
4774a9b152ad3455ee63325d59137551ae8d1e62
55f09b33b9108b0be69f00e58bf8812cdf9f0402
refs/heads/dev
2022-03-04T13:58:23.328000
2019-09-20T20:12:01
2019-09-20T20:12:01
208,967,685
0
0
MIT
true
2019-09-21T02:26:35
2019-09-17T05:37:42
2019-09-18T03:54:06
2019-09-21T02:26:34
34,461
0
0
0
Java
false
false
package com.denizenscript.denizen.scripts.commands.entity; import com.denizenscript.denizen.utilities.Utilities; import com.denizenscript.denizen.utilities.debugging.Debug; import com.denizenscript.denizen.nms.NMSHandler; import com.denizenscript.denizen.objects.EntityTag; import com.denizenscript.denizen.objects.NPCTag; import com.denizenscript.denizencore.exceptions.InvalidArgumentsException; import com.denizenscript.denizencore.objects.Argument; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.ArgumentHelper; import com.denizenscript.denizencore.objects.core.ListTag; import com.denizenscript.denizencore.scripts.ScriptEntry; import com.denizenscript.denizencore.scripts.commands.AbstractCommand; public class FollowCommand extends AbstractCommand { // <--[command] // @Name Follow // @Syntax follow (followers:<entity>|...) (stop) (lead:<#.#>) (max:<#.#>) (speed:<#.#>) (target:<entity>) (allow_wander) // @Required 0 // @Short Causes a list of entities to follow a target. // @Group entity // // @Description // TODO: Document Command Details // The 'max' and 'allow_wander' arguments can only be used on non-NPC entities. // // @Tags // <NPCTag.navigator.target_entity> returns the entity the npc is following. // // @Usage // To make an NPC follow the player in an interact script // - follow followers:<npc> target:<player> // TODO: Document Command Details // --> @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { // Parse Arguments for (Argument arg : scriptEntry.getProcessedArgs()) { if (!scriptEntry.hasObject("stop") && arg.matches("STOP")) { scriptEntry.addObject("stop", new ElementTag(true)); } else if (!scriptEntry.hasObject("lead") && arg.matchesPrimitive(ArgumentHelper.PrimitiveType.Double) && arg.matchesPrefix("l", "lead")) { scriptEntry.addObject("lead", arg.asElement()); } else if (!scriptEntry.hasObject("max") && arg.matchesPrimitive(ArgumentHelper.PrimitiveType.Double) && arg.matchesPrefix("max")) { scriptEntry.addObject("max", arg.asElement()); } else if (!scriptEntry.hasObject("allow_wander") && arg.matches("allow_wander")) { scriptEntry.addObject("allow_wander", new ElementTag(true)); } else if (!scriptEntry.hasObject("speed") && arg.matchesPrimitive(ArgumentHelper.PrimitiveType.Percentage) && arg.matchesPrefix("s", "speed")) { scriptEntry.addObject("speed", arg.asElement()); } else if (!scriptEntry.hasObject("entities") && arg.matchesPrefix("followers", "follower") && arg.matchesArgumentList(EntityTag.class)) { scriptEntry.addObject("entities", arg.asType(ListTag.class)); } else if (!scriptEntry.hasObject("target") && arg.matchesArgumentType(EntityTag.class)) { scriptEntry.addObject("target", arg.asType(EntityTag.class)); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("target")) { if (Utilities.entryHasPlayer(scriptEntry)) { scriptEntry.addObject("target", Utilities.getEntryPlayer(scriptEntry).getDenizenEntity()); } else { throw new InvalidArgumentsException("This command requires a linked player!"); } } if (!scriptEntry.hasObject("entities")) { if (!Utilities.entryHasNPC(scriptEntry)) { throw new InvalidArgumentsException("This command requires a linked NPC!"); } else { scriptEntry.addObject("entities", new ListTag(Utilities.getEntryNPC(scriptEntry).identify())); } } scriptEntry.defaultObject("stop", new ElementTag(false)).defaultObject("allow_wander", new ElementTag(false)); } @Override public void execute(ScriptEntry scriptEntry) { // Get objects ElementTag stop = scriptEntry.getElement("stop"); ElementTag lead = scriptEntry.getElement("lead"); ElementTag maxRange = scriptEntry.getElement("max"); ElementTag allowWander = scriptEntry.getElement("allow_wander"); ElementTag speed = scriptEntry.getElement("speed"); ListTag entities = scriptEntry.getObjectTag("entities"); EntityTag target = scriptEntry.getObjectTag("target"); // Report to dB if (scriptEntry.dbCallShouldDebug()) { Debug.report(scriptEntry, getName(), (Utilities.getEntryPlayer(scriptEntry) != null ? Utilities.getEntryPlayer(scriptEntry).debug() : "") + (!stop.asBoolean() ? ArgumentHelper.debugObj("Action", "FOLLOW") : ArgumentHelper.debugObj("Action", "STOP")) + (lead != null ? lead.debug() : "") + (maxRange != null ? maxRange.debug() : "") + allowWander.debug() + entities.debug() + target.debug()); } for (EntityTag entity : entities.filter(EntityTag.class, scriptEntry)) { if (entity.isCitizensNPC()) { NPCTag npc = entity.getDenizenNPC(); if (lead != null) { npc.getNavigator().getLocalParameters().distanceMargin(lead.asDouble()); } if (speed != null) { npc.getNavigator().getLocalParameters().speedModifier(speed.asFloat()); } if (stop.asBoolean()) { npc.getNavigator().cancelNavigation(); } else { npc.getNavigator().setTarget(target.getBukkitEntity(), false); } } else { if (stop.asBoolean()) { NMSHandler.getEntityHelper().stopFollowing(entity.getBukkitEntity()); } else { NMSHandler.getEntityHelper().follow(target.getBukkitEntity(), entity.getBukkitEntity(), speed != null ? speed.asDouble() : 0.3, lead != null ? lead.asDouble() : 5, maxRange != null ? maxRange.asDouble() : 8, allowWander.asBoolean()); } } } } }
UTF-8
Java
6,980
java
FollowCommand.java
Java
[]
null
[]
package com.denizenscript.denizen.scripts.commands.entity; import com.denizenscript.denizen.utilities.Utilities; import com.denizenscript.denizen.utilities.debugging.Debug; import com.denizenscript.denizen.nms.NMSHandler; import com.denizenscript.denizen.objects.EntityTag; import com.denizenscript.denizen.objects.NPCTag; import com.denizenscript.denizencore.exceptions.InvalidArgumentsException; import com.denizenscript.denizencore.objects.Argument; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.ArgumentHelper; import com.denizenscript.denizencore.objects.core.ListTag; import com.denizenscript.denizencore.scripts.ScriptEntry; import com.denizenscript.denizencore.scripts.commands.AbstractCommand; public class FollowCommand extends AbstractCommand { // <--[command] // @Name Follow // @Syntax follow (followers:<entity>|...) (stop) (lead:<#.#>) (max:<#.#>) (speed:<#.#>) (target:<entity>) (allow_wander) // @Required 0 // @Short Causes a list of entities to follow a target. // @Group entity // // @Description // TODO: Document Command Details // The 'max' and 'allow_wander' arguments can only be used on non-NPC entities. // // @Tags // <NPCTag.navigator.target_entity> returns the entity the npc is following. // // @Usage // To make an NPC follow the player in an interact script // - follow followers:<npc> target:<player> // TODO: Document Command Details // --> @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { // Parse Arguments for (Argument arg : scriptEntry.getProcessedArgs()) { if (!scriptEntry.hasObject("stop") && arg.matches("STOP")) { scriptEntry.addObject("stop", new ElementTag(true)); } else if (!scriptEntry.hasObject("lead") && arg.matchesPrimitive(ArgumentHelper.PrimitiveType.Double) && arg.matchesPrefix("l", "lead")) { scriptEntry.addObject("lead", arg.asElement()); } else if (!scriptEntry.hasObject("max") && arg.matchesPrimitive(ArgumentHelper.PrimitiveType.Double) && arg.matchesPrefix("max")) { scriptEntry.addObject("max", arg.asElement()); } else if (!scriptEntry.hasObject("allow_wander") && arg.matches("allow_wander")) { scriptEntry.addObject("allow_wander", new ElementTag(true)); } else if (!scriptEntry.hasObject("speed") && arg.matchesPrimitive(ArgumentHelper.PrimitiveType.Percentage) && arg.matchesPrefix("s", "speed")) { scriptEntry.addObject("speed", arg.asElement()); } else if (!scriptEntry.hasObject("entities") && arg.matchesPrefix("followers", "follower") && arg.matchesArgumentList(EntityTag.class)) { scriptEntry.addObject("entities", arg.asType(ListTag.class)); } else if (!scriptEntry.hasObject("target") && arg.matchesArgumentType(EntityTag.class)) { scriptEntry.addObject("target", arg.asType(EntityTag.class)); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("target")) { if (Utilities.entryHasPlayer(scriptEntry)) { scriptEntry.addObject("target", Utilities.getEntryPlayer(scriptEntry).getDenizenEntity()); } else { throw new InvalidArgumentsException("This command requires a linked player!"); } } if (!scriptEntry.hasObject("entities")) { if (!Utilities.entryHasNPC(scriptEntry)) { throw new InvalidArgumentsException("This command requires a linked NPC!"); } else { scriptEntry.addObject("entities", new ListTag(Utilities.getEntryNPC(scriptEntry).identify())); } } scriptEntry.defaultObject("stop", new ElementTag(false)).defaultObject("allow_wander", new ElementTag(false)); } @Override public void execute(ScriptEntry scriptEntry) { // Get objects ElementTag stop = scriptEntry.getElement("stop"); ElementTag lead = scriptEntry.getElement("lead"); ElementTag maxRange = scriptEntry.getElement("max"); ElementTag allowWander = scriptEntry.getElement("allow_wander"); ElementTag speed = scriptEntry.getElement("speed"); ListTag entities = scriptEntry.getObjectTag("entities"); EntityTag target = scriptEntry.getObjectTag("target"); // Report to dB if (scriptEntry.dbCallShouldDebug()) { Debug.report(scriptEntry, getName(), (Utilities.getEntryPlayer(scriptEntry) != null ? Utilities.getEntryPlayer(scriptEntry).debug() : "") + (!stop.asBoolean() ? ArgumentHelper.debugObj("Action", "FOLLOW") : ArgumentHelper.debugObj("Action", "STOP")) + (lead != null ? lead.debug() : "") + (maxRange != null ? maxRange.debug() : "") + allowWander.debug() + entities.debug() + target.debug()); } for (EntityTag entity : entities.filter(EntityTag.class, scriptEntry)) { if (entity.isCitizensNPC()) { NPCTag npc = entity.getDenizenNPC(); if (lead != null) { npc.getNavigator().getLocalParameters().distanceMargin(lead.asDouble()); } if (speed != null) { npc.getNavigator().getLocalParameters().speedModifier(speed.asFloat()); } if (stop.asBoolean()) { npc.getNavigator().cancelNavigation(); } else { npc.getNavigator().setTarget(target.getBukkitEntity(), false); } } else { if (stop.asBoolean()) { NMSHandler.getEntityHelper().stopFollowing(entity.getBukkitEntity()); } else { NMSHandler.getEntityHelper().follow(target.getBukkitEntity(), entity.getBukkitEntity(), speed != null ? speed.asDouble() : 0.3, lead != null ? lead.asDouble() : 5, maxRange != null ? maxRange.asDouble() : 8, allowWander.asBoolean()); } } } } }
6,980
0.561461
0.560745
154
43.324677
31.257183
139
false
false
0
0
0
0
0
0
0.435065
false
false
15
56700341a1435902e9d2e84c66f77a983909fbeb
11,235,634,466,887
e957aad3c3f96cef739e99c40b9926fc133c8c98
/hu.bme.mit.cps/src/cps/constraint/CorrectSeverityLevelConstraint.java
7d65b2bfbb9b9e0c7b34c78e20772fe4f97361d4
[]
no_license
akbence/calab3
https://github.com/akbence/calab3
2ab938b351da89d224b5c8cacf9e4aa6566fb1c5
e98875ad53fc665fa3528e0c56b27c79aa78ce54
refs/heads/master
2020-04-24T02:13:21.954000
2019-02-20T11:07:43
2019-02-20T11:07:43
171,629,376
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cps.constraint; import org.eclipse.core.runtime.IStatus; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.validation.AbstractModelConstraint; import org.eclipse.emf.validation.EMFEventType; import org.eclipse.emf.validation.IValidationContext; import cps.Alarm; import cps.Controller; import cps.MotionDetector; import cps.Severity; import cps.SmokeDetector; import cps.Task; public class CorrectSeverityLevelConstraint extends AbstractModelConstraint { @Override public IStatus validate(IValidationContext ctx) { EObject eObj = ctx.getTarget(); EMFEventType eType = ctx.getEventType(); // In the case of batch mode. if (eType == EMFEventType.NULL) { if (eObj instanceof Task) { if (eObj instanceof MotionDetector) { if (((Task) eObj).getSeverity() != Severity.LOW) { return ctx.createFailureStatus(eObj.eClass().getName()); } } else if (eObj instanceof Alarm) { if (((Task) eObj).getSeverity() != Severity.MEDIUM) { return ctx.createFailureStatus(eObj.eClass().getName()); } } else if (eObj instanceof SmokeDetector) { if (((Task) eObj).getSeverity() != Severity.HIGH) { return ctx.createFailureStatus(eObj.eClass().getName()); } } else if (eObj instanceof Controller) { if (((Task) eObj).getSeverity() != Severity.CRITICAL) { return ctx.createFailureStatus(eObj.eClass().getName()); } } } } return ctx.createSuccessStatus(); } }
UTF-8
Java
1,473
java
CorrectSeverityLevelConstraint.java
Java
[]
null
[]
package cps.constraint; import org.eclipse.core.runtime.IStatus; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.validation.AbstractModelConstraint; import org.eclipse.emf.validation.EMFEventType; import org.eclipse.emf.validation.IValidationContext; import cps.Alarm; import cps.Controller; import cps.MotionDetector; import cps.Severity; import cps.SmokeDetector; import cps.Task; public class CorrectSeverityLevelConstraint extends AbstractModelConstraint { @Override public IStatus validate(IValidationContext ctx) { EObject eObj = ctx.getTarget(); EMFEventType eType = ctx.getEventType(); // In the case of batch mode. if (eType == EMFEventType.NULL) { if (eObj instanceof Task) { if (eObj instanceof MotionDetector) { if (((Task) eObj).getSeverity() != Severity.LOW) { return ctx.createFailureStatus(eObj.eClass().getName()); } } else if (eObj instanceof Alarm) { if (((Task) eObj).getSeverity() != Severity.MEDIUM) { return ctx.createFailureStatus(eObj.eClass().getName()); } } else if (eObj instanceof SmokeDetector) { if (((Task) eObj).getSeverity() != Severity.HIGH) { return ctx.createFailureStatus(eObj.eClass().getName()); } } else if (eObj instanceof Controller) { if (((Task) eObj).getSeverity() != Severity.CRITICAL) { return ctx.createFailureStatus(eObj.eClass().getName()); } } } } return ctx.createSuccessStatus(); } }
1,473
0.702648
0.702648
49
29.061224
22.607031
77
false
false
0
0
0
0
0
0
2.612245
false
false
15
493f8898836f0937289ab7ee70f4436bd5b4aad4
22,462,678,959,043
b5bc50ffc4abc6bb77cb5b208ece874e1e65f311
/app/src/main/java/de/hosenhasser/funktrainer/exam/QuestionResults.java
9d5873c818fe268cffd8e73120f870bba725854f
[ "Apache-2.0" ]
permissive
meyerd/funktrainer
https://github.com/meyerd/funktrainer
9efa12354f452c8b39f9ddc5a1227bb799a41c2b
9c50a7851d374553b0d41bfb7164c5562658a3a3
refs/heads/master
2023-03-02T05:53:17.463000
2022-02-09T15:46:24
2022-02-09T15:46:24
46,332,462
8
9
Apache-2.0
false
2023-02-23T17:14:26
2015-11-17T08:12:53
2022-02-09T15:36:55
2023-02-23T17:14:26
27,176
6
7
5
PLpgSQL
false
false
package de.hosenhasser.funktrainer.exam; import java.io.Serializable; import java.util.List; import de.hosenhasser.funktrainer.data.ExamSettings; import de.hosenhasser.funktrainer.data.QuestionState; public class QuestionResults implements Serializable { private List<QuestionState> results; private ExamSettings examSettings; public QuestionResults(final List<QuestionState> rl, final ExamSettings e) { this.results = rl; this.examSettings = e; } public List<QuestionState> getResults() { return results; } public ExamSettings getExamSettings() { return examSettings; } }
UTF-8
Java
642
java
QuestionResults.java
Java
[]
null
[]
package de.hosenhasser.funktrainer.exam; import java.io.Serializable; import java.util.List; import de.hosenhasser.funktrainer.data.ExamSettings; import de.hosenhasser.funktrainer.data.QuestionState; public class QuestionResults implements Serializable { private List<QuestionState> results; private ExamSettings examSettings; public QuestionResults(final List<QuestionState> rl, final ExamSettings e) { this.results = rl; this.examSettings = e; } public List<QuestionState> getResults() { return results; } public ExamSettings getExamSettings() { return examSettings; } }
642
0.732087
0.732087
25
24.719999
22.183813
80
false
false
0
0
0
0
0
0
0.48
false
false
15
0e73c8fc1d65a3750dd1bf31f2c3b6622c6df958
25,675,314,518,889
ab48d571f63d37313daf8467b189f6ac1626b700
/core/src/de/geniusatwork/playground/dungeon/start/resources/DungeonResLoader.java
32675fcfe751346f65138f79888b9099e1ee748b
[]
no_license
RobertPense/Playground
https://github.com/RobertPense/Playground
de2d08641a0c7d819002f49a923a214aea446c48
519763d475a734b50389267679b7c18ebdb051b8
refs/heads/master
2016-08-06T12:51:49.117000
2015-08-30T08:24:09
2015-08-30T08:24:09
32,424,251
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.geniusatwork.playground.dungeon.start.resources; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; /** * Created by Robse on 17.03.15. */ public class DungeonResLoader { private Texture background; private Texture border; private Texture blob; public DungeonResLoader() { loadTextures(); } protected void loadTextures () { blob = new Texture(Gdx.files.internal("data/dungeon/blob.png")); background = new Texture(Gdx.files.internal("data/dungeon/background.png")); border = new Texture(Gdx.files.internal("data/dungeon/border.png")); } public Texture getBackground() { return background; } public Texture getBorder() { return border; } public Texture getBlob() { return blob; } }
UTF-8
Java
830
java
DungeonResLoader.java
Java
[ { "context": ".badlogic.gdx.graphics.Texture;\n\n/**\n * Created by Robse on 17.03.15.\n */\npublic class DungeonResLoader {\n", "end": 156, "score": 0.9989149570465088, "start": 151, "tag": "USERNAME", "value": "Robse" } ]
null
[]
package de.geniusatwork.playground.dungeon.start.resources; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; /** * Created by Robse on 17.03.15. */ public class DungeonResLoader { private Texture background; private Texture border; private Texture blob; public DungeonResLoader() { loadTextures(); } protected void loadTextures () { blob = new Texture(Gdx.files.internal("data/dungeon/blob.png")); background = new Texture(Gdx.files.internal("data/dungeon/background.png")); border = new Texture(Gdx.files.internal("data/dungeon/border.png")); } public Texture getBackground() { return background; } public Texture getBorder() { return border; } public Texture getBlob() { return blob; } }
830
0.657831
0.650602
36
22.055555
22.644529
84
false
false
0
0
0
0
0
0
0.361111
false
false
15
8b2a78cf9464eaf232a7fecbbc99078b8be75104
13,340,168,476,278
65fb5dc284f0daa43e1822a3173d1e6087c137dd
/src/bsts/BST.java
aaf3da54b7d39e3f8a1c238f28d9753c331b56f4
[]
no_license
IoanaCM/data_structures
https://github.com/IoanaCM/data_structures
3281e7be406b2f29aaca24deb722d171ce8de047
0d2794e78bbca4bee346cee5b12838f7bbac0786
refs/heads/master
2023-04-14T01:51:54.771000
2021-04-25T17:17:49
2021-04-25T17:17:49
356,090,462
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bsts; public interface BST<E extends Comparable<E>> { boolean add(E element); boolean remove(E element); boolean contains(E element); }
UTF-8
Java
155
java
BST.java
Java
[]
null
[]
package bsts; public interface BST<E extends Comparable<E>> { boolean add(E element); boolean remove(E element); boolean contains(E element); }
155
0.709677
0.709677
11
13.090909
15.962767
47
false
false
0
0
0
0
0
0
0.363636
false
false
15
7fd509597c556952ff3cc45d388cdb6a32b8e8f8
18,073,222,398,957
c54c77b1e73050c5b01d4c8b461b995b36c5b8ab
/src/main/java/com/demo/loan/service/SuserService.java
100d8f80b8d16279f9677abf7492d37ab455bb00
[]
no_license
jj392502304/demo
https://github.com/jj392502304/demo
6e28f34b1650f3f515e9eb84494eafd66487a7ab
30e7e8785a4a1e0a3c71d4dff20649646f818c69
refs/heads/master
2020-04-20T05:11:58.324000
2019-08-16T02:44:36
2019-08-16T02:44:36
168,649,651
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.loan.service; import com.demo.loan.entity.Suser; import com.constant.core.Service; /** * Created by CodeGenerator on 2019/02/18. */ public interface SuserService extends Service<Suser> { }
UTF-8
Java
211
java
SuserService.java
Java
[ { "context": "ort com.constant.core.Service;\n\n\n/**\n * Created by CodeGenerator on 2019/02/18.\n */\npublic interface SuserService ", "end": 133, "score": 0.9540690183639526, "start": 120, "tag": "USERNAME", "value": "CodeGenerator" } ]
null
[]
package com.demo.loan.service; import com.demo.loan.entity.Suser; import com.constant.core.Service; /** * Created by CodeGenerator on 2019/02/18. */ public interface SuserService extends Service<Suser> { }
211
0.753555
0.71564
11
18.181818
19.557924
54
false
false
0
0
0
0
0
0
0.272727
false
false
15
8fea39f00564b0ff322793d3bd4371ff3979199f
24,919,400,269,134
af7324349107ef841094cce90dc17f1f62de14a8
/test/SudokuGeneratorTest.java
c4c94421b8aaf3fcd9afc530db3b7662b7b35424
[]
no_license
DewitteRuben/Sudoku
https://github.com/DewitteRuben/Sudoku
30490c791e9ea3edd4cf6d5be9186962117054c6
e390a2f2715fe062b7ca16934806dca233198c49
refs/heads/master
2021-01-21T17:37:50.441000
2018-06-29T21:55:22
2018-06-29T21:55:22
91,970,695
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import be.howest.ti.sudokuapplication.game.Sudoku; import be.howest.ti.sudokuapplication.game.SudokuGenerator; import be.howest.ti.sudokuapplication.ConsoleUI.consoleDisplay; import be.howest.ti.sudokuapplication.game.SudokuSolver; import be.howest.ti.sudokuapplication.game.SudokuValidator; import junit.framework.AssertionFailedError; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class SudokuGeneratorTest { int[][] unsolvedSudoku1 = new int[][]{ {5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, {0, 0, 0, 0, 8, 0, 0, 7, 9} }; int[][] solvedSudoku1 = new int[][]{ {8, 4, 5, 6, 3, 2, 1, 7, 9,}, {7, 3, 2, 9, 1, 8, 6, 5, 4,}, {1, 9, 6, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 7,}, {3, 6, 1, 4, 2, 9, 7, 8, 5,}, {5, 7, 4, 1, 8, 6, 2, 9, 3,}, {9, 2, 8, 3, 5, 7, 4, 6, 1,} }; int[][] invalidSudoku1 = new int[][]{ {8, 4, 6, 6, 3, 1, 2, 7, 9,}, {7, 3, 2, 9, 1, 8, 6, 5, 4,}, {1, 9, 4, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 5,}, {3, 6, 1, 4, 2, 9, 7, 8, 7,}, {5, 7, 5, 1, 8, 6, 2, 9, 3,}, {8, 2, 9, 3, 5, 7, 4, 6, 1,} }; int[][] falseSudoku1 = new int[][]{ {8, 4, 5, 6, 3, 8, 1, 7, 9,}, {7, 3, 2, 9, 1, 2, 6, 5, 4,}, {1, 9, 6, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 7,}, {3, 6, 1, 4, 2, 9, 7, 8, 5,}, {5, 7, 4, 1, 8, 6, 2, 9, 3,}, {9, 2, 8, 3, 5, 7, 4, 6, 1,} }; int[][] falseSudoku2 = new int[][]{ {8, 4, 5, 6, 3, 2, 1, 7, 9,}, {8, 3, 2, 9, 1, 7, 6, 5, 4,}, {1, 9, 6, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 7,}, {3, 6, 1, 4, 2, 9, 7, 8, 5,}, {5, 7, 4, 1, 8, 6, 2, 9, 3,}, {9, 2, 8, 3, 5, 7, 4, 6, 1,} }; int[][] solved3x2 = { {6, 1, 2, 3, 4, 5,}, {5, 3, 4, 6, 2, 1,}, {1, 2, 6, 5, 3, 4,}, {4, 5, 3, 2, 1, 6,}, {2, 4, 5, 1, 6, 3,}, {3, 6, 1, 4, 5, 2,} }; int[][] unsolved3x2 = { {0, 1, 2, 0, 0, 0,}, {0, 0, 0, 6, 0, 1,}, {0, 0, 0, 5, 3, 0,}, {4, 5, 0, 2, 1, 0,}, {2, 4, 0, 0, 6, 3}, {0, 0, 0, 0, 5, 2} }; // Generate 5000 sudoku secrets and check if they're valid @Test public void TestSudokuSecretGenerator() { SudokuGenerator SG = new SudokuGenerator(9, 9, 3, 3, "Normal"); SudokuValidator SV; for (int i = 0; i < 5000; i++) { SG.generateSudokuSecret(); SV = new SudokuValidator(SG.getSudoku()); assertTrue(SV.isValid()); } } // Generate 200 empty 12X12 (3X4) (Easy) Sudoku Grids @Test public void TestSudokuGenerator12X123X4Easy() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 200; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Easy"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 50 empty 12X12 (3X4) (Hard) Sudoku Grids @Test public void TestSudokuGenerator12X123X4Hard() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Hard"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 12X12 (3X4) (Normal) Sudoku Grids @Test public void TestSudokuGenerator12X123X4Normal() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 200 empty 12X12 (4X3) (Easy) Sudoku Grids @Test public void TestSudokuGenerator12X124X3Easy() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 200; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Easy"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false));; } } // Generate 100 empty 12X12 (4X3) (Hard) Sudoku Grids @Test public void TestSudokuGenerator12X124X3Hard() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Hard"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 12X12 (4X3) (Normal) Sudoku Grids @Test public void TestSudokuGenerator12X124X3Normal() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 200 empty 9X9 (Easy) Sudoku Grids @Test public void TestSudokuGenerator9X9Easy() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 200; i++) { SG = new SudokuGenerator(9, 9, 3, 3, "Easy"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 9X9 (Hard) Sudoku Grids @Test public void TestSudokuGenerator9X9Hard() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(9, 9, 3, 3, "Hard"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 9X9 (Normal) Sudoku Grids @Test public void TestSudokuGenerator9X9Normal() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(9, 9, 3, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 500 empty 6X6 (3X2) Sudoku Grids @Test public void TestSudokuGenerator6X63X2() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 500; i++) { SG = new SudokuGenerator(6, 6, 3, 2, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 500 empty 6X6 (2X3) Sudoku Grids @Test public void TestSudokuGenerator6X62X3() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 500; i++) { SG = new SudokuGenerator(6, 6, 2, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 5000 empty 4X4 Sudoku Grids @Test public void TestSudokuGenerator4X4() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 5000; i++) { SG = new SudokuGenerator(4, 4, 2, 2, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } }
UTF-8
Java
9,155
java
SudokuGeneratorTest.java
Java
[]
null
[]
import be.howest.ti.sudokuapplication.game.Sudoku; import be.howest.ti.sudokuapplication.game.SudokuGenerator; import be.howest.ti.sudokuapplication.ConsoleUI.consoleDisplay; import be.howest.ti.sudokuapplication.game.SudokuSolver; import be.howest.ti.sudokuapplication.game.SudokuValidator; import junit.framework.AssertionFailedError; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class SudokuGeneratorTest { int[][] unsolvedSudoku1 = new int[][]{ {5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, {0, 0, 0, 0, 8, 0, 0, 7, 9} }; int[][] solvedSudoku1 = new int[][]{ {8, 4, 5, 6, 3, 2, 1, 7, 9,}, {7, 3, 2, 9, 1, 8, 6, 5, 4,}, {1, 9, 6, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 7,}, {3, 6, 1, 4, 2, 9, 7, 8, 5,}, {5, 7, 4, 1, 8, 6, 2, 9, 3,}, {9, 2, 8, 3, 5, 7, 4, 6, 1,} }; int[][] invalidSudoku1 = new int[][]{ {8, 4, 6, 6, 3, 1, 2, 7, 9,}, {7, 3, 2, 9, 1, 8, 6, 5, 4,}, {1, 9, 4, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 5,}, {3, 6, 1, 4, 2, 9, 7, 8, 7,}, {5, 7, 5, 1, 8, 6, 2, 9, 3,}, {8, 2, 9, 3, 5, 7, 4, 6, 1,} }; int[][] falseSudoku1 = new int[][]{ {8, 4, 5, 6, 3, 8, 1, 7, 9,}, {7, 3, 2, 9, 1, 2, 6, 5, 4,}, {1, 9, 6, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 7,}, {3, 6, 1, 4, 2, 9, 7, 8, 5,}, {5, 7, 4, 1, 8, 6, 2, 9, 3,}, {9, 2, 8, 3, 5, 7, 4, 6, 1,} }; int[][] falseSudoku2 = new int[][]{ {8, 4, 5, 6, 3, 2, 1, 7, 9,}, {8, 3, 2, 9, 1, 7, 6, 5, 4,}, {1, 9, 6, 7, 4, 5, 3, 2, 8,}, {6, 8, 3, 5, 7, 4, 9, 1, 2,}, {4, 5, 7, 2, 9, 1, 8, 3, 6,}, {2, 1, 9, 8, 6, 3, 5, 4, 7,}, {3, 6, 1, 4, 2, 9, 7, 8, 5,}, {5, 7, 4, 1, 8, 6, 2, 9, 3,}, {9, 2, 8, 3, 5, 7, 4, 6, 1,} }; int[][] solved3x2 = { {6, 1, 2, 3, 4, 5,}, {5, 3, 4, 6, 2, 1,}, {1, 2, 6, 5, 3, 4,}, {4, 5, 3, 2, 1, 6,}, {2, 4, 5, 1, 6, 3,}, {3, 6, 1, 4, 5, 2,} }; int[][] unsolved3x2 = { {0, 1, 2, 0, 0, 0,}, {0, 0, 0, 6, 0, 1,}, {0, 0, 0, 5, 3, 0,}, {4, 5, 0, 2, 1, 0,}, {2, 4, 0, 0, 6, 3}, {0, 0, 0, 0, 5, 2} }; // Generate 5000 sudoku secrets and check if they're valid @Test public void TestSudokuSecretGenerator() { SudokuGenerator SG = new SudokuGenerator(9, 9, 3, 3, "Normal"); SudokuValidator SV; for (int i = 0; i < 5000; i++) { SG.generateSudokuSecret(); SV = new SudokuValidator(SG.getSudoku()); assertTrue(SV.isValid()); } } // Generate 200 empty 12X12 (3X4) (Easy) Sudoku Grids @Test public void TestSudokuGenerator12X123X4Easy() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 200; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Easy"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 50 empty 12X12 (3X4) (Hard) Sudoku Grids @Test public void TestSudokuGenerator12X123X4Hard() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Hard"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 12X12 (3X4) (Normal) Sudoku Grids @Test public void TestSudokuGenerator12X123X4Normal() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 200 empty 12X12 (4X3) (Easy) Sudoku Grids @Test public void TestSudokuGenerator12X124X3Easy() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 200; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Easy"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false));; } } // Generate 100 empty 12X12 (4X3) (Hard) Sudoku Grids @Test public void TestSudokuGenerator12X124X3Hard() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Hard"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 12X12 (4X3) (Normal) Sudoku Grids @Test public void TestSudokuGenerator12X124X3Normal() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(12, 12, 4, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 200 empty 9X9 (Easy) Sudoku Grids @Test public void TestSudokuGenerator9X9Easy() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 200; i++) { SG = new SudokuGenerator(9, 9, 3, 3, "Easy"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 9X9 (Hard) Sudoku Grids @Test public void TestSudokuGenerator9X9Hard() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(9, 9, 3, 3, "Hard"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 100 empty 9X9 (Normal) Sudoku Grids @Test public void TestSudokuGenerator9X9Normal() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 100; i++) { SG = new SudokuGenerator(9, 9, 3, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 500 empty 6X6 (3X2) Sudoku Grids @Test public void TestSudokuGenerator6X63X2() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 500; i++) { SG = new SudokuGenerator(6, 6, 3, 2, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 500 empty 6X6 (2X3) Sudoku Grids @Test public void TestSudokuGenerator6X62X3() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 500; i++) { SG = new SudokuGenerator(6, 6, 2, 3, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } // Generate 5000 empty 4X4 Sudoku Grids @Test public void TestSudokuGenerator4X4() { SudokuGenerator SG; SudokuValidator SV; for (int i = 0; i < 5000; i++) { SG = new SudokuGenerator(4, 4, 2, 2, "Normal"); SV = new SudokuValidator(SG.generate()); SudokuSolver SS = new SudokuSolver(SG.getSudoku()); assertTrue(SV.isValid()); assertEquals(1, SS.solve(false)); } } }
9,155
0.496122
0.413108
274
32.40876
18.865662
71
false
false
0
0
0
0
0
0
2.609489
false
false
15
bdd984027d182a1092fdec0c018fc9491766c195
32,375,463,503,948
cc72abc74748250a33ff2fd67d561137e473eaff
/src/twn/test/EventTest.java
d8bee72d22a86505da35636e31e5a13395f2bf81
[]
no_license
tywunon/twn.utils
https://github.com/tywunon/twn.utils
889b2cbcefaae75507d07f2571ae54e918730989
634da3e7d16a9eaf7da6f86ced4e43ed2cf810ca
refs/heads/master
2020-12-19T03:14:40.576000
2019-11-22T18:00:11
2019-11-22T18:00:11
235,603,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package twn.test; import static org.junit.Assert.*; import org.junit.Test; import twn.evt.Event; import twn.evt.EventArgs; public class EventTest { @Test public void eventRecived() { EventHolder evh = new EventHolder(); new EventReciever (evh); evh.invoke(); } private static class EventHolder { private final Object eventOwner = new Object(); public final Event<EventArgs> event = new Event<>(eventOwner); public void invoke() { event.fire(eventOwner, this, EventArgs.Empty); } } private static class EventReciever { public EventReciever(EventHolder evh){ evh.event.subscribe(this::handle); } private void handle(Object sender, EventArgs eventArgs) { assertTrue("Event recieved", true); } } }
UTF-8
Java
746
java
EventTest.java
Java
[]
null
[]
package twn.test; import static org.junit.Assert.*; import org.junit.Test; import twn.evt.Event; import twn.evt.EventArgs; public class EventTest { @Test public void eventRecived() { EventHolder evh = new EventHolder(); new EventReciever (evh); evh.invoke(); } private static class EventHolder { private final Object eventOwner = new Object(); public final Event<EventArgs> event = new Event<>(eventOwner); public void invoke() { event.fire(eventOwner, this, EventArgs.Empty); } } private static class EventReciever { public EventReciever(EventHolder evh){ evh.event.subscribe(this::handle); } private void handle(Object sender, EventArgs eventArgs) { assertTrue("Event recieved", true); } } }
746
0.710456
0.710456
37
19.162163
18.852936
64
false
false
0
0
0
0
0
0
1.621622
false
false
15
9e60632cb050a47ed78d1e52e86030e855843fce
24,103,356,503,587
d689632cdbc0bceaafe39e4892cae2c455fb0aff
/PSHesap/PSHesap/src/main/java/com/Hesap/PSHesap/repository/PStableStatusRepository.java
d5003bc02ac1e2ce33053f651fb72117ad021264
[]
no_license
burhanguven/PSCafeHesap-spring
https://github.com/burhanguven/PSCafeHesap-spring
a1e8c061d1da72f282ce20c8ce036e443e9c2722
c39ac16d67e1443e5b2af2191aee3afc1267df8d
refs/heads/master
2022-07-28T20:58:29.862000
2020-05-21T18:56:39
2020-05-21T18:56:39
260,466,720
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Hesap.PSHesap.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.Hesap.PSHesap.model.TableStatus; public interface PStableStatusRepository extends JpaRepository<TableStatus, Integer> { TableStatus findFirstById(Integer id); }
UTF-8
Java
304
java
PStableStatusRepository.java
Java
[]
null
[]
package com.Hesap.PSHesap.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.Hesap.PSHesap.model.TableStatus; public interface PStableStatusRepository extends JpaRepository<TableStatus, Integer> { TableStatus findFirstById(Integer id); }
304
0.822368
0.822368
13
22.384615
27.49696
86
false
false
0
0
0
0
0
0
0.692308
false
false
15
38a461f8a013b813e46f707da437b1248861b51c
32,461,362,830,493
22d6a5ece092b379acdc354790b3214216c4d33e
/siscarLogic/src/geniar/siscar/logic/vehicle/services/ReservesService.java
3751d25dd170a2b381b13f5b99c0ba9eedd92fbe
[]
no_license
josealvarohincapie/carritos
https://github.com/josealvarohincapie/carritos
82dd4927b4fab38ce6f393eebcdcf54da4eada85
b60ff02175facdbbd2ebc441a24e460200a18dd9
refs/heads/master
2021-01-25T04:08:59.955000
2015-03-04T03:44:59
2015-03-04T03:44:59
32,355,348
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package geniar.siscar.logic.vehicle.services; import geniar.siscar.model.Requests; import gwork.exception.GWorkException; public interface ReservesService { public void CancelarReservaVehiculoUsuario(String numeroSolicitud, String estadoSolicitud, String descripcion)throws GWorkException; public Requests ConsultarSolicitudAsignacionAlquilerVehiculos(String numeroSolicitud)throws GWorkException; }
UTF-8
Java
419
java
ReservesService.java
Java
[]
null
[]
package geniar.siscar.logic.vehicle.services; import geniar.siscar.model.Requests; import gwork.exception.GWorkException; public interface ReservesService { public void CancelarReservaVehiculoUsuario(String numeroSolicitud, String estadoSolicitud, String descripcion)throws GWorkException; public Requests ConsultarSolicitudAsignacionAlquilerVehiculos(String numeroSolicitud)throws GWorkException; }
419
0.842482
0.842482
12
32.916668
43.082207
133
false
false
0
0
0
0
0
0
0.75
false
false
15
c18ff9442edb994cef0511b284f8db2049ecc69f
5,746,666,270,225
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_af1989b0cc9a5aaa427597d37c28d0f0c2a21e0b/Bidding/17_af1989b0cc9a5aaa427597d37c28d0f0c2a21e0b_Bidding_s.java
e2bdda4d5b40d0d373137d77121fee0ce150fb3f
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/* @ShortLicense@ Author: @MJL@ Released: @ReleaseDate@ */ package de.jskat.ai.mjl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import de.jskat.util.CardList; import de.jskat.util.GameType; import de.jskat.util.SkatConstants; import de.jskat.util.Suit; /** * @author Markus J. Luzius <markus@luzius.de> * */ class Bidding { private Log log = LogFactory.getLog(Bidding.class); /** * Maximum value that the player will bid */ private int maxBid = -1; private GameType suggestedGameType = null; /** default constructor * @param cards hand of the player */ Bidding(CardList cards) { log.debug("Checking out what to bid with ["+cards+"]"); Suit mostFrequentSuitColor; int mostFrequentSuitColorValue = 0; int multiplier = Helper.getMultiplier(cards); mostFrequentSuitColor = cards.getMostFrequentSuit(); int noOfTrumps = cards.getSuitCount(mostFrequentSuitColor, true); int noOfJacks = Helper.countJacks(cards); if (mostFrequentSuitColor == Suit.CLUBS) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.CLUBS, false, false); } else if (mostFrequentSuitColor == Suit.SPADES) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.SPADES, false, false); } else if (mostFrequentSuitColor == Suit.HEARTS) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.HEARTS, false, false); } else if (mostFrequentSuitColor == Suit.DIAMONDS) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.DIAMONDS, false, false); } maxBid = mostFrequentSuitColorValue * multiplier; // but I will only play, if I have at least 1 jack and 4 color cards or 2 jacks and 3 color cards if (noOfJacks < 3 && noOfTrumps < 4) maxBid = 0; else if (noOfJacks < 2 && noOfTrumps < 5) maxBid = 0; else if (noOfJacks < 1 && noOfTrumps < 6) maxBid = 0; else if ((Helper.getJacks(cards)&12)==0 && noOfTrumps < 5) maxBid = 0; if(maxBid>0) suggestedGameType = mostFrequentSuitColor.getGameType(); log.debug("I will bid until " + maxBid +" - I have "+noOfJacks+" Jacks and "+noOfTrumps+" Trumps in suit "+mostFrequentSuitColor); } /** Gets the maximum bid value of the player * @return maximum bid value */ int getMaxBid() { return maxBid; } GameType getSuggestedGameType() { return suggestedGameType; } }
UTF-8
Java
2,496
java
17_af1989b0cc9a5aaa427597d37c28d0f0c2a21e0b_Bidding_s.java
Java
[ { "context": " /*\n \n @ShortLicense@\n \n Author: @MJL@\n \n Released: @ReleaseDate@\n \n */\n \n package de.j", "end": 37, "score": 0.8210914134979248, "start": 34, "tag": "USERNAME", "value": "MJL" }, { "context": "ts;\n import de.jskat.util.Suit;\n \n /**\n * @author Markus J. Luzius <markus@luzius.de>\n *\n */\n class Bidding {\n \n \t", "end": 355, "score": 0.9998818039894104, "start": 339, "tag": "NAME", "value": "Markus J. Luzius" }, { "context": "t.util.Suit;\n \n /**\n * @author Markus J. Luzius <markus@luzius.de>\n *\n */\n class Bidding {\n \n \tprivate Log log = ", "end": 373, "score": 0.9999339580535889, "start": 357, "tag": "EMAIL", "value": "markus@luzius.de" } ]
null
[]
/* @ShortLicense@ Author: @MJL@ Released: @ReleaseDate@ */ package de.jskat.ai.mjl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import de.jskat.util.CardList; import de.jskat.util.GameType; import de.jskat.util.SkatConstants; import de.jskat.util.Suit; /** * @author <NAME> <<EMAIL>> * */ class Bidding { private Log log = LogFactory.getLog(Bidding.class); /** * Maximum value that the player will bid */ private int maxBid = -1; private GameType suggestedGameType = null; /** default constructor * @param cards hand of the player */ Bidding(CardList cards) { log.debug("Checking out what to bid with ["+cards+"]"); Suit mostFrequentSuitColor; int mostFrequentSuitColorValue = 0; int multiplier = Helper.getMultiplier(cards); mostFrequentSuitColor = cards.getMostFrequentSuit(); int noOfTrumps = cards.getSuitCount(mostFrequentSuitColor, true); int noOfJacks = Helper.countJacks(cards); if (mostFrequentSuitColor == Suit.CLUBS) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.CLUBS, false, false); } else if (mostFrequentSuitColor == Suit.SPADES) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.SPADES, false, false); } else if (mostFrequentSuitColor == Suit.HEARTS) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.HEARTS, false, false); } else if (mostFrequentSuitColor == Suit.DIAMONDS) { mostFrequentSuitColorValue = SkatConstants.getGameBaseValue(GameType.DIAMONDS, false, false); } maxBid = mostFrequentSuitColorValue * multiplier; // but I will only play, if I have at least 1 jack and 4 color cards or 2 jacks and 3 color cards if (noOfJacks < 3 && noOfTrumps < 4) maxBid = 0; else if (noOfJacks < 2 && noOfTrumps < 5) maxBid = 0; else if (noOfJacks < 1 && noOfTrumps < 6) maxBid = 0; else if ((Helper.getJacks(cards)&12)==0 && noOfTrumps < 5) maxBid = 0; if(maxBid>0) suggestedGameType = mostFrequentSuitColor.getGameType(); log.debug("I will bid until " + maxBid +" - I have "+noOfJacks+" Jacks and "+noOfTrumps+" Trumps in suit "+mostFrequentSuitColor); } /** Gets the maximum bid value of the player * @return maximum bid value */ int getMaxBid() { return maxBid; } GameType getSuggestedGameType() { return suggestedGameType; } }
2,477
0.691106
0.682692
85
28.352942
29.412964
133
false
false
0
0
0
0
0
0
1.423529
false
false
15
7b75db7c6e48c942ae2dd333c97cd8f116e0404e
7,988,639,214,260
612aedf167c94e77b346b9551de5968f659f7980
/SS_PCMedica/src/conexion/control/Control.java
e9ca1ddad67b018e514a899569f617a547c92c83
[]
no_license
JavierMendez-262/ProyectoFinal_SecretariaDeLaSalud
https://github.com/JavierMendez-262/ProyectoFinal_SecretariaDeLaSalud
1f7c3290ba6733022f9a310683307e74ef96ec65
cdb771a6dc5800d973559242ebad61d75b2ebf12
refs/heads/master
2022-07-05T20:39:47.084000
2020-05-21T07:09:01
2020-05-21T07:09:01
256,647,704
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Control.java * * Documentado en Mayo 15, 2020. 09:41. */ package conexion.control; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.net.URI; import negocio.Expediente; import org.glassfish.tyrus.client.ClientManager; import conexion.rest.RecursoExpediente_Client; import conexion.rest.RecursoUsuario_Client; import conexion.websockets.ClientEndpointAnnotated; import java.io.IOException; import java.net.URISyntaxException; import javax.websocket.DeploymentException; import javax.ws.rs.BadRequestException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotAuthorizedException; import javax.ws.rs.NotFoundException; import negocio.Usuario; import org.glassfish.grizzly.ssl.SSLContextConfigurator; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.tyrus.client.ClientProperties; /** * Clase que maneja las conexiones al servidor. * * @author JavierMéndez 00000181816 & EnriqueMendoza 00000181798 */ public class Control { private static final String URI = "wss://localhost:8443/SS_BDLocal/websockets/expediente"; private RecursoUsuario_Client ruc; private RecursoExpediente_Client rec; private ClientEndpointAnnotated cea; private Gson gson; private String token; /** * Constructor que inicializa las variables de la clase. */ public Control(String nickname, String password) { this.rec = new RecursoExpediente_Client(); this.cea = new ClientEndpointAnnotated(this); this.ruc = new RecursoUsuario_Client(); gson = new GsonBuilder().setPrettyPrinting().create(); token = ruc.validar(new Usuario(nickname, password, 0, false)).readEntity(String.class); } /** * Método que solicita el expediente al servidor de la BD Local a través de * RESTful y WebSockets. * * @param id Id del expediente a solicitar de la BD Local. * @return Expediente del Id solicitado. */ public Expediente getExpediente(String idMedico, String idExpediente) throws IOException, URISyntaxException, DeploymentException { try { Expediente expediente = rec.getExpediente(token, idExpediente, idMedico);// Se solicita el expediente al servidor a través de RESTful. System.out.println(gson.toJson(expediente));//En caso de que el servidor local lo posea se imprime no más para ver. } catch (NotAuthorizedException ex) { System.out.println("No Esta Autorizado"); } catch (NotFoundException ex) {// Si no lo encuentra, solicitalo a través de WebSockets al servidor. prepareClient().connectToServer(cea, new URI(URI)); cea.sendMessage(idExpediente); System.out.println("Error: Expediente no encontrado en la Base de Datos Local...\nSolicitando al Servidor Remoto espere un momento... ");// Se espera a que la solicitud sea procesada. } catch (BadRequestException ex) { } catch (InternalServerErrorException ex) { } return null; } /** * Método que se invoca al obtenerse una respuesta de WS del Servidor. * * @param expedienteGson Expediente en formato Json solicitado */ public void receivedExpedienteWS(String message) { if (!message.equals("null")) { System.out.println(message); } else { System.out.println("Error: Expediente no inexistente."); } } /** * Método que actualiza el expediente al servidor de la BD Local a través de * RESTful. * * @param expediente Expediente a actualizar de la BD Local. */ public void putExpediente(Expediente expediente) { rec.putExpediente(expediente); } private ClientManager prepareClient() { System.getProperties().put(SSLContextConfigurator.KEY_STORE_FILE, "lib/certs/keystore.jks"); System.getProperties().put(SSLContextConfigurator.TRUST_STORE_FILE, "lib/certs/keystore.jks"); System.getProperties().put(SSLContextConfigurator.KEY_STORE_PASSWORD, "secretaria"); System.getProperties().put(SSLContextConfigurator.TRUST_STORE_PASSWORD, "secretaria"); final SSLContextConfigurator defaultConfig = new SSLContextConfigurator(); defaultConfig.retrieve(System.getProperties()); SSLEngineConfigurator sslEngineConfigurator = new SSLEngineConfigurator(defaultConfig, true, false, false); ClientManager client = ClientManager.createClient(); client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator); return client; } }
UTF-8
Java
4,758
java
Control.java
Java
[ { "context": "maneja las conexiones al servidor.\r\n *\r\n * @author JavierMéndez 00000181816 & EnriqueMendoza 00000181798\r\n */\r\npu", "end": 975, "score": 0.9996126890182495, "start": 963, "tag": "NAME", "value": "JavierMéndez" }, { "context": ").put(SSLContextConfigurator.KEY_STORE_PASSWORD, \"secretaria\");\r\n System.getProperties().put(SSLContext", "end": 4184, "score": 0.9993464350700378, "start": 4174, "tag": "PASSWORD", "value": "secretaria" }, { "context": "put(SSLContextConfigurator.TRUST_STORE_PASSWORD, \"secretaria\");\r\n\r\n final SSLContextConfigurator defaul", "end": 4280, "score": 0.9991832375526428, "start": 4270, "tag": "PASSWORD", "value": "secretaria" } ]
null
[]
/* * Control.java * * Documentado en Mayo 15, 2020. 09:41. */ package conexion.control; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.net.URI; import negocio.Expediente; import org.glassfish.tyrus.client.ClientManager; import conexion.rest.RecursoExpediente_Client; import conexion.rest.RecursoUsuario_Client; import conexion.websockets.ClientEndpointAnnotated; import java.io.IOException; import java.net.URISyntaxException; import javax.websocket.DeploymentException; import javax.ws.rs.BadRequestException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotAuthorizedException; import javax.ws.rs.NotFoundException; import negocio.Usuario; import org.glassfish.grizzly.ssl.SSLContextConfigurator; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.tyrus.client.ClientProperties; /** * Clase que maneja las conexiones al servidor. * * @author JavierMéndez 00000181816 & EnriqueMendoza 00000181798 */ public class Control { private static final String URI = "wss://localhost:8443/SS_BDLocal/websockets/expediente"; private RecursoUsuario_Client ruc; private RecursoExpediente_Client rec; private ClientEndpointAnnotated cea; private Gson gson; private String token; /** * Constructor que inicializa las variables de la clase. */ public Control(String nickname, String password) { this.rec = new RecursoExpediente_Client(); this.cea = new ClientEndpointAnnotated(this); this.ruc = new RecursoUsuario_Client(); gson = new GsonBuilder().setPrettyPrinting().create(); token = ruc.validar(new Usuario(nickname, password, 0, false)).readEntity(String.class); } /** * Método que solicita el expediente al servidor de la BD Local a través de * RESTful y WebSockets. * * @param id Id del expediente a solicitar de la BD Local. * @return Expediente del Id solicitado. */ public Expediente getExpediente(String idMedico, String idExpediente) throws IOException, URISyntaxException, DeploymentException { try { Expediente expediente = rec.getExpediente(token, idExpediente, idMedico);// Se solicita el expediente al servidor a través de RESTful. System.out.println(gson.toJson(expediente));//En caso de que el servidor local lo posea se imprime no más para ver. } catch (NotAuthorizedException ex) { System.out.println("No Esta Autorizado"); } catch (NotFoundException ex) {// Si no lo encuentra, solicitalo a través de WebSockets al servidor. prepareClient().connectToServer(cea, new URI(URI)); cea.sendMessage(idExpediente); System.out.println("Error: Expediente no encontrado en la Base de Datos Local...\nSolicitando al Servidor Remoto espere un momento... ");// Se espera a que la solicitud sea procesada. } catch (BadRequestException ex) { } catch (InternalServerErrorException ex) { } return null; } /** * Método que se invoca al obtenerse una respuesta de WS del Servidor. * * @param expedienteGson Expediente en formato Json solicitado */ public void receivedExpedienteWS(String message) { if (!message.equals("null")) { System.out.println(message); } else { System.out.println("Error: Expediente no inexistente."); } } /** * Método que actualiza el expediente al servidor de la BD Local a través de * RESTful. * * @param expediente Expediente a actualizar de la BD Local. */ public void putExpediente(Expediente expediente) { rec.putExpediente(expediente); } private ClientManager prepareClient() { System.getProperties().put(SSLContextConfigurator.KEY_STORE_FILE, "lib/certs/keystore.jks"); System.getProperties().put(SSLContextConfigurator.TRUST_STORE_FILE, "lib/certs/keystore.jks"); System.getProperties().put(SSLContextConfigurator.KEY_STORE_PASSWORD, "<PASSWORD>"); System.getProperties().put(SSLContextConfigurator.TRUST_STORE_PASSWORD, "<PASSWORD>"); final SSLContextConfigurator defaultConfig = new SSLContextConfigurator(); defaultConfig.retrieve(System.getProperties()); SSLEngineConfigurator sslEngineConfigurator = new SSLEngineConfigurator(defaultConfig, true, false, false); ClientManager client = ClientManager.createClient(); client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator); return client; } }
4,758
0.694251
0.68646
121
37.247932
36.605171
195
false
false
0
0
0
0
0
0
0.586777
false
false
15
b2baa321a55fcaf3c213730d05835d1e887142dc
26,517,128,112,594
5cddb68dcff3a512d89570bb82eb03aae524e807
/src/leetcode/IsPalindrome.java
861e1fb300d93f698827a9a9071f0ff0e3aeabd9
[]
no_license
biggerhuang/java-learn-notes
https://github.com/biggerhuang/java-learn-notes
df11cca11714b5423fb35edd24dbcbe4c0cba682
c8d8389de23d79991c4fb99d7eca5d2a1e9a76f2
refs/heads/master
2022-03-22T22:01:01.594000
2020-01-12T05:50:54
2020-01-12T05:50:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode; /** * 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 * 1 * 12 * 123 * 1234 * * @author hbj * @date 2020/1/12 13:33 */ public class IsPalindrome { public static boolean isPalindrome(int x) { if (x < 0) { return false; } if (x == 0) { return true; } String str = String.valueOf(x); char[] chars = str.toCharArray(); int i = 0; int j = chars.length - 1; for (; i < j; i++, j--) { if (chars[i] != chars[j]) { break; } } return i == j || i == j + 1; } public static void main(String[] args) { System.out.println(isPalindrome(-121)); } }
UTF-8
Java
823
java
IsPalindrome.java
Java
[ { "context": ")读都是一样的整数。\n * 1\n * 12\n * 123\n * 1234\n *\n * @author hbj\n * @date 2020/1/12 13:33\n */\npublic class IsPalin", "end": 114, "score": 0.999629020690918, "start": 111, "tag": "USERNAME", "value": "hbj" } ]
null
[]
package leetcode; /** * 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 * 1 * 12 * 123 * 1234 * * @author hbj * @date 2020/1/12 13:33 */ public class IsPalindrome { public static boolean isPalindrome(int x) { if (x < 0) { return false; } if (x == 0) { return true; } String str = String.valueOf(x); char[] chars = str.toCharArray(); int i = 0; int j = chars.length - 1; for (; i < j; i++, j--) { if (chars[i] != chars[j]) { break; } } return i == j || i == j + 1; } public static void main(String[] args) { System.out.println(isPalindrome(-121)); } }
823
0.461224
0.421769
36
19.416666
15.310445
47
false
false
0
0
0
0
0
0
0.416667
false
false
5
9b52dfcb6cbec5159821725a3510c48a5cb1b962
33,423,435,528,368
7d196e835fcd3a79f3d580b83d76153051f6c7e4
/nio.engine/src/ImplemClasses/MyServer.java
a8df85ad9a47fe3ef8a9bb8ae97ddae8c7d4d0bf
[]
no_license
fpeyre/SAR-NIO
https://github.com/fpeyre/SAR-NIO
2480629d8d9401f5d2e2ea83b8bf7d9a1e83d5ef
1ab803281060baa17d33eeffb1a96d99a0ffbb03
refs/heads/master
2021-01-19T14:56:12.111000
2014-10-30T14:38:05
2014-10-30T14:38:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ImplemClasses; import java.io.IOException; import java.nio.channels.ServerSocketChannel; import nio.engine.*; /** * This class wraps an accepted connection. It provides access to the port on * which the connection was accepted as well as the ability to close that */ public class MyServer extends NioServer { ServerSocketChannel myServerSocketChannel; AcceptCallback myCallback; public MyServer() { super(); } public MyServer(ServerSocketChannel myServerSocketChannel) { this.myServerSocketChannel = myServerSocketChannel; } public MyServer(ServerSocketChannel myServerSocketChannel, AcceptCallback callback) { this.myServerSocketChannel = myServerSocketChannel; this.myCallback = callback; } /** * @return the port onto which connections are accepted. */ @Override public int getPort() { return myServerSocketChannel.socket().getLocalPort(); } /** * Close the server port, no longer accepting connections. */ @Override public void close() { try { this.myServerSocketChannel.close(); } catch (IOException e) { System.out.println("Erreur close MyServer : "+e.getMessage()); } } public void setSSC(ServerSocketChannel ssc){ this.myServerSocketChannel=ssc; } public void setAcceptCallback(AcceptCallback cb){ this.myCallback=cb; } public AcceptCallback getAcceptCallback(){ return myCallback; } }
UTF-8
Java
1,462
java
MyServer.java
Java
[]
null
[]
package ImplemClasses; import java.io.IOException; import java.nio.channels.ServerSocketChannel; import nio.engine.*; /** * This class wraps an accepted connection. It provides access to the port on * which the connection was accepted as well as the ability to close that */ public class MyServer extends NioServer { ServerSocketChannel myServerSocketChannel; AcceptCallback myCallback; public MyServer() { super(); } public MyServer(ServerSocketChannel myServerSocketChannel) { this.myServerSocketChannel = myServerSocketChannel; } public MyServer(ServerSocketChannel myServerSocketChannel, AcceptCallback callback) { this.myServerSocketChannel = myServerSocketChannel; this.myCallback = callback; } /** * @return the port onto which connections are accepted. */ @Override public int getPort() { return myServerSocketChannel.socket().getLocalPort(); } /** * Close the server port, no longer accepting connections. */ @Override public void close() { try { this.myServerSocketChannel.close(); } catch (IOException e) { System.out.println("Erreur close MyServer : "+e.getMessage()); } } public void setSSC(ServerSocketChannel ssc){ this.myServerSocketChannel=ssc; } public void setAcceptCallback(AcceptCallback cb){ this.myCallback=cb; } public AcceptCallback getAcceptCallback(){ return myCallback; } }
1,462
0.707934
0.707934
68
19.5
23.48435
86
false
false
0
0
0
0
0
0
1.147059
false
false
5
165bc9d2258e225283ba7bf247c2a68f44a353da
16,088,947,524,236
3d8f229a23c091cb75715cf093e3a612bb15fae2
/EasyMother/src/com/Library/ToolsClass/.svn/text-base/GalleryItemAdapter.java.svn-base
c62724e494130e1ad984cf56707eeb154a48aac8
[]
no_license
zaxcler/EasyMother
https://github.com/zaxcler/EasyMother
f42affbeb5b2cb3f0d7d104b51d561110d5da75d
032692cd0439e6f3907c018f77b7c7d33ae81407
refs/heads/master
2021-01-17T11:33:51.246000
2015-11-09T06:33:09
2015-11-09T06:33:09
40,812,626
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Library.ToolsClass; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; public class GalleryItemAdapter extends BaseAdapter { private ArrayList<ImageView> arrListItem = null; private Context mContext; private String kind; LayoutInflater vi; public GalleryItemAdapter(Context c, String kind, ArrayList<ImageView> arrItem) { mContext = c; if (arrItem == null) arrItem = new ArrayList<ImageView>(); this.arrListItem = arrItem; this.kind = kind; vi = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE); } public int getCount() { return arrListItem.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView iv; if (convertView == null) { // iv = new ImageView(mContext); iv = arrListItem.get(position); Gallery.LayoutParams params = new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); iv.setAdjustViewBounds(true); iv.setScaleType(ScaleType.FIT_XY); iv.setLayoutParams(params); } else { iv = (ImageView) convertView; } return iv; } }
UTF-8
Java
1,576
GalleryItemAdapter.java.svn-base
Java
[]
null
[]
package com.Library.ToolsClass; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; public class GalleryItemAdapter extends BaseAdapter { private ArrayList<ImageView> arrListItem = null; private Context mContext; private String kind; LayoutInflater vi; public GalleryItemAdapter(Context c, String kind, ArrayList<ImageView> arrItem) { mContext = c; if (arrItem == null) arrItem = new ArrayList<ImageView>(); this.arrListItem = arrItem; this.kind = kind; vi = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE); } public int getCount() { return arrListItem.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView iv; if (convertView == null) { // iv = new ImageView(mContext); iv = arrListItem.get(position); Gallery.LayoutParams params = new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); iv.setAdjustViewBounds(true); iv.setScaleType(ScaleType.FIT_XY); iv.setLayoutParams(params); } else { iv = (ImageView) convertView; } return iv; } }
1,576
0.718909
0.718909
67
21.552238
22.560225
112
false
false
0
0
0
0
0
0
1.671642
false
false
5
5e59fc7b3858b8abe20adb671dfdd024ac3f5dc5
3,582,002,726,469
51fba76ece27d127da6fc9caea6365b75f86e5a5
/src/mypackage/Lesson25.java
d99b09bebc6dd4f482e888f06cff25993ed6f905
[]
no_license
AlexZhuravlev/javatest
https://github.com/AlexZhuravlev/javatest
359a442efe7f48c93f9a92c6a4572758596c84d6
b3292ea61e7466e15ae1f85691abf8841e2ffafd
refs/heads/master
2021-02-10T01:00:56.549000
2020-03-03T14:34:36
2020-03-03T14:34:36
244,340,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mypackage; import javax.swing.plaf.metal.MetalTabbedPaneUI; public class Lesson25 { public static void main(String[] args) { Lesson25car car1 = new Lesson25car(); car1.color = "Black"; car1.length = 5000; car1.height = 2000; car1.width = 2000; car1.addWeight(50); car1.drive(120); System.out.println("Add some weight!"); car1.addWeight(700); car1.drive(100); Lesson25car car2 = new Lesson25car(); car2.color = "White"; Lesson25car car3 = new Lesson25car(); car3.color = "Red"; car2.drive(100); car3.drive(150); System.out.println(car2.color); //Lesson26, конструктор класса Lesson25car car4 = new Lesson25car("redda"); System.out.println(car4.color); Lesson25car car5 = new Lesson25car("Blue"); System.out.println(car5.color); Lesson25car car6 = new Lesson25car(12,"blue",33, 44); System.out.println(car6.length); System.out.println(car6.color); System.out.println(car6.height); System.out.println(car6.width); //OR System.out.println(car6.length + " " + car6.color + " " + car6.height + " " + car6.width); // Lesson 27 модификаторы досутпа, Static & Final. System.out.println(Lesson25car.asd); System.out.println(car2.asd); Lesson25car.asd = 10; System.out.println(car2.asd); Lesson25car.method(); System.out.println(Lesson25car.fin); } }
UTF-8
Java
1,611
java
Lesson25.java
Java
[ { "context": "асса\n\n Lesson25car car4 = new Lesson25car(\"redda\");\n System.out.println(car4.color);\n\n ", "end": 793, "score": 0.9708016514778137, "start": 788, "tag": "NAME", "value": "redda" } ]
null
[]
package mypackage; import javax.swing.plaf.metal.MetalTabbedPaneUI; public class Lesson25 { public static void main(String[] args) { Lesson25car car1 = new Lesson25car(); car1.color = "Black"; car1.length = 5000; car1.height = 2000; car1.width = 2000; car1.addWeight(50); car1.drive(120); System.out.println("Add some weight!"); car1.addWeight(700); car1.drive(100); Lesson25car car2 = new Lesson25car(); car2.color = "White"; Lesson25car car3 = new Lesson25car(); car3.color = "Red"; car2.drive(100); car3.drive(150); System.out.println(car2.color); //Lesson26, конструктор класса Lesson25car car4 = new Lesson25car("redda"); System.out.println(car4.color); Lesson25car car5 = new Lesson25car("Blue"); System.out.println(car5.color); Lesson25car car6 = new Lesson25car(12,"blue",33, 44); System.out.println(car6.length); System.out.println(car6.color); System.out.println(car6.height); System.out.println(car6.width); //OR System.out.println(car6.length + " " + car6.color + " " + car6.height + " " + car6.width); // Lesson 27 модификаторы досутпа, Static & Final. System.out.println(Lesson25car.asd); System.out.println(car2.asd); Lesson25car.asd = 10; System.out.println(car2.asd); Lesson25car.method(); System.out.println(Lesson25car.fin); } }
1,611
0.586667
0.519365
73
20.575342
21.43478
98
false
false
0
0
0
0
0
0
0.547945
false
false
5
2bea00f37a90723f81a7eb22112418bdb6d5e0d2
32,530,082,329,049
92a68dfb3f48c2c32ee8bf38f244a87d778422d9
/src/main/java/com/simpastudio/loading/lines/service/MessageService.java
002662008d0697cb09d42212883e0f46563a65eb
[]
no_license
aarsla/loading-lines
https://github.com/aarsla/loading-lines
67e537dba57b9c0917e5753a31f1702ddaee4f55
3139655cde4d4d6c5a4f6ebea1eb34a7f390373f
refs/heads/master
2020-03-07T06:13:18.453000
2018-04-07T18:27:53
2018-04-07T18:27:53
127,316,046
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.simpastudio.loading.lines.service; import com.simpastudio.loading.lines.data.model.Message; import java.util.List; public interface MessageService { Message getMessage(); List<Message> getMessages(int limit); Message getShortMessage(); List<Message> getShortMessages(int limit); Message getSimCityMessage(); List<Message> getSimCityMessages(int limit); String getAdjective(); String getVerb(); String getNoun(); }
UTF-8
Java
468
java
MessageService.java
Java
[]
null
[]
package com.simpastudio.loading.lines.service; import com.simpastudio.loading.lines.data.model.Message; import java.util.List; public interface MessageService { Message getMessage(); List<Message> getMessages(int limit); Message getShortMessage(); List<Message> getShortMessages(int limit); Message getSimCityMessage(); List<Message> getSimCityMessages(int limit); String getAdjective(); String getVerb(); String getNoun(); }
468
0.735043
0.735043
20
22.4
18.706684
56
false
false
0
0
0
0
0
0
0.6
false
false
5
8f4d4cec84525a2c75d4dcf46b8cf021f570d8b0
9,560,597,235,272
e881698bfb58fb49e86284d852a2fd3b39438cf8
/code/core/src/test/java/ikube/scheduling/schedule/IndexSizeScheduleTest.java
6ad41abed317859990a013f336f0aaaff264a609
[ "Apache-2.0" ]
permissive
Pro-100Evhen/ikube
https://github.com/Pro-100Evhen/ikube
928c2bb520fec63f3836daec0006d91b515afac9
5b255116604284ec6349e10468e4ca5e634db3e9
refs/heads/master
2023-04-13T00:40:36.786000
2018-10-19T17:03:51
2018-10-19T17:03:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ikube.scheduling.schedule; import ikube.AbstractTest; import ikube.IConstants; import ikube.mock.ApplicationContextManagerMock; import ikube.model.IndexContext; import ikube.model.Snapshot; import ikube.toolkit.FILE; import mockit.Deencapsulation; import mockit.Mockit; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; /** * @author Michael Couck * @version 01.00 * @since 29-08-2012 */ public class IndexSizeScheduleTest extends AbstractTest { /** * Class under test. */ private IndexSizeSchedule indexSizeSchedule; @Before public void before() { indexSizeSchedule = new IndexSizeSchedule(); Mockit.setUpMocks(ApplicationContextManagerMock.class); ApplicationContextManagerMock.setBean(IndexContext.class, indexContext); Snapshot snapshot = mock(Snapshot.class); when(snapshot.getIndexSize()).thenReturn(Long.MAX_VALUE); when(indexContext.getSnapshot()).thenReturn(snapshot); when(indexContext.getIndexWriters()).thenReturn(new IndexWriter[]{indexWriter}); File indexDirectory = FILE.getFile(indexDirectoryPath + IConstants.SEP + "127.0.0.1.8000", Boolean.TRUE); when(fsDirectory.getDirectory()).thenReturn(indexDirectory); Deencapsulation.setField(indexSizeSchedule, monitorService); FILE.deleteFile(new File(indexContext.getIndexDirectoryPath()), 1); } @After public void after() { Mockit.tearDownMocks(ApplicationContextManagerMock.class); FILE.deleteFile(new File(indexContext.getIndexDirectoryPath()), 1); } @Test public void handleNotification() throws CorruptIndexException, IOException { indexSizeSchedule.run(); // We never call this because the mock doesn't really get the new index writer // so the logic never calls the close on the index writer verify(indexWriter, never()).close(Boolean.TRUE); IndexWriter[] indexWriters = indexContext.getIndexWriters(); logger.info("Index writers : " + indexWriters.length); assertTrue(indexWriters.length == 1); indexSizeSchedule.run(); indexWriters = indexContext.getIndexWriters(); logger.info("Index writers : " + indexWriters.length); assertTrue(indexWriters.length == 1); // TODO Write tests for the fail over } }
UTF-8
Java
2,599
java
IndexSizeScheduleTest.java
Java
[ { "context": "port static org.mockito.Mockito.*;\n\n/**\n * @author Michael Couck\n * @version 01.00\n * @since 29-08-2012\n */\npublic", "end": 609, "score": 0.9996572732925415, "start": 596, "tag": "NAME", "value": "Michael Couck" } ]
null
[]
package ikube.scheduling.schedule; import ikube.AbstractTest; import ikube.IConstants; import ikube.mock.ApplicationContextManagerMock; import ikube.model.IndexContext; import ikube.model.Snapshot; import ikube.toolkit.FILE; import mockit.Deencapsulation; import mockit.Mockit; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; /** * @author <NAME> * @version 01.00 * @since 29-08-2012 */ public class IndexSizeScheduleTest extends AbstractTest { /** * Class under test. */ private IndexSizeSchedule indexSizeSchedule; @Before public void before() { indexSizeSchedule = new IndexSizeSchedule(); Mockit.setUpMocks(ApplicationContextManagerMock.class); ApplicationContextManagerMock.setBean(IndexContext.class, indexContext); Snapshot snapshot = mock(Snapshot.class); when(snapshot.getIndexSize()).thenReturn(Long.MAX_VALUE); when(indexContext.getSnapshot()).thenReturn(snapshot); when(indexContext.getIndexWriters()).thenReturn(new IndexWriter[]{indexWriter}); File indexDirectory = FILE.getFile(indexDirectoryPath + IConstants.SEP + "127.0.0.1.8000", Boolean.TRUE); when(fsDirectory.getDirectory()).thenReturn(indexDirectory); Deencapsulation.setField(indexSizeSchedule, monitorService); FILE.deleteFile(new File(indexContext.getIndexDirectoryPath()), 1); } @After public void after() { Mockit.tearDownMocks(ApplicationContextManagerMock.class); FILE.deleteFile(new File(indexContext.getIndexDirectoryPath()), 1); } @Test public void handleNotification() throws CorruptIndexException, IOException { indexSizeSchedule.run(); // We never call this because the mock doesn't really get the new index writer // so the logic never calls the close on the index writer verify(indexWriter, never()).close(Boolean.TRUE); IndexWriter[] indexWriters = indexContext.getIndexWriters(); logger.info("Index writers : " + indexWriters.length); assertTrue(indexWriters.length == 1); indexSizeSchedule.run(); indexWriters = indexContext.getIndexWriters(); logger.info("Index writers : " + indexWriters.length); assertTrue(indexWriters.length == 1); // TODO Write tests for the fail over } }
2,592
0.719892
0.709888
77
32.766235
27.686508
113
false
false
0
0
0
0
0
0
0.623377
false
false
5
49b26c41412ec36533cf93357312bc23432964d5
9,560,597,234,018
f6eabc046674ce2819c12aa8d41669e32b37b6ab
/src/main/java/com/wemp/controller/PathController.java
bc778e66d9ec25fd8b78f2e8428d0f82460e1e30
[]
no_license
muneebunnabi7/FinalProject
https://github.com/muneebunnabi7/FinalProject
e4d8287f8e0cb0c8526aab0745674a0643cc487d
b0ff5aaee74d5b69df308148fcb5a76ada3b96f7
refs/heads/master
2020-04-09T11:03:08.963000
2018-12-04T16:14:13
2018-12-04T16:14:13
160,293,511
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wemp.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * * @author promot *This controller maps different jsp pages */ @Controller public class PathController { @RequestMapping("contact") public ModelAndView stepcontact() { return new ModelAndView("Contact"); } @RequestMapping("hstep") public ModelAndView stepHome() { return new ModelAndView("HomeStep"); } @RequestMapping("StepReg") public ModelAndView stepForm() { return new ModelAndView("traineeform"); } @RequestMapping("/forget") public ModelAndView forgetPass() { return new ModelAndView("forgetpassword"); } @RequestMapping("/hadmin") public ModelAndView adminHome() { return new ModelAndView("HomeAdmin"); } @RequestMapping("/applicant") public ModelAndView adminLogin() { return new ModelAndView("AdminLogin"); } @RequestMapping("/statuscheckup") public ModelAndView konwStatus() { return new ModelAndView("traineelogin"); } @RequestMapping("/habout") public ModelAndView konwAbout() { return new ModelAndView("HomeAbout"); } @RequestMapping("/hleg") public ModelAndView konwLeg() { return new ModelAndView("HomeLeg"); } @RequestMapping("/StepStatus") public ModelAndView userStatus() { return new ModelAndView("traineelogin"); } @RequestMapping("applicants") public ModelAndView userList() { return new ModelAndView("viewapplicant"); } }
UTF-8
Java
1,731
java
PathController.java
Java
[ { "context": "rk.web.servlet.ModelAndView;\r\n/**\r\n * \r\n * @author promot\r\n *This controller maps different jsp pages\r\n */\r", "end": 228, "score": 0.9996128678321838, "start": 222, "tag": "USERNAME", "value": "promot" } ]
null
[]
package com.wemp.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * * @author promot *This controller maps different jsp pages */ @Controller public class PathController { @RequestMapping("contact") public ModelAndView stepcontact() { return new ModelAndView("Contact"); } @RequestMapping("hstep") public ModelAndView stepHome() { return new ModelAndView("HomeStep"); } @RequestMapping("StepReg") public ModelAndView stepForm() { return new ModelAndView("traineeform"); } @RequestMapping("/forget") public ModelAndView forgetPass() { return new ModelAndView("forgetpassword"); } @RequestMapping("/hadmin") public ModelAndView adminHome() { return new ModelAndView("HomeAdmin"); } @RequestMapping("/applicant") public ModelAndView adminLogin() { return new ModelAndView("AdminLogin"); } @RequestMapping("/statuscheckup") public ModelAndView konwStatus() { return new ModelAndView("traineelogin"); } @RequestMapping("/habout") public ModelAndView konwAbout() { return new ModelAndView("HomeAbout"); } @RequestMapping("/hleg") public ModelAndView konwLeg() { return new ModelAndView("HomeLeg"); } @RequestMapping("/StepStatus") public ModelAndView userStatus() { return new ModelAndView("traineelogin"); } @RequestMapping("applicants") public ModelAndView userList() { return new ModelAndView("viewapplicant"); } }
1,731
0.652224
0.652224
72
22.041666
17.222754
62
false
false
0
0
0
0
0
0
0.555556
false
false
5
b75c372ac35063f83bcf515dd20f22deecf6ecdc
2,516,850,843,840
4807b8aeac8e583b71a14cab55e70325dcc41689
/src/AccountManagementGUI/CreatAccountChooseIdentityPanel.java
4fd1531c0293d21243d311dcf6a7e2b0b322759a
[]
no_license
tanyuqing100/proj_2013_ams
https://github.com/tanyuqing100/proj_2013_ams
cf7eacafa65d7e76d00e00ce55b3fd1671ec2cd4
f36eb50695cc0f992450285d797600c9f490cf66
refs/heads/master
2021-01-18T10:19:04.249000
2016-09-18T19:00:32
2016-09-18T19:00:32
68,537,473
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package AccountManagementGUI; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JComboBox; import MainMenuGUI.MenuButton; public class CreatAccountChooseIdentityPanel extends JPanel{ @SuppressWarnings("rawtypes") private JComboBox boxIdentity; private int permission; @SuppressWarnings({ "unchecked", "rawtypes" }) public CreatAccountChooseIdentityPanel(){ MenuButton buttons = null; setLayout(new FlowLayout(FlowLayout.CENTER)); add(Box.createVerticalGlue()); JLabel prompt = new JLabel("Identity For New Account:"); add(prompt); String[] level = {"manager","staff","tenant"}; boxIdentity = new JComboBox(level); boxIdentity.setMaximumSize(boxIdentity.getPreferredSize()); add(boxIdentity); buttons = new MenuButton("Create Account",120); buttons.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent evt){ if( boxIdentity.getSelectedItem() == "manager"){ permission = 0; CreateNewAccountForStaffPanel panel = new CreateNewAccountForStaffPanel(permission); AccountManagementMainPanel.pnl4.removeAll(); AccountManagementMainPanel.pnl4.add(panel); AccountManagementMainPanel.pnl4.validate(); AccountManagementMainPanel.pnl4.repaint(); }else if(boxIdentity.getSelectedItem() == "staff"){ permission = 1; CreateNewAccountForStaffPanel panel = new CreateNewAccountForStaffPanel(permission); AccountManagementMainPanel.pnl4.removeAll(); AccountManagementMainPanel.pnl4.add(panel); AccountManagementMainPanel.pnl4.validate(); AccountManagementMainPanel.pnl4.repaint(); } else { permission = 2; CreateNewAccountForTenantfPanel panel = new CreateNewAccountForTenantfPanel(permission); AccountManagementMainPanel.pnl4.removeAll(); AccountManagementMainPanel.pnl4.add(panel); AccountManagementMainPanel.pnl4.validate(); AccountManagementMainPanel.pnl4.repaint(); } } }); buttons.setMaximumSize(new Dimension(150,30)); buttons.setAlignmentX(Component.CENTER_ALIGNMENT); add(buttons); } public static final long serialVersionUID = 1; }
UTF-8
Java
2,429
java
CreatAccountChooseIdentityPanel.java
Java
[]
null
[]
package AccountManagementGUI; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JComboBox; import MainMenuGUI.MenuButton; public class CreatAccountChooseIdentityPanel extends JPanel{ @SuppressWarnings("rawtypes") private JComboBox boxIdentity; private int permission; @SuppressWarnings({ "unchecked", "rawtypes" }) public CreatAccountChooseIdentityPanel(){ MenuButton buttons = null; setLayout(new FlowLayout(FlowLayout.CENTER)); add(Box.createVerticalGlue()); JLabel prompt = new JLabel("Identity For New Account:"); add(prompt); String[] level = {"manager","staff","tenant"}; boxIdentity = new JComboBox(level); boxIdentity.setMaximumSize(boxIdentity.getPreferredSize()); add(boxIdentity); buttons = new MenuButton("Create Account",120); buttons.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent evt){ if( boxIdentity.getSelectedItem() == "manager"){ permission = 0; CreateNewAccountForStaffPanel panel = new CreateNewAccountForStaffPanel(permission); AccountManagementMainPanel.pnl4.removeAll(); AccountManagementMainPanel.pnl4.add(panel); AccountManagementMainPanel.pnl4.validate(); AccountManagementMainPanel.pnl4.repaint(); }else if(boxIdentity.getSelectedItem() == "staff"){ permission = 1; CreateNewAccountForStaffPanel panel = new CreateNewAccountForStaffPanel(permission); AccountManagementMainPanel.pnl4.removeAll(); AccountManagementMainPanel.pnl4.add(panel); AccountManagementMainPanel.pnl4.validate(); AccountManagementMainPanel.pnl4.repaint(); } else { permission = 2; CreateNewAccountForTenantfPanel panel = new CreateNewAccountForTenantfPanel(permission); AccountManagementMainPanel.pnl4.removeAll(); AccountManagementMainPanel.pnl4.add(panel); AccountManagementMainPanel.pnl4.validate(); AccountManagementMainPanel.pnl4.repaint(); } } }); buttons.setMaximumSize(new Dimension(150,30)); buttons.setAlignmentX(Component.CENTER_ALIGNMENT); add(buttons); } public static final long serialVersionUID = 1; }
2,429
0.722931
0.713051
82
27.621952
23.618223
93
false
false
0
0
0
0
0
0
2.609756
false
false
5
644af002a8846d22c6b98173c75f693f4b34ee0d
28,690,381,550,994
3719ce60d99ef540600bb475eb303e21f2d5b7b9
/core-base/src/main/java/org/fairy/Fairy.java
f812e78d56199b0815ee8e023d31ccd3fcd28c7d
[ "MIT" ]
permissive
CyberFlameGO/fairy
https://github.com/CyberFlameGO/fairy
3704ea6ef2359c53e147b97427b0ff7634011d65
a86b4011a3f11e3bb4e7d8bf3ab8a3ad6ffadd03
refs/heads/master
2023-08-12T20:06:38.456000
2021-09-01T10:38:39
2021-09-01T10:38:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * MIT License * * Copyright (c) 2021 Imanity * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.fairy; import lombok.experimental.UtilityClass; import org.fairy.config.BaseConfiguration; import org.fairy.library.LibraryHandler; import org.fairy.task.ITaskScheduler; import org.fairy.util.FastRandom; /** * Static extension of FairyBootstrap */ @UtilityClass public class Fairy { public final String METADATA_PREFIX = "Imanity_"; private final FastRandom RANDOM = new FastRandom(); public FastRandom random() { return RANDOM; } public boolean isRunning() { return FairyBootstrap.INSTANCE.getPlatform().isRunning(); } public ITaskScheduler getTaskScheduler() { return FairyBootstrap.INSTANCE.getTaskScheduler(); } public LibraryHandler getLibraryHandler() { return FairyBootstrap.INSTANCE.getLibraryHandler(); } public FairyPlatform getPlatform() { return FairyBootstrap.INSTANCE.getPlatform(); } public BaseConfiguration getBaseConfiguration() { return FairyBootstrap.INSTANCE.getBaseConfiguration(); } }
UTF-8
Java
2,167
java
Fairy.java
Java
[ { "context": "/*\n * MIT License\n *\n * Copyright (c) 2021 Imanity\n *\n * Permission is hereby granted, free of charg", "end": 50, "score": 0.8330262303352356, "start": 43, "tag": "USERNAME", "value": "Imanity" } ]
null
[]
/* * MIT License * * Copyright (c) 2021 Imanity * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.fairy; import lombok.experimental.UtilityClass; import org.fairy.config.BaseConfiguration; import org.fairy.library.LibraryHandler; import org.fairy.task.ITaskScheduler; import org.fairy.util.FastRandom; /** * Static extension of FairyBootstrap */ @UtilityClass public class Fairy { public final String METADATA_PREFIX = "Imanity_"; private final FastRandom RANDOM = new FastRandom(); public FastRandom random() { return RANDOM; } public boolean isRunning() { return FairyBootstrap.INSTANCE.getPlatform().isRunning(); } public ITaskScheduler getTaskScheduler() { return FairyBootstrap.INSTANCE.getTaskScheduler(); } public LibraryHandler getLibraryHandler() { return FairyBootstrap.INSTANCE.getLibraryHandler(); } public FairyPlatform getPlatform() { return FairyBootstrap.INSTANCE.getPlatform(); } public BaseConfiguration getBaseConfiguration() { return FairyBootstrap.INSTANCE.getBaseConfiguration(); } }
2,167
0.740194
0.738348
66
31.833334
29.427664
81
false
false
0
0
0
0
0
0
0.545455
false
false
5
31244e4d876b342fafe169e87992b96eeed4a9ff
28,690,381,550,078
021f30e9e9acdbaa8a45e8c087f960698c6c1ff4
/app/src/main/java/com/personal/coine/scorpion/jxnuhelper/view/fragment/NewsListFragment.java
0078a01f3498baf68a90a26ebc315fde9ff70424
[]
no_license
RyanTech/JxnuHelper
https://github.com/RyanTech/JxnuHelper
18338433fb9b8c5e3720f17343751f272079fab8
ed89b2ba3fbaefa1055f65f2f554f9c917f668ec
refs/heads/master
2017-12-03T01:55:46.230000
2016-03-17T11:02:30
2016-03-17T11:02:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright(c) Runsdata Technologies Co., Ltd. * All Rights Reserved. * * This software is the confidential and proprietary information of Runsdata * Technologies Co., Ltd. ("Confidential Information"). You shall not disclose * such Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with Runsdata. * For more information about Runsdata, welcome to http://www.runsdata.com * * Revision History * Date Version Name Description * 2016/3/7 1.0 huangwei Creation File */ package com.personal.coine.scorpion.jxnuhelper.view.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.kaopiz.kprogresshud.KProgressHUD; import com.personal.coine.scorpion.jxnuhelper.R; import com.personal.coine.scorpion.jxnuhelper.presenter.NewsPresenter; import com.personal.coine.scorpion.jxnuhelper.view.INewsView; import com.personal.coine.scorpion.jxnuhelper.view.activity.NewsDetailActivity; import com.personal.coine.scorpion.jxnuhelper.view.refreshview.HitBlockRefreshView; /** * Description: * * @author huangwei * Date 2016/3/7 */ public class NewsListFragment extends Fragment implements INewsView { private HitBlockRefreshView refreshView; private NewsPresenter newsPresenter = new NewsPresenter(this); private ListView newsList; private KProgressHUD loadingProgress; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_school_news, null); initViews(view); return view; } private void initViews(View view) { loadingProgress = KProgressHUD.create(getContext()).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setLabel("正在加载数据...").setCancellable(false).setAnimationSpeed(2).setDimAmount(0.5f); refreshView = (HitBlockRefreshView) view.findViewById(R.id.refresh_hit_block); newsList = (ListView) view.findViewById(R.id.news_list); newsPresenter.requestNewsData(); refreshView.setOnRefreshListener(new HitBlockRefreshView.HitBlockRefreshListener() { @Override public void onRefreshing() { newsPresenter.requestNewsData(); } }); newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { newsPresenter.goDetail(); } }); } @Override public HitBlockRefreshView getRefreshView() { return refreshView; } @Override public ListView getListView() { return newsList; } @Override public void showLoading() { loadingProgress.show(); } @Override public void hideLoading() { loadingProgress.dismiss(); } @Override public Context getFragmentContext() { return getContext(); } }
UTF-8
Java
3,460
java
NewsListFragment.java
Java
[ { "context": " Name Description\r\n * 2016/3/7 1.0 huangwei Creation File\r\n */\r\npackage com.personal.coine", "end": 565, "score": 0.9991896152496338, "start": 557, "tag": "USERNAME", "value": "huangwei" }, { "context": "freshView;\r\n\r\n/**\r\n * Description:\r\n *\r\n * @author huangwei\r\n * Date 2016/3/7\r\n */\r\npublic class News", "end": 1443, "score": 0.9996766448020935, "start": 1435, "tag": "USERNAME", "value": "huangwei" } ]
null
[]
/* * Copyright(c) Runsdata Technologies Co., Ltd. * All Rights Reserved. * * This software is the confidential and proprietary information of Runsdata * Technologies Co., Ltd. ("Confidential Information"). You shall not disclose * such Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with Runsdata. * For more information about Runsdata, welcome to http://www.runsdata.com * * Revision History * Date Version Name Description * 2016/3/7 1.0 huangwei Creation File */ package com.personal.coine.scorpion.jxnuhelper.view.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.kaopiz.kprogresshud.KProgressHUD; import com.personal.coine.scorpion.jxnuhelper.R; import com.personal.coine.scorpion.jxnuhelper.presenter.NewsPresenter; import com.personal.coine.scorpion.jxnuhelper.view.INewsView; import com.personal.coine.scorpion.jxnuhelper.view.activity.NewsDetailActivity; import com.personal.coine.scorpion.jxnuhelper.view.refreshview.HitBlockRefreshView; /** * Description: * * @author huangwei * Date 2016/3/7 */ public class NewsListFragment extends Fragment implements INewsView { private HitBlockRefreshView refreshView; private NewsPresenter newsPresenter = new NewsPresenter(this); private ListView newsList; private KProgressHUD loadingProgress; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_school_news, null); initViews(view); return view; } private void initViews(View view) { loadingProgress = KProgressHUD.create(getContext()).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setLabel("正在加载数据...").setCancellable(false).setAnimationSpeed(2).setDimAmount(0.5f); refreshView = (HitBlockRefreshView) view.findViewById(R.id.refresh_hit_block); newsList = (ListView) view.findViewById(R.id.news_list); newsPresenter.requestNewsData(); refreshView.setOnRefreshListener(new HitBlockRefreshView.HitBlockRefreshListener() { @Override public void onRefreshing() { newsPresenter.requestNewsData(); } }); newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { newsPresenter.goDetail(); } }); } @Override public HitBlockRefreshView getRefreshView() { return refreshView; } @Override public ListView getListView() { return newsList; } @Override public void showLoading() { loadingProgress.show(); } @Override public void hideLoading() { loadingProgress.dismiss(); } @Override public Context getFragmentContext() { return getContext(); } }
3,460
0.694026
0.688805
100
32.5
31.78097
192
false
false
0
0
0
0
0
0
0.46
false
false
5
5eb29b798f908a553279d6749f156ca6e28cfb23
10,651,518,909,485
2a5c01feb2c618fa32ac63341b7f155cb8d8809e
/src/feature8/OrdenarColecao.java
58e1e4d9ed7f0a03c7d2edb07678bfa909b5d63f
[]
no_license
PatriciaLocatelli/features-java
https://github.com/PatriciaLocatelli/features-java
37177b76560170b674bb9222272b14c51808f038
00dc7eef2963293967b5bec305ed4d7103cd43c9
refs/heads/master
2021-01-02T05:08:30.397000
2020-02-10T15:30:22
2020-02-10T15:30:22
239,502,227
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package feature8; import java.util.Arrays; import java.util.Collections; import java.util.List; public class OrdenarColecao { public static void main(String[] args) { List<String> lista = Arrays.asList("Patricia", "Jéssica", "Roger", "Gabriel", "Thiago"); Collections.sort(lista); System.out.println(lista); } }
UTF-8
Java
350
java
OrdenarColecao.java
Java
[ { "context": "s) {\n\n List<String> lista = Arrays.asList(\"Patricia\", \"Jéssica\", \"Roger\", \"Gabriel\", \"Thiago\");\n\n ", "end": 226, "score": 0.9998236298561096, "start": 218, "tag": "NAME", "value": "Patricia" }, { "context": " List<String> lista = Arrays.asList(\"Patricia\", \"Jéssica\", \"Roger\", \"Gabriel\", \"Thiago\");\n\n Collect", "end": 237, "score": 0.9998058676719666, "start": 230, "tag": "NAME", "value": "Jéssica" }, { "context": "ng> lista = Arrays.asList(\"Patricia\", \"Jéssica\", \"Roger\", \"Gabriel\", \"Thiago\");\n\n Collections.sort", "end": 246, "score": 0.9998124241828918, "start": 241, "tag": "NAME", "value": "Roger" }, { "context": " = Arrays.asList(\"Patricia\", \"Jéssica\", \"Roger\", \"Gabriel\", \"Thiago\");\n\n Collections.sort(lista);\n ", "end": 257, "score": 0.9998047947883606, "start": 250, "tag": "NAME", "value": "Gabriel" }, { "context": "sList(\"Patricia\", \"Jéssica\", \"Roger\", \"Gabriel\", \"Thiago\");\n\n Collections.sort(lista);\n Syst", "end": 267, "score": 0.9997990727424622, "start": 261, "tag": "NAME", "value": "Thiago" } ]
null
[]
package feature8; import java.util.Arrays; import java.util.Collections; import java.util.List; public class OrdenarColecao { public static void main(String[] args) { List<String> lista = Arrays.asList("Patricia", "Jéssica", "Roger", "Gabriel", "Thiago"); Collections.sort(lista); System.out.println(lista); } }
350
0.670487
0.667622
16
20.8125
24.313625
96
false
false
0
0
0
0
0
0
0.6875
false
false
5
5d9857eef2fa926bbdcb09277a237d0bfd7e2385
429,496,778,974
6bdd970a53a20b882fff055fbade2a532f5e43e0
/status-models/src/main/java/com/telecominfraproject/wlan/status/models/StatusDetails.java
048522551c72140fed0440872a769a78b4284ac1
[]
no_license
eugenetaranov-opsfleet/wlan-cloud-services
https://github.com/eugenetaranov-opsfleet/wlan-cloud-services
826a333d0aa517f2f23e605638ec6df12d91a4b4
3410672fd978374ee74902ee6396955054b6728a
refs/heads/master
2022-11-16T00:44:40.672000
2020-07-01T12:11:45
2020-07-01T12:11:45
276,321,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.telecominfraproject.wlan.status.models; import com.telecominfraproject.wlan.core.model.json.BaseJsonModel; /** * @author dtoptygin * */ public abstract class StatusDetails extends BaseJsonModel { private static final long serialVersionUID = 5570757656953699233L; @Override public boolean hasUnsupportedValue() { if (super.hasUnsupportedValue()) { return true; } return false; } @Override public StatusDetails clone() { return (StatusDetails) super.clone(); } public abstract StatusDataType getStatusDataType(); }
UTF-8
Java
582
java
StatusDetails.java
Java
[ { "context": "lan.core.model.json.BaseJsonModel;\n\n/**\n * @author dtoptygin\n *\n */\npublic abstract class StatusDetails extend", "end": 145, "score": 0.9996272921562195, "start": 136, "tag": "USERNAME", "value": "dtoptygin" } ]
null
[]
package com.telecominfraproject.wlan.status.models; import com.telecominfraproject.wlan.core.model.json.BaseJsonModel; /** * @author dtoptygin * */ public abstract class StatusDetails extends BaseJsonModel { private static final long serialVersionUID = 5570757656953699233L; @Override public boolean hasUnsupportedValue() { if (super.hasUnsupportedValue()) { return true; } return false; } @Override public StatusDetails clone() { return (StatusDetails) super.clone(); } public abstract StatusDataType getStatusDataType(); }
582
0.723368
0.690722
28
19.785715
22.521984
67
false
false
0
0
0
0
0
0
0.785714
false
false
5
4ac17c92d2f149e7c9ed98be499b144b469f2c4d
34,016,140,990,467
97703dd9f803c2a04f2770538d27965fe249dffc
/practica2/src/clasebocina/bocina.java
2fcc10887f7b6dd418b3080e0534d5f3f67a76a7
[]
no_license
Antonio22Rene/proyectoFinal
https://github.com/Antonio22Rene/proyectoFinal
5d8288a2663b285e935c7387a9caae75327e7827
d6ee9f3bc84a4136b91139d43e1581d5f8aa06a1
refs/heads/master
2022-11-08T21:51:32.571000
2020-06-19T23:20:49
2020-06-19T23:20:49
273,591,134
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package clasebocina; public class bocina { private String bluetooh; private int peso; private String color; private String tamaņo; private String marca; public bocina() { } public bocina(String color2, String tamaņo2, String marca2) { // TODO Auto-generated constructor stub } public String getBluetooh() { return this.bluetooh; } public void setBluetooh(String b) { this.bluetooh="conectado"; } public int getPeso() { return this.peso; } public void setPeso(int p) { this.peso=5; } public String getColor() { return this.color; } public void setColor(String c) { this.color="negra"; } public String getTamaņo() { return this.tamaņo; } public void setTamaņo(String t) { this.tamaņo="grande"; } public String getMarac() { return this.marca; } public void setMarca(String m) { this.marca="LG"; } }
ISO-8859-10
Java
874
java
bocina.java
Java
[]
null
[]
package clasebocina; public class bocina { private String bluetooh; private int peso; private String color; private String tamaņo; private String marca; public bocina() { } public bocina(String color2, String tamaņo2, String marca2) { // TODO Auto-generated constructor stub } public String getBluetooh() { return this.bluetooh; } public void setBluetooh(String b) { this.bluetooh="conectado"; } public int getPeso() { return this.peso; } public void setPeso(int p) { this.peso=5; } public String getColor() { return this.color; } public void setColor(String c) { this.color="negra"; } public String getTamaņo() { return this.tamaņo; } public void setTamaņo(String t) { this.tamaņo="grande"; } public String getMarac() { return this.marca; } public void setMarca(String m) { this.marca="LG"; } }
874
0.682028
0.677419
61
13.229508
13.305236
62
false
false
0
0
0
0
0
0
1.377049
false
false
5
c248efa20282ae7b74976737562ee5bf527d80a9
32,865,089,818,163
dbfa3a392483c010d9c04ec539f180b3f06fc75f
/DataStructures/src/com/srikar/ds/binarytree/BinaryTree.java
b5d98b7e1752f91e3c710c06cccbb7e804304062
[]
no_license
srikarrao/ds-and-algorithms
https://github.com/srikarrao/ds-and-algorithms
f679a729b4684ec9da247e4f420378a4ab0fc6f3
22fce225a3b092c9b683de4863c5113ce2923c90
refs/heads/master
2021-01-18T23:36:56.489000
2020-03-14T01:35:33
2020-03-14T01:35:33
72,712,567
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.srikar.ds.binarytree; /** * Snippet for Binary Tree remove method * * @author SrikarRao * */ public class BinaryTree { public Node root; private static class Node { Node left; Node right; int data; Node(Node left, Node right, int data) { this.left = left; this.right = right; this.data = data; } } private void deleteNode() { deleteNode(root); } /** * Method to delete the node from a binary tree * * @throws IllegalArgumentException * @param node */ private void deleteNode(Node node) { if (node == null) { throw new IllegalArgumentException("Tree is empty!!"); } while (node.left != null || node.right != null) { if (node.right != null) { node = node.right; } else { node = node.left; } } node = null; } }
UTF-8
Java
805
java
BinaryTree.java
Java
[ { "context": "ippet for Binary Tree remove method\n * \n * @author SrikarRao\n *\n */\n\npublic class BinaryTree {\n\n\tpublic Node r", "end": 104, "score": 0.9998623728752136, "start": 95, "tag": "NAME", "value": "SrikarRao" } ]
null
[]
package com.srikar.ds.binarytree; /** * Snippet for Binary Tree remove method * * @author SrikarRao * */ public class BinaryTree { public Node root; private static class Node { Node left; Node right; int data; Node(Node left, Node right, int data) { this.left = left; this.right = right; this.data = data; } } private void deleteNode() { deleteNode(root); } /** * Method to delete the node from a binary tree * * @throws IllegalArgumentException * @param node */ private void deleteNode(Node node) { if (node == null) { throw new IllegalArgumentException("Tree is empty!!"); } while (node.left != null || node.right != null) { if (node.right != null) { node = node.right; } else { node = node.left; } } node = null; } }
805
0.616149
0.616149
51
14.784314
15.252533
57
false
false
0
0
0
0
0
0
1.588235
false
false
5
b983b991bf8e620d43d3051e15e68d0e6f059088
32,865,089,818,009
7bebbc9ac28e7dbac24385cd105105621247308c
/src/geomap/GeoMap.java
ab02a26ba4be9a65d11c99559b9b700881aa8599
[]
no_license
patomems/GeoMap
https://github.com/patomems/GeoMap
1387c5aba774b11f342dd105e921c1f0d9f3fd00
b4dc1088babfd0a2da7935c76452c62d38cdecbe
refs/heads/master
2020-04-29T16:03:31.013000
2019-03-18T09:24:34
2019-03-18T09:24:34
176,246,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package geomap; /** * * @author Kim Jon Un */ import java.net.URI; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.glassfish.jersey.client.ClientConfig; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class GeoMap { public static void main(String...aa) { try { System.out.println("Finding Address...\n"); ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target = client.target(getBaseURI()); String jsonaddresss = target.request().accept(MediaType.APPLICATION_JSON).get(String.class); String address = adres(jsonaddresss); System.out.println("My Address is : >>"+address); } catch(Exception e) { System.out.println("Error"+e); } } private static URI getBaseURI() { return UriBuilder.fromUri("https://maps.googleapis.com/maps/api/geocode/json?latlng=1.28333,36.81667&key=AIzaSyC-EwAaeu1L6mJRKms91yp0kQpQZXhHJe4").build(); } private static String adres(String jsonaddresss) { try { JSONParser parser = new JSONParser(); Object obj = parser.parse(jsonaddresss); JSONObject jsonObject = (JSONObject) obj; JSONArray msg = (JSONArray) jsonObject.get("results"); //System.out.println("Message"+msg.get(1)); //Get Second Line Of Result JSONObject jobj = (JSONObject) parser.parse(msg.get(1).toString()); // Parsse it String perfect_address = jobj.get("formatted_address").toString(); jsonaddresss = perfect_address; } catch(Exception e) { jsonaddresss = "Error In Address"+e; } return jsonaddresss; } }
UTF-8
Java
2,316
java
GeoMap.java
Java
[ { "context": "itor.\r\n */\r\npackage geomap;\r\n\r\n/**\r\n *\r\n * @author Kim Jon Un\r\n */\r\n\r\nimport java.net.URI;\r\nimport javax.ws.rs.", "end": 239, "score": 0.999660074710846, "start": 229, "tag": "NAME", "value": "Kim Jon Un" }, { "context": "maps/api/geocode/json?latlng=1.28333,36.81667&key=AIzaSyC-EwAaeu1L6mJRKms91yp0kQpQZXhHJe4\").build();\r\n }\r\n private static String adre", "end": 1507, "score": 0.9996678829193115, "start": 1468, "tag": "KEY", "value": "AIzaSyC-EwAaeu1L6mJRKms91yp0kQpQZXhHJe4" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package geomap; /** * * @author <NAME> */ import java.net.URI; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.glassfish.jersey.client.ClientConfig; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class GeoMap { public static void main(String...aa) { try { System.out.println("Finding Address...\n"); ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target = client.target(getBaseURI()); String jsonaddresss = target.request().accept(MediaType.APPLICATION_JSON).get(String.class); String address = adres(jsonaddresss); System.out.println("My Address is : >>"+address); } catch(Exception e) { System.out.println("Error"+e); } } private static URI getBaseURI() { return UriBuilder.fromUri("https://maps.googleapis.com/maps/api/geocode/json?latlng=1.28333,36.81667&key=<KEY>").build(); } private static String adres(String jsonaddresss) { try { JSONParser parser = new JSONParser(); Object obj = parser.parse(jsonaddresss); JSONObject jsonObject = (JSONObject) obj; JSONArray msg = (JSONArray) jsonObject.get("results"); //System.out.println("Message"+msg.get(1)); //Get Second Line Of Result JSONObject jobj = (JSONObject) parser.parse(msg.get(1).toString()); // Parsse it String perfect_address = jobj.get("formatted_address").toString(); jsonaddresss = perfect_address; } catch(Exception e) { jsonaddresss = "Error In Address"+e; } return jsonaddresss; } }
2,278
0.607513
0.598446
79
27.341772
30.179583
163
false
false
0
0
0
0
0
0
0.43038
false
false
5
95e877f4c174b007278a4ed37fbf8cd6bc9befa0
5,720,896,465,732
6c00b357985f912a3add0d9c09fca4744696f7c5
/src/EarthText.java
a6d3f6f329e273b5e7b3d53f0ef5c85ac1182afe
[]
no_license
danielgulland/AdapterProject
https://github.com/danielgulland/AdapterProject
d877798fcc1008f4cf0719be3feb56ecb182a7a8
2bf66a3c5070c6102ad07875e4c828f616e0a21e
refs/heads/master
2021-10-24T20:02:20.621000
2019-03-28T08:47:53
2019-03-28T08:47:53
176,968,487
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* John Bui & Daniel Gulland March 27, 2019 Purpose: send texts and reads text Inputs: language, filename Outputs: n/a */ import java.util.ArrayList; import java.util.Scanner; import java.io.FileNotFoundException; public class EarthText implements EarthCellPhone { private ArrayList<String> validLanguages; /** * initializes validLanguages and adds 3 languages. */ public EarthText() { validLanguages = new ArrayList<>(); validLanguages.add("Earth"); validLanguages.add("Klingon"); validLanguages.add("Vulcan"); } /** * Sends a message in the respective language. * * @param languageType the language that it's going to be translated to * @param fileName the file to be read from * @throws InvalidLanguageException */ @Override public void sendMessage(String languageType, String fileName) throws InvalidLanguageException { if (validLanguages.contains(languageType)) { try{ java.io.File f1 = new java.io.File(fileName); Scanner input = new Scanner(f1); System.out.println(languageType + " Message Sent"); } catch (FileNotFoundException fnf) { System.out.println(fileName + " doesn't exist"); } } else throw new InvalidLanguageException(languageType); } /** * reads a message from a file * * @param fileName file to be read from */ @Override public void readMessage(String fileName) { java.io.File f1 = new java.io.File(fileName); try { Scanner input = new Scanner(f1); System.out.println(input.nextLine()); input.close(); } catch (FileNotFoundException fnf) { System.out.println("File: " + fileName + " does not exist"); } } /** * string representation of an EarthText object * * @return string representation of an EarthText object */ public String toString() { return "This is an EarthText object.\n"; } }
UTF-8
Java
1,842
java
EarthText.java
Java
[ { "context": "/* John Bui & Daniel Gulland\n March 27, 2019\n Purpose: se", "end": 11, "score": 0.9998379349708557, "start": 3, "tag": "NAME", "value": "John Bui" }, { "context": "/* John Bui & Daniel Gulland\n March 27, 2019\n Purpose: send texts and read", "end": 28, "score": 0.9998723268508911, "start": 14, "tag": "NAME", "value": "Daniel Gulland" } ]
null
[]
/* <NAME> & <NAME> March 27, 2019 Purpose: send texts and reads text Inputs: language, filename Outputs: n/a */ import java.util.ArrayList; import java.util.Scanner; import java.io.FileNotFoundException; public class EarthText implements EarthCellPhone { private ArrayList<String> validLanguages; /** * initializes validLanguages and adds 3 languages. */ public EarthText() { validLanguages = new ArrayList<>(); validLanguages.add("Earth"); validLanguages.add("Klingon"); validLanguages.add("Vulcan"); } /** * Sends a message in the respective language. * * @param languageType the language that it's going to be translated to * @param fileName the file to be read from * @throws InvalidLanguageException */ @Override public void sendMessage(String languageType, String fileName) throws InvalidLanguageException { if (validLanguages.contains(languageType)) { try{ java.io.File f1 = new java.io.File(fileName); Scanner input = new Scanner(f1); System.out.println(languageType + " Message Sent"); } catch (FileNotFoundException fnf) { System.out.println(fileName + " doesn't exist"); } } else throw new InvalidLanguageException(languageType); } /** * reads a message from a file * * @param fileName file to be read from */ @Override public void readMessage(String fileName) { java.io.File f1 = new java.io.File(fileName); try { Scanner input = new Scanner(f1); System.out.println(input.nextLine()); input.close(); } catch (FileNotFoundException fnf) { System.out.println("File: " + fileName + " does not exist"); } } /** * string representation of an EarthText object * * @return string representation of an EarthText object */ public String toString() { return "This is an EarthText object.\n"; } }
1,832
0.698697
0.692725
74
23.891891
21.718449
96
false
false
0
0
0
0
0
0
1.621622
false
false
5
d9b0b41731f855d2081c1d97e325a3f7d90be86b
23,527,830,894,119
b1115032e6ca9712bcd7612f6cf16757252d41a4
/RoomForHire/app/src/main/java/com/example/quanla/roomforhire/events/Event.java
26f5b6a6956b8bbe95fbdac311f9b082bc693fad
[]
no_license
quanleanhqla/RoomForHire
https://github.com/quanleanhqla/RoomForHire
c7c68015710dc3fb874c881a00cd8c53bb4bf76f
e633746fb4ba47e72749829327cd7849d8ef393f
refs/heads/master
2021-01-19T14:46:22.120000
2017-05-18T17:27:11
2017-05-18T17:27:11
88,188,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.quanla.roomforhire.events; import com.example.quanla.roomforhire.dataFake.models.Room; /** * Created by QuanLA on 5/12/2017. */ public class Event { private Room room; private MoveToMap moveToMap; public Event(Room room, MoveToMap moveToMap) { this.room = room; moveToMap = moveToMap; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } }
UTF-8
Java
473
java
Event.java
Java
[ { "context": "omforhire.dataFake.models.Room;\n\n/**\n * Created by QuanLA on 5/12/2017.\n */\n\npublic class Event {\n priva", "end": 133, "score": 0.9708001017570496, "start": 127, "tag": "USERNAME", "value": "QuanLA" } ]
null
[]
package com.example.quanla.roomforhire.events; import com.example.quanla.roomforhire.dataFake.models.Room; /** * Created by QuanLA on 5/12/2017. */ public class Event { private Room room; private MoveToMap moveToMap; public Event(Room room, MoveToMap moveToMap) { this.room = room; moveToMap = moveToMap; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } }
473
0.638478
0.623679
25
17.92
17.665606
59
false
false
0
0
0
0
0
0
0.36
false
false
5
7759a3e28844ccedfda3b255c8bc98e556807e5f
17,772,574,710,659
91e50320d08dcd8279c5a750412fbae42f0aceda
/app/src/main/java/com/klcn/xuant/transporter/CustomerCallActivity.java
aa42d73cc8b0cc49e168b6111b59c54d40b50db2
[]
no_license
KLCN-K14/FinalProject
https://github.com/KLCN-K14/FinalProject
a7d23130a870aef91916c0476d5ceee5ca137582
de0ec635464ef8bb72548b108d13f387d7084b3a
refs/heads/master
2020-03-23T05:04:35.055000
2018-07-18T12:59:34
2018-07-18T12:59:34
141,123,347
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.klcn.xuant.transporter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import com.github.lzyzsd.circleprogress.ArcProgress; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.klcn.xuant.transporter.common.Common; import com.klcn.xuant.transporter.helper.ArcProgressAnimation; import com.klcn.xuant.transporter.model.Driver; import com.klcn.xuant.transporter.model.FCMResponse; import com.klcn.xuant.transporter.model.Notification; import com.klcn.xuant.transporter.model.PickupRequest; import com.klcn.xuant.transporter.model.Sender; import com.klcn.xuant.transporter.model.Token; import com.klcn.xuant.transporter.remote.IFCMService; import com.klcn.xuant.transporter.remote.IGoogleAPI; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class CustomerCallActivity extends AppCompatActivity implements View.OnClickListener{ @BindView(R.id.txt_your_destination) TextView mTxtYourDestination; // @BindView(R.id.txt_price) // TextView mTxtPrice; // @BindView(R.id.txt_distance) TextView mTxtDistance; @BindView(R.id.txt_time) TextView mTxtTime; @BindView(R.id.btn_accept_pickup_request) Button mBtnAccept; @BindView(R.id.btn_cancel_find_driver) Button mBtnCancel; @BindView(R.id.arc_progress) ArcProgress mArcProgress; @BindView(R.id.lnl_panel_distance) RelativeLayout mPanelDistance; IGoogleAPI mService; MediaPlayer mediaPlayer; double lat,lng; String destination; String customerId; Driver mDriver; IFCMService mFCMService; private BroadcastReceiver mReceiver; @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/Arkhip_font.ttf") .setFontAttrId(R.attr.fontPath) .build()); setContentView(R.layout.activity_customer_call); ButterKnife.bind(this); mFCMService = Common.getFCMService(); mPanelDistance.setVisibility(View.GONE); mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.notification); mediaPlayer.setLooping(true); mediaPlayer.start(); getInfoDriver(); removeDriverAvailable(); mService = Common.getGoogleAPI(); if(getIntent()!=null){ lat = Double.parseDouble(getIntent().getStringExtra("lat").toString()); lng = Double.parseDouble(getIntent().getStringExtra("lng").toString()); mTxtYourDestination.setText(getNameAdress(lat,lng).toUpperCase()); destination = getIntent().getStringExtra("destination"); customerId = getIntent().getStringExtra("customerId"); getDirection(lat,lng,destination); } mBtnAccept.setOnClickListener(this); mBtnCancel.setOnClickListener(this); mArcProgress.setMax(15); ArcProgressAnimation anim = new ArcProgressAnimation(mArcProgress, 0, 15); anim.setDuration(15000); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } addDriverAvailable(); sendMessageCancelRequest(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { finish(); } },1000); } @Override public void onAnimationRepeat(Animation animation) { } }); mArcProgress.startAnimation(anim); } private void getInfoDriver() { FirebaseDatabase.getInstance().getReference(Common.drivers_tbl) .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ mDriver = dataSnapshot.getValue(Driver.class); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public void removeDriverAvailable() { String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(Common.driver_available_tbl); GeoFire geoFire = new GeoFire(ref); geoFire.removeLocation(userId, new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { } }); } public void addDriverAvailable() { String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(Common.driver_available_tbl); GeoFire geoFire = new GeoFire(ref); geoFire.setLocation(userId, new GeoLocation( Common.mLastLocationDriver.getLatitude(), Common.mLastLocationDriver.getLongitude()), new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { //Add marker } }); } private void getDirection(double lat, double lng, String destination) { String requestApi = null; try{ requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+ "mode=driving&"+ "transit_routing_preference=less_driving&"+ "origin="+ lat+","+lng+"&"+ "destination="+destination+"&"+ "key="+getResources().getString(R.string.google_direction_api); Log.d("TRANSPORT",requestApi); mService.getPath(requestApi) .enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { try { JSONObject jsonObject = new JSONObject(response.body().toString()); JSONArray routes = jsonObject.getJSONArray("routes"); JSONObject object = routes.getJSONObject(0); JSONArray legs = object.getJSONArray("legs"); JSONObject legsObject = legs.getJSONObject(0); JSONObject distanceJS = legsObject.getJSONObject("distance"); Double distance = distanceJS.getDouble("value"); JSONObject timeJS = legsObject.getJSONObject("duration"); Double time = timeJS.getDouble("value"); if(distance>15000){ mPanelDistance.setVisibility(View.VISIBLE); mTxtDistance.setText(distanceJS.getString("text")); calculateFare(distance,time); } String address = legsObject.getString("start_address"); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(Call<String> call, Throwable t) { } }); }catch (Exception e){ e.printStackTrace(); } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_cancel_find_driver: sendMessageCancelRequest(); addDriverAvailable(); finish(); break; case R.id.btn_accept_pickup_request: sendMessageAccept(); DatabaseReference pickupRequest = FirebaseDatabase.getInstance().getReference(Common.pickup_request_tbl); PickupRequest pickupRequest1 = new PickupRequest(); pickupRequest1.setLatPickup(String.valueOf(lat)); pickupRequest1.setLngPickup(String.valueOf(lng)); pickupRequest1.setDestination(destination); pickupRequest1.setCustomerId(customerId); pickupRequest.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .setValue(pickupRequest1) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { finish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull final Exception e) { e.printStackTrace(); // send cancel to customer } }); break; } } private void sendMessageAccept() { DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.tokens_tbl); tokens.orderByKey().equalTo(customerId) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot postData: dataSnapshot.getChildren()){ Token token = postData.getValue(Token.class); Notification notification = new Notification("DriverAccept","Your driver accept your request!"); Sender sender = new Sender(token.getToken(),notification); mFCMService.sendMessage(sender).enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if(response.body().success == 1){ Log.e("MessageCancelRequest","Success"); } else{ Log.e("MessageCancelRequest",response.message()); Log.e("MessageCancelRequest",response.errorBody().toString()); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void sendMessageCancelRequest() { DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.tokens_tbl); tokens.orderByKey().equalTo(customerId) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot postData: dataSnapshot.getChildren()){ Token token = postData.getValue(Token.class); Notification notification = new Notification("Cancel","Your driver denied your request!"); Sender sender = new Sender(token.getToken(),notification); mFCMService.sendMessage(sender).enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if(response.body().success == 1){ Log.e("MessageCancelRequest","Success"); } else{ Log.e("MessageCancelRequest",response.message()); Log.e("MessageCancelRequest",response.errorBody().toString()); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override protected void onResume() { IntentFilter intentFilter = new IntentFilter( "android.intent.action.MAIN"); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //extract our message from intent if(intent.getStringExtra("CancelTrip")!=null){ mBtnAccept.setEnabled(false); mBtnCancel.setEnabled(false); Toast.makeText(getApplicationContext(),"Customer cancel request!!!",Toast.LENGTH_LONG).show(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { finish(); } },2000); } } }; //registering our receiver this.registerReceiver(mReceiver, intentFilter); super.onResume(); } @Override protected void onStop() { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } this.unregisterReceiver(mReceiver); super.onStop(); } @Override protected void onPause() { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } super.onPause(); } @Override protected void onDestroy() { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } private String getNameAdress(double lat, double lng) { Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(lat,lng, 1); if(!addresses.isEmpty()){ Address obj = addresses.get(0); String namePlacePickup = ""; if (obj.getSubThoroughfare() != null && obj.getThoroughfare() != null) { namePlacePickup = namePlacePickup + obj.getSubThoroughfare() + " "+ obj.getThoroughfare() + ", "; } if(obj.getLocality()!=null){ namePlacePickup = namePlacePickup + obj.getLocality() + ", "; } namePlacePickup = namePlacePickup + obj.getSubAdminArea()+", "+obj.getAdminArea(); return namePlacePickup; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } return ""; } private void calculateFare(Double distance, Double time) { Double realDistance = (distance/1000); Double realTime = time/60; Double hour = realTime%60; Double minute = realTime - hour*60; String timeArrived; if(realTime<60.){ timeArrived = realTime.intValue() + " min"; }else{ timeArrived = hour.intValue() + " h "+minute.intValue()+" min"; } mTxtTime.setText(timeArrived); // Double fareStandard = Common.base_fare + Common.cost_per_km*realDistance + Common.cost_per_minute_standard*realTime; // Double farePremium = Common.base_fare + Common.cost_per_km*realDistance + Common.cost_per_minute_premium*realTime; // String textFareStandard = "VND "+Integer.toString(fareStandard.intValue())+"K"; // String textFarePremium = "VND "+Integer.toString(farePremium.intValue())+"K"; // if(mDriver!=null){ // if(mDriver.getServiceVehicle().equals(Common.service_vehicle_standard)){ // mTxtPrice.setText(textFareStandard); // }else{ // mTxtPrice.setText(textFarePremium); // } // } } }
UTF-8
Java
19,590
java
CustomerCallActivity.java
Java
[ { "context": "m.firebase.geofire.GeoLocation;\nimport com.github.lzyzsd.circleprogress.ArcProgress;\nimport com.google.and", "end": 827, "score": 0.9404653906822205, "start": 821, "tag": "USERNAME", "value": "lzyzsd" }, { "context": "Callback;\nimport retrofit2.Response;\nimport uk.co.chrisjenx.calligraphy.CalligraphyConfig;\nimport uk.co.chris", "end": 2127, "score": 0.9316551685333252, "start": 2118, "tag": "USERNAME", "value": "chrisjenx" }, { "context": "sjenx.calligraphy.CalligraphyConfig;\nimport uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;\n\npublic cl", "end": 2181, "score": 0.8610824942588806, "start": 2172, "tag": "USERNAME", "value": "chrisjenx" } ]
null
[]
package com.klcn.xuant.transporter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import com.github.lzyzsd.circleprogress.ArcProgress; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.klcn.xuant.transporter.common.Common; import com.klcn.xuant.transporter.helper.ArcProgressAnimation; import com.klcn.xuant.transporter.model.Driver; import com.klcn.xuant.transporter.model.FCMResponse; import com.klcn.xuant.transporter.model.Notification; import com.klcn.xuant.transporter.model.PickupRequest; import com.klcn.xuant.transporter.model.Sender; import com.klcn.xuant.transporter.model.Token; import com.klcn.xuant.transporter.remote.IFCMService; import com.klcn.xuant.transporter.remote.IGoogleAPI; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class CustomerCallActivity extends AppCompatActivity implements View.OnClickListener{ @BindView(R.id.txt_your_destination) TextView mTxtYourDestination; // @BindView(R.id.txt_price) // TextView mTxtPrice; // @BindView(R.id.txt_distance) TextView mTxtDistance; @BindView(R.id.txt_time) TextView mTxtTime; @BindView(R.id.btn_accept_pickup_request) Button mBtnAccept; @BindView(R.id.btn_cancel_find_driver) Button mBtnCancel; @BindView(R.id.arc_progress) ArcProgress mArcProgress; @BindView(R.id.lnl_panel_distance) RelativeLayout mPanelDistance; IGoogleAPI mService; MediaPlayer mediaPlayer; double lat,lng; String destination; String customerId; Driver mDriver; IFCMService mFCMService; private BroadcastReceiver mReceiver; @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/Arkhip_font.ttf") .setFontAttrId(R.attr.fontPath) .build()); setContentView(R.layout.activity_customer_call); ButterKnife.bind(this); mFCMService = Common.getFCMService(); mPanelDistance.setVisibility(View.GONE); mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.notification); mediaPlayer.setLooping(true); mediaPlayer.start(); getInfoDriver(); removeDriverAvailable(); mService = Common.getGoogleAPI(); if(getIntent()!=null){ lat = Double.parseDouble(getIntent().getStringExtra("lat").toString()); lng = Double.parseDouble(getIntent().getStringExtra("lng").toString()); mTxtYourDestination.setText(getNameAdress(lat,lng).toUpperCase()); destination = getIntent().getStringExtra("destination"); customerId = getIntent().getStringExtra("customerId"); getDirection(lat,lng,destination); } mBtnAccept.setOnClickListener(this); mBtnCancel.setOnClickListener(this); mArcProgress.setMax(15); ArcProgressAnimation anim = new ArcProgressAnimation(mArcProgress, 0, 15); anim.setDuration(15000); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } addDriverAvailable(); sendMessageCancelRequest(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { finish(); } },1000); } @Override public void onAnimationRepeat(Animation animation) { } }); mArcProgress.startAnimation(anim); } private void getInfoDriver() { FirebaseDatabase.getInstance().getReference(Common.drivers_tbl) .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ mDriver = dataSnapshot.getValue(Driver.class); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public void removeDriverAvailable() { String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(Common.driver_available_tbl); GeoFire geoFire = new GeoFire(ref); geoFire.removeLocation(userId, new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { } }); } public void addDriverAvailable() { String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(Common.driver_available_tbl); GeoFire geoFire = new GeoFire(ref); geoFire.setLocation(userId, new GeoLocation( Common.mLastLocationDriver.getLatitude(), Common.mLastLocationDriver.getLongitude()), new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { //Add marker } }); } private void getDirection(double lat, double lng, String destination) { String requestApi = null; try{ requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+ "mode=driving&"+ "transit_routing_preference=less_driving&"+ "origin="+ lat+","+lng+"&"+ "destination="+destination+"&"+ "key="+getResources().getString(R.string.google_direction_api); Log.d("TRANSPORT",requestApi); mService.getPath(requestApi) .enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { try { JSONObject jsonObject = new JSONObject(response.body().toString()); JSONArray routes = jsonObject.getJSONArray("routes"); JSONObject object = routes.getJSONObject(0); JSONArray legs = object.getJSONArray("legs"); JSONObject legsObject = legs.getJSONObject(0); JSONObject distanceJS = legsObject.getJSONObject("distance"); Double distance = distanceJS.getDouble("value"); JSONObject timeJS = legsObject.getJSONObject("duration"); Double time = timeJS.getDouble("value"); if(distance>15000){ mPanelDistance.setVisibility(View.VISIBLE); mTxtDistance.setText(distanceJS.getString("text")); calculateFare(distance,time); } String address = legsObject.getString("start_address"); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(Call<String> call, Throwable t) { } }); }catch (Exception e){ e.printStackTrace(); } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_cancel_find_driver: sendMessageCancelRequest(); addDriverAvailable(); finish(); break; case R.id.btn_accept_pickup_request: sendMessageAccept(); DatabaseReference pickupRequest = FirebaseDatabase.getInstance().getReference(Common.pickup_request_tbl); PickupRequest pickupRequest1 = new PickupRequest(); pickupRequest1.setLatPickup(String.valueOf(lat)); pickupRequest1.setLngPickup(String.valueOf(lng)); pickupRequest1.setDestination(destination); pickupRequest1.setCustomerId(customerId); pickupRequest.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .setValue(pickupRequest1) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { finish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull final Exception e) { e.printStackTrace(); // send cancel to customer } }); break; } } private void sendMessageAccept() { DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.tokens_tbl); tokens.orderByKey().equalTo(customerId) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot postData: dataSnapshot.getChildren()){ Token token = postData.getValue(Token.class); Notification notification = new Notification("DriverAccept","Your driver accept your request!"); Sender sender = new Sender(token.getToken(),notification); mFCMService.sendMessage(sender).enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if(response.body().success == 1){ Log.e("MessageCancelRequest","Success"); } else{ Log.e("MessageCancelRequest",response.message()); Log.e("MessageCancelRequest",response.errorBody().toString()); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void sendMessageCancelRequest() { DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.tokens_tbl); tokens.orderByKey().equalTo(customerId) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot postData: dataSnapshot.getChildren()){ Token token = postData.getValue(Token.class); Notification notification = new Notification("Cancel","Your driver denied your request!"); Sender sender = new Sender(token.getToken(),notification); mFCMService.sendMessage(sender).enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if(response.body().success == 1){ Log.e("MessageCancelRequest","Success"); } else{ Log.e("MessageCancelRequest",response.message()); Log.e("MessageCancelRequest",response.errorBody().toString()); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override protected void onResume() { IntentFilter intentFilter = new IntentFilter( "android.intent.action.MAIN"); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //extract our message from intent if(intent.getStringExtra("CancelTrip")!=null){ mBtnAccept.setEnabled(false); mBtnCancel.setEnabled(false); Toast.makeText(getApplicationContext(),"Customer cancel request!!!",Toast.LENGTH_LONG).show(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { finish(); } },2000); } } }; //registering our receiver this.registerReceiver(mReceiver, intentFilter); super.onResume(); } @Override protected void onStop() { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } this.unregisterReceiver(mReceiver); super.onStop(); } @Override protected void onPause() { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } super.onPause(); } @Override protected void onDestroy() { try { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer=null; } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } private String getNameAdress(double lat, double lng) { Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(lat,lng, 1); if(!addresses.isEmpty()){ Address obj = addresses.get(0); String namePlacePickup = ""; if (obj.getSubThoroughfare() != null && obj.getThoroughfare() != null) { namePlacePickup = namePlacePickup + obj.getSubThoroughfare() + " "+ obj.getThoroughfare() + ", "; } if(obj.getLocality()!=null){ namePlacePickup = namePlacePickup + obj.getLocality() + ", "; } namePlacePickup = namePlacePickup + obj.getSubAdminArea()+", "+obj.getAdminArea(); return namePlacePickup; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } return ""; } private void calculateFare(Double distance, Double time) { Double realDistance = (distance/1000); Double realTime = time/60; Double hour = realTime%60; Double minute = realTime - hour*60; String timeArrived; if(realTime<60.){ timeArrived = realTime.intValue() + " min"; }else{ timeArrived = hour.intValue() + " h "+minute.intValue()+" min"; } mTxtTime.setText(timeArrived); // Double fareStandard = Common.base_fare + Common.cost_per_km*realDistance + Common.cost_per_minute_standard*realTime; // Double farePremium = Common.base_fare + Common.cost_per_km*realDistance + Common.cost_per_minute_premium*realTime; // String textFareStandard = "VND "+Integer.toString(fareStandard.intValue())+"K"; // String textFarePremium = "VND "+Integer.toString(farePremium.intValue())+"K"; // if(mDriver!=null){ // if(mDriver.getServiceVehicle().equals(Common.service_vehicle_standard)){ // mTxtPrice.setText(textFareStandard); // }else{ // mTxtPrice.setText(textFarePremium); // } // } } }
19,590
0.551455
0.548851
523
36.456978
29.286211
154
false
false
0
0
0
0
0
0
0.51434
false
false
5
29d9953b3506217f6b4ae6a1103ea16a66a70d9e
17,772,574,709,256
d6888e32fd97c37ab418d95a1f02823b48821f8f
/interfaceSegregation/bad/Messenger.java
171a2b1bcefe8b5285d8731174e79270cec7c86d
[ "MIT" ]
permissive
JonathanF07/solid
https://github.com/JonathanF07/solid
cf79a8ba7d0a2065cc96eec004cba9e8753b8f7e
1eb3e2c414c8ba626b0858f79e02230fd91f21fc
refs/heads/master
2021-01-01T17:55:25.742000
2017-07-24T22:36:11
2017-07-24T22:36:11
98,202,565
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package interfaceSegregation.bad; public interface Messenger { void videoCall(); void audioCall(); void instantMessage(); void attachDocuments(); void attachPhotos(); void attachVideos(); void quickAndGoneVideo(); // AKA: Snap }
UTF-8
Java
275
java
Messenger.java
Java
[]
null
[]
package interfaceSegregation.bad; public interface Messenger { void videoCall(); void audioCall(); void instantMessage(); void attachDocuments(); void attachPhotos(); void attachVideos(); void quickAndGoneVideo(); // AKA: Snap }
275
0.643636
0.643636
20
12.75
13.888394
42
false
false
0
0
0
0
0
0
0.4
false
false
5
069c12158790bc6c0ae4226918f96433d9b64e10
30,227,979,876,409
ed25f9b70decb482c6f5e48fc3a4a4a0a6f7307c
/app/src/main/java/cn/com/sise/ca/castore/server/facades/HomePageBaseFacade.java
4a5a7c106896dd9dbc622b75aa5b920b0243d7fd
[ "MIT" ]
permissive
codimiracle/castore-android
https://github.com/codimiracle/castore-android
7dcc46444454df39dd32ff2017239bac37a84f12
ff46c515a41791f213562416d9058ea3e7a0a890
refs/heads/master
2020-03-16T13:46:51.590000
2018-06-23T09:06:38
2018-06-23T09:06:38
132,699,469
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.sise.ca.castore.server.facades; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import cn.com.sise.ca.castore.R; import cn.com.sise.ca.castore.server.som.HomePageInfoBean; public class HomePageBaseFacade implements Facade { private HomePageInfoBean homePageInfoBean; private View view; private PosterAlbumFacade posterAlbumFacade; private ArticleAlbumFacade articleAlbumFacade; private ApplicationSimpleFacade[] applicationSimpleFacade = new ApplicationSimpleFacade[4]; private LinearLayout viewOddmentsApps; private TextView viewOddmentsTitle; public HomePageInfoBean getHomePageInfoBean() { return homePageInfoBean; } public void setHomePageInfoBean(HomePageInfoBean homePageInfoBean) { if (homePageInfoBean.getType() != HomePageInfoBean.PAGE) { throw new IllegalArgumentException(); } this.homePageInfoBean = homePageInfoBean; viewOddmentsTitle.setText(homePageInfoBean.getOddmentsTitle()); int childCount = viewOddmentsApps.getChildCount(); for (int i = 0; i < childCount; i++) { applicationSimpleFacade[i] = new ApplicationSimpleFacade(); applicationSimpleFacade[i].setView(viewOddmentsApps.getChildAt(i)); } } @Override public void setView(View view) { this.view = view; viewOddmentsApps = view.findViewById(R.id.home_page_oddments_apps_container); viewOddmentsTitle = view.findViewById(R.id.home_page_oddments_apps_title); posterAlbumFacade = new PosterAlbumFacade(view.findViewById(R.id.home_page_poster_album)); articleAlbumFacade = new ArticleAlbumFacade(view.findViewById(R.id.home_page_article_album)); } @Override public View getView() { return view; } }
UTF-8
Java
1,856
java
HomePageBaseFacade.java
Java
[]
null
[]
package cn.com.sise.ca.castore.server.facades; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import cn.com.sise.ca.castore.R; import cn.com.sise.ca.castore.server.som.HomePageInfoBean; public class HomePageBaseFacade implements Facade { private HomePageInfoBean homePageInfoBean; private View view; private PosterAlbumFacade posterAlbumFacade; private ArticleAlbumFacade articleAlbumFacade; private ApplicationSimpleFacade[] applicationSimpleFacade = new ApplicationSimpleFacade[4]; private LinearLayout viewOddmentsApps; private TextView viewOddmentsTitle; public HomePageInfoBean getHomePageInfoBean() { return homePageInfoBean; } public void setHomePageInfoBean(HomePageInfoBean homePageInfoBean) { if (homePageInfoBean.getType() != HomePageInfoBean.PAGE) { throw new IllegalArgumentException(); } this.homePageInfoBean = homePageInfoBean; viewOddmentsTitle.setText(homePageInfoBean.getOddmentsTitle()); int childCount = viewOddmentsApps.getChildCount(); for (int i = 0; i < childCount; i++) { applicationSimpleFacade[i] = new ApplicationSimpleFacade(); applicationSimpleFacade[i].setView(viewOddmentsApps.getChildAt(i)); } } @Override public void setView(View view) { this.view = view; viewOddmentsApps = view.findViewById(R.id.home_page_oddments_apps_container); viewOddmentsTitle = view.findViewById(R.id.home_page_oddments_apps_title); posterAlbumFacade = new PosterAlbumFacade(view.findViewById(R.id.home_page_poster_album)); articleAlbumFacade = new ArticleAlbumFacade(view.findViewById(R.id.home_page_article_album)); } @Override public View getView() { return view; } }
1,856
0.72306
0.721983
53
34.018867
29.927265
101
false
false
0
0
0
0
0
0
0.528302
false
false
5
8f0abbe75381b6b63c04885ef739272abb1f2aca
30,227,979,879,012
e5c209bd727fb9c6f3266a74ae7d0fbb388daa6f
/src/test/java/se/lexicon/teri/data/TodoSequencerTest.java
b46d94bd85ebcb80511fdfcd2fe7d049439bc769
[]
no_license
Tamadoc/todo_it
https://github.com/Tamadoc/todo_it
9083c3aee099929ec386c1485489e7f09cbd01df
126bf94c0c1df4a4e9eafecaf3e84ae1f9061323
refs/heads/main
2023-03-09T10:05:14.934000
2021-01-02T16:59:45
2021-01-02T16:59:45
324,960,837
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.lexicon.teri.data; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TodoSequencerTest { @Test public void test_nextTodoId() { TodoSequencer.resetTodoId(); int expectedId = 1; assertEquals(expectedId, TodoSequencer.nextTodoId()); } }
UTF-8
Java
316
java
TodoSequencerTest.java
Java
[]
null
[]
package se.lexicon.teri.data; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TodoSequencerTest { @Test public void test_nextTodoId() { TodoSequencer.resetTodoId(); int expectedId = 1; assertEquals(expectedId, TodoSequencer.nextTodoId()); } }
316
0.693038
0.689873
15
20.066668
18.837788
61
false
false
0
0
0
0
0
0
0.466667
false
false
5
58131de58f04bb1f2ff7827ef3d3a677bf02c8ea
6,511,170,473,692
f095742764161e52f27de771fbd869a7b92bb068
/program/src/main/java/com/smart/program/service/recharge/impl/RechargeServiceImpl.java
d0af75935f50aeb4cbb471ed4e251993713411b9
[]
no_license
seraphFu/zammc-server
https://github.com/seraphFu/zammc-server
c82b47f7d8447b2be3b47d706855b831ca872d30
536c3043c10dbd56063cb2ae38a0f1245ab4452f
refs/heads/master
2018-11-16T03:05:03.201000
2018-09-16T06:31:36
2018-09-16T06:31:36
141,905,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smart.program.service.recharge.impl; import com.smart.program.common.ErrorConstant; import com.smart.program.common.ObjectTranslate; import com.smart.program.common.ServiceConfig; import com.smart.program.common.StringUtil; import com.smart.program.common.pay.PayUtil; import com.smart.program.domain.recharge.RechargeOrderEntity; import com.smart.program.domain.recharge.RechargePackageEntity; import com.smart.program.exception.BusinessException; import com.smart.program.idwork.IdWorker; import com.smart.program.repository.recharge.RechargeOrderRepository; import com.smart.program.repository.recharge.RechargePackageRepository; import com.smart.program.request.account.UserAccountService; import com.smart.program.request.recharge.RechargeRequest; import com.smart.program.response.recharge.RechargePackageResponse; import com.smart.program.service.recharge.RechargeService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Slf4j public class RechargeServiceImpl implements RechargeService { @Autowired private RechargePackageRepository rechargePackageRepository; @Autowired private IdWorker idWorker; @Autowired private RechargeOrderRepository rechargeOrderRepository; @Autowired private UserAccountService userAccountService; /** * 获取充值套餐 * * @return * @throws Exception */ public List<RechargePackageResponse> queryRechargePackage() throws Exception { List<RechargePackageResponse> rechargePackageResponses = new ArrayList<>(); List<RechargePackageEntity> rechargePackageEntities = rechargePackageRepository.queryRechargePackageList(); for (RechargePackageEntity rechargePackageEntity : rechargePackageEntities) { RechargePackageResponse rechargePackageResponse = new RechargePackageResponse(); rechargePackageResponse.setPackageId(rechargePackageEntity.getPackageId()); rechargePackageResponse.setRechargeMoney(rechargePackageEntity.getRechargeMoney()); rechargePackageResponse.setPayMoney(rechargePackageEntity.getPayMoney()); rechargePackageResponse.setChosen(false); rechargePackageResponses.add(rechargePackageResponse); } return rechargePackageResponses; } /** * 充值 * * @param request * @throws Exception */ public synchronized Map<String, Object> recharge(RechargeRequest request) throws Exception { RechargeOrderEntity rechargeOrderEntity = new RechargeOrderEntity(); Long orderId = idWorker.nextId(); rechargeOrderEntity.setOrderId(orderId); rechargeOrderEntity.setUserId(request.getUserId()); BigDecimal fee = BigDecimal.ZERO; if (request.getIsPackage() == 1) {//是套餐 // 获取套餐信息 RechargePackageEntity rechargePackageEntity = rechargePackageRepository.queryPackageById(request.getPackageId()); if (null == rechargeOrderEntity) { throw new BusinessException(ErrorConstant.PACKAGE_IS_NULL_ERROR, ErrorConstant.PACKAGE_IS_NULL_ERROR_MSG); } fee = rechargePackageEntity.getPayMoney(); rechargeOrderEntity.setRechargeMoney(rechargePackageEntity.getRechargeMoney()); } else { fee = request.getRechargeMoney(); rechargeOrderEntity.setRechargeMoney(fee); } rechargeOrderEntity.setPayMoney(fee); rechargeOrderEntity.setIsPackage(request.getIsPackage()); // 新增充值信息至订单表 rechargeOrderRepository.saveAndFlush(rechargeOrderEntity); //生成的随机字符串 String nonce_str = StringUtil.getRandomStringByLength(32); //组装参数,用户生成统一下单接口的签名 Map<String, String> packageParams = getSign(request, orderId, fee, nonce_str); String preStr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口 String mySign = PayUtil.sign(preStr, ServiceConfig.key, "utf-8").toUpperCase(); //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去 String xml = getMessage(orderId, fee, nonce_str, mySign); log.info("调试模式_统一下单接口 请求XML数据:-> {}", xml); //调用统一下单接口,并接受返回的结果 String res = PayUtil.httpRequest(ServiceConfig.pay_url, "POST", xml); System.out.println("调试模式_统一下单接口 返回XML数据:" + res); Map<String, Object> result = new HashMap<>(); // 将解析结果存储在HashMap中 Map map = new HashMap(); try { map = PayUtil.doXMLParse(res); } catch (Exception e) { log.error("调用微信转账失败"); throw new BusinessException(ErrorConstant.RECHARGE_ERROR, ErrorConstant.RECHARGE_ERROR_MSG); } String return_code = (String) map.get("return_code");//返回状态码 if (return_code == "SUCCESS") { String prepay_id = (String) map.get("prepay_id");//返回的预付单信息 result.put("nonceStr", nonce_str); result.put("package", "prepay_id=" + prepay_id); Long timeStamp = System.currentTimeMillis() / 1000; result.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误 //拼接签名需要的参数 String stringSignTemp = "appId=" + ServiceConfig.MINIAPPID + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp; //再次签名,这个签名用于小程序端调用wx.requesetPayment方法 String paySign = PayUtil.sign(stringSignTemp, ServiceConfig.key, "utf-8").toUpperCase(); result.put("nonce_str", nonce_str); result.put("package", "prepay_id=" + prepay_id); result.put("timeStamp", timeStamp + ""); result.put("paySign", paySign); } return result; } /** * 获取报文 * * @param orderId * @param fee * @param nonce_str * @param mySign * @return */ private String getMessage(Long orderId, BigDecimal fee, String nonce_str, String mySign) { return "<xml>" + "<appid>" + ServiceConfig.MINIAPPID + "</appid>" + "<body><![CDATA[\"转账\"]]></body>" + "<mch_id>" + ServiceConfig.mch_id + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<notify_url>" + ServiceConfig.notify_url + "</notify_url>" + "<openid>" + ObjectTranslate.getString(orderId) + "</openid>" + "<out_trade_no>" + ObjectTranslate.getString(orderId) + "</out_trade_no>" + "<spbill_create_ip>127.0.0.1</spbill_create_ip>" + "<total_fee>" + fee + "</total_fee>" + "<trade_type>" + ServiceConfig.TRADETYPE + "</trade_type>" + "<sign>" + mySign + "</sign>" + "</xml>"; } /** * 获取签名 * * @param request * @param orderId * @param fee * @param nonce_str * @return */ private Map<String, String> getSign(RechargeRequest request, Long orderId, BigDecimal fee, String nonce_str) { Map<String, String> packageParams = new HashMap<>(); packageParams.put("appid", ServiceConfig.MINIAPPID); packageParams.put("mch_id", ServiceConfig.mch_id); packageParams.put("nonce_str", nonce_str); packageParams.put("body", "转账"); packageParams.put("out_trade_no", ObjectTranslate.getString(orderId));//商户订单号 packageParams.put("total_fee", fee + "");//支付金额,这边需要转成字符串类型,否则后面的签名会失败 ObjectTranslate.getString(order.get("transport")) packageParams.put("spbill_create_ip", "127.0.0.1"); packageParams.put("notify_url", ServiceConfig.notify_url);//支付成功后的回调地址 packageParams.put("trade_type", ServiceConfig.TRADETYPE);//支付方式 packageParams.put("openid", request.getUserId()); return packageParams; } /** * 支付回调 * * @param request * @return * @throws Exception */ public String getCallBack(HttpServletRequest request) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } // sb为微信返回的xml String notityXml = sb.toString(); String resXml = ""; log.info("接收到的报文 -> {}", notityXml); Map map = PayUtil.doXMLParse(notityXml); String return_code = map.get("return_code").toString().toUpperCase(); if (return_code.equals("SUCCESS")) { //进行签名验证,看是否是从微信发送过来的,防止资金被盗 System.err.println(); // 验证签名是否正确 if (PayUtil.checkSign(notityXml)) { // 订单支付成功 业务处理 String out_trade_no = ObjectTranslate.getString(map.get("out_trade_no")); // 商户订单号 // 修改订单状态 updateOrderFinish(out_trade_no); resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; // 修改账户信息 updateUserAccount(Long.parseLong(out_trade_no)); } } else { resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> "; } log.info("callBack xml -> {}", resXml); log.info("微信支付回调数据结束"); return resXml; } /** * 修改订单状态为已完成 * * @param orderId * @throws Exception */ private void updateOrderFinish(String orderId) throws Exception { rechargeOrderRepository.updateOrderFinish(Long.parseLong(orderId)); } /** * 支付成功后修改账户信息 * * @param orderId * @throws Exception */ private void updateUserAccount(Long orderId) throws Exception { userAccountService.updateUserAccount(orderId); } }
UTF-8
Java
11,246
java
RechargeServiceImpl.java
Java
[ { "context": "t_trade_no>\"\n + \"<spbill_create_ip>127.0.0.1</spbill_create_ip>\"\n + \"<total_fee", "end": 6922, "score": 0.9909102320671082, "start": 6913, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "))\n packageParams.put(\"spbill_create_ip\", \"127.0.0.1\");\n packageParams.put(\"notify_url\", Servic", "end": 7954, "score": 0.9978058934211731, "start": 7945, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
package com.smart.program.service.recharge.impl; import com.smart.program.common.ErrorConstant; import com.smart.program.common.ObjectTranslate; import com.smart.program.common.ServiceConfig; import com.smart.program.common.StringUtil; import com.smart.program.common.pay.PayUtil; import com.smart.program.domain.recharge.RechargeOrderEntity; import com.smart.program.domain.recharge.RechargePackageEntity; import com.smart.program.exception.BusinessException; import com.smart.program.idwork.IdWorker; import com.smart.program.repository.recharge.RechargeOrderRepository; import com.smart.program.repository.recharge.RechargePackageRepository; import com.smart.program.request.account.UserAccountService; import com.smart.program.request.recharge.RechargeRequest; import com.smart.program.response.recharge.RechargePackageResponse; import com.smart.program.service.recharge.RechargeService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Slf4j public class RechargeServiceImpl implements RechargeService { @Autowired private RechargePackageRepository rechargePackageRepository; @Autowired private IdWorker idWorker; @Autowired private RechargeOrderRepository rechargeOrderRepository; @Autowired private UserAccountService userAccountService; /** * 获取充值套餐 * * @return * @throws Exception */ public List<RechargePackageResponse> queryRechargePackage() throws Exception { List<RechargePackageResponse> rechargePackageResponses = new ArrayList<>(); List<RechargePackageEntity> rechargePackageEntities = rechargePackageRepository.queryRechargePackageList(); for (RechargePackageEntity rechargePackageEntity : rechargePackageEntities) { RechargePackageResponse rechargePackageResponse = new RechargePackageResponse(); rechargePackageResponse.setPackageId(rechargePackageEntity.getPackageId()); rechargePackageResponse.setRechargeMoney(rechargePackageEntity.getRechargeMoney()); rechargePackageResponse.setPayMoney(rechargePackageEntity.getPayMoney()); rechargePackageResponse.setChosen(false); rechargePackageResponses.add(rechargePackageResponse); } return rechargePackageResponses; } /** * 充值 * * @param request * @throws Exception */ public synchronized Map<String, Object> recharge(RechargeRequest request) throws Exception { RechargeOrderEntity rechargeOrderEntity = new RechargeOrderEntity(); Long orderId = idWorker.nextId(); rechargeOrderEntity.setOrderId(orderId); rechargeOrderEntity.setUserId(request.getUserId()); BigDecimal fee = BigDecimal.ZERO; if (request.getIsPackage() == 1) {//是套餐 // 获取套餐信息 RechargePackageEntity rechargePackageEntity = rechargePackageRepository.queryPackageById(request.getPackageId()); if (null == rechargeOrderEntity) { throw new BusinessException(ErrorConstant.PACKAGE_IS_NULL_ERROR, ErrorConstant.PACKAGE_IS_NULL_ERROR_MSG); } fee = rechargePackageEntity.getPayMoney(); rechargeOrderEntity.setRechargeMoney(rechargePackageEntity.getRechargeMoney()); } else { fee = request.getRechargeMoney(); rechargeOrderEntity.setRechargeMoney(fee); } rechargeOrderEntity.setPayMoney(fee); rechargeOrderEntity.setIsPackage(request.getIsPackage()); // 新增充值信息至订单表 rechargeOrderRepository.saveAndFlush(rechargeOrderEntity); //生成的随机字符串 String nonce_str = StringUtil.getRandomStringByLength(32); //组装参数,用户生成统一下单接口的签名 Map<String, String> packageParams = getSign(request, orderId, fee, nonce_str); String preStr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口 String mySign = PayUtil.sign(preStr, ServiceConfig.key, "utf-8").toUpperCase(); //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去 String xml = getMessage(orderId, fee, nonce_str, mySign); log.info("调试模式_统一下单接口 请求XML数据:-> {}", xml); //调用统一下单接口,并接受返回的结果 String res = PayUtil.httpRequest(ServiceConfig.pay_url, "POST", xml); System.out.println("调试模式_统一下单接口 返回XML数据:" + res); Map<String, Object> result = new HashMap<>(); // 将解析结果存储在HashMap中 Map map = new HashMap(); try { map = PayUtil.doXMLParse(res); } catch (Exception e) { log.error("调用微信转账失败"); throw new BusinessException(ErrorConstant.RECHARGE_ERROR, ErrorConstant.RECHARGE_ERROR_MSG); } String return_code = (String) map.get("return_code");//返回状态码 if (return_code == "SUCCESS") { String prepay_id = (String) map.get("prepay_id");//返回的预付单信息 result.put("nonceStr", nonce_str); result.put("package", "prepay_id=" + prepay_id); Long timeStamp = System.currentTimeMillis() / 1000; result.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误 //拼接签名需要的参数 String stringSignTemp = "appId=" + ServiceConfig.MINIAPPID + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp; //再次签名,这个签名用于小程序端调用wx.requesetPayment方法 String paySign = PayUtil.sign(stringSignTemp, ServiceConfig.key, "utf-8").toUpperCase(); result.put("nonce_str", nonce_str); result.put("package", "prepay_id=" + prepay_id); result.put("timeStamp", timeStamp + ""); result.put("paySign", paySign); } return result; } /** * 获取报文 * * @param orderId * @param fee * @param nonce_str * @param mySign * @return */ private String getMessage(Long orderId, BigDecimal fee, String nonce_str, String mySign) { return "<xml>" + "<appid>" + ServiceConfig.MINIAPPID + "</appid>" + "<body><![CDATA[\"转账\"]]></body>" + "<mch_id>" + ServiceConfig.mch_id + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<notify_url>" + ServiceConfig.notify_url + "</notify_url>" + "<openid>" + ObjectTranslate.getString(orderId) + "</openid>" + "<out_trade_no>" + ObjectTranslate.getString(orderId) + "</out_trade_no>" + "<spbill_create_ip>127.0.0.1</spbill_create_ip>" + "<total_fee>" + fee + "</total_fee>" + "<trade_type>" + ServiceConfig.TRADETYPE + "</trade_type>" + "<sign>" + mySign + "</sign>" + "</xml>"; } /** * 获取签名 * * @param request * @param orderId * @param fee * @param nonce_str * @return */ private Map<String, String> getSign(RechargeRequest request, Long orderId, BigDecimal fee, String nonce_str) { Map<String, String> packageParams = new HashMap<>(); packageParams.put("appid", ServiceConfig.MINIAPPID); packageParams.put("mch_id", ServiceConfig.mch_id); packageParams.put("nonce_str", nonce_str); packageParams.put("body", "转账"); packageParams.put("out_trade_no", ObjectTranslate.getString(orderId));//商户订单号 packageParams.put("total_fee", fee + "");//支付金额,这边需要转成字符串类型,否则后面的签名会失败 ObjectTranslate.getString(order.get("transport")) packageParams.put("spbill_create_ip", "127.0.0.1"); packageParams.put("notify_url", ServiceConfig.notify_url);//支付成功后的回调地址 packageParams.put("trade_type", ServiceConfig.TRADETYPE);//支付方式 packageParams.put("openid", request.getUserId()); return packageParams; } /** * 支付回调 * * @param request * @return * @throws Exception */ public String getCallBack(HttpServletRequest request) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } // sb为微信返回的xml String notityXml = sb.toString(); String resXml = ""; log.info("接收到的报文 -> {}", notityXml); Map map = PayUtil.doXMLParse(notityXml); String return_code = map.get("return_code").toString().toUpperCase(); if (return_code.equals("SUCCESS")) { //进行签名验证,看是否是从微信发送过来的,防止资金被盗 System.err.println(); // 验证签名是否正确 if (PayUtil.checkSign(notityXml)) { // 订单支付成功 业务处理 String out_trade_no = ObjectTranslate.getString(map.get("out_trade_no")); // 商户订单号 // 修改订单状态 updateOrderFinish(out_trade_no); resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; // 修改账户信息 updateUserAccount(Long.parseLong(out_trade_no)); } } else { resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> "; } log.info("callBack xml -> {}", resXml); log.info("微信支付回调数据结束"); return resXml; } /** * 修改订单状态为已完成 * * @param orderId * @throws Exception */ private void updateOrderFinish(String orderId) throws Exception { rechargeOrderRepository.updateOrderFinish(Long.parseLong(orderId)); } /** * 支付成功后修改账户信息 * * @param orderId * @throws Exception */ private void updateUserAccount(Long orderId) throws Exception { userAccountService.updateUserAccount(orderId); } }
11,246
0.640773
0.638261
264
38.204544
31.864828
175
false
false
0
0
0
0
0
0
0.602273
false
false
5
c263b149ece93bf31e8ec9a3416ea18280530349
16,054,587,803,556
43aa135f1d0983b5a8a8455857931c720d8787df
/oms/web3-NewDc/plugin/web3-xbaio/java/webbroker3/aio/service/delegate/stdimpls/WEB3AdminFXTransferOrderUnitServiceImpl.java
a1d94a0ddad152f334f56731ac79a490929c52a6
[ "Apache-2.0", "W3C-19980720", "Apache-1.1", "BSD-2-Clause" ]
permissive
leegine/COMS
https://github.com/leegine/COMS
d8637ee07d0d0cc83187cf216c5b423d19ce9c43
f8d9027ca0b6f3656843d908b0c6b95600266193
refs/heads/master
2020-04-18T05:37:41.079000
2019-01-29T08:31:38
2019-01-29T08:31:38
167,285,652
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
head 1.1; access; symbols; locks; strict; comment @// @; 1.1 date 2011.03.16.05.31.02; author zhang-tengyu; state Exp; branches; next ; deltatype text; kopt kv; permissions 666; commitid 8f04d80403d696d; filename WEB3AdminFXTransferOrderUnitServiceImpl.java; desc @@ 1.1 log @*** empty log message *** @ text @/** Copyright : (株)大和総研 証券ソリューションシステム第二部 File Name : FX振替注文UnitServiceImpl(WEB3AdminFXTransferOrderUnitServiceImpl.java) Author Name : Daiwa Institute of Research Revesion History : 2006/02/23 鄭徳懇(中訊) 新規作成 Revesion History : 2007/07/12 趙林鵬(中訊) モデルNo.733 Revesion History : 2007/07/28 孟亜南(中訊) 仕様変更モデル744 Revesion History : 2009/03/11 王志葵(中訊) 仕様変更モデル1115 */ package webbroker3.aio.service.delegate.stdimpls; import java.util.Date; import java.util.Map; import com.fitechlabs.xtrade.kernel.boot.Services; import com.fitechlabs.xtrade.plugin.security.oplogin.LoginInfo; import com.fitechlabs.xtrade.plugin.security.oplogin.OpLoginAdminService; import com.fitechlabs.xtrade.plugin.security.oplogin.OpLoginSecurityService; import com.fitechlabs.xtrade.plugin.tc.gentrade.FinApp; import com.fitechlabs.xtrade.plugin.tc.gentrade.GtlUtils; import com.fitechlabs.xtrade.plugin.tc.gentrade.Institution; import com.fitechlabs.xtrade.plugin.tc.gentrade.NotFoundException; import com.fitechlabs.xtrade.plugin.tc.gentrade.ProductTypeEnum; import com.fitechlabs.xtrade.plugin.tc.gentrade.SubAccount; import com.fitechlabs.xtrade.plugin.tc.gentrade.SubAccountTypeEnum; import com.fitechlabs.xtrade.plugin.tc.xbaio.AssetTransferTypeEnum; import webbroker3.aio.WEB3AdminFXTransferOrderUploadCsv; import webbroker3.aio.WEB3AioNewOrderSpec; import webbroker3.aio.WEB3AioOrderManager; import webbroker3.aio.WEB3FXDataControlService; import webbroker3.aio.WEB3FXTransferOrderUpdateInterceptor; import webbroker3.aio.data.CompFxConditionParams; import webbroker3.aio.data.FxAccountCodeParams; import webbroker3.aio.data.FxAccountParams; import webbroker3.aio.data.FxTransferMasterParams; import webbroker3.aio.message.WEB3FXGftAskingTelegramUnit; import webbroker3.aio.service.delegate.WEB3AdminFXTransferOrderUnitService; import webbroker3.aio.service.delegate.WEB3MarginTransferService; import webbroker3.common.WEB3BaseException; import webbroker3.common.WEB3Crypt; import webbroker3.common.WEB3ErrorCatalog; import webbroker3.common.WEB3SystemLayerException; import webbroker3.common.define.WEB3AioTransferDivDef; import webbroker3.common.define.WEB3GftMessageOperationDef; import webbroker3.common.define.WEB3GftTransStatusCourseDivDef; import webbroker3.common.define.WEB3LoginTypeAttributeKeyDef; import webbroker3.common.define.WEB3MqStatusDef; import webbroker3.common.define.WEB3TradingPwdEnvDef; import webbroker3.common.message.WEB3GenResponse; import webbroker3.gentrade.WEB3GentradeAccountManager; import webbroker3.gentrade.WEB3GentradeMainAccount; import webbroker3.gentrade.WEB3GentradeSubAccount; import webbroker3.gentrade.WEB3GentradeTradingTimeManagement; import webbroker3.gentrade.WEB3HostReqOrderNumberManageService; import webbroker3.gentrade.define.WEB3GentradeRepaymentDivDef; import webbroker3.tradingpower.WEB3TPTradingPowerService; import webbroker3.util.WEB3DateUtility; import webbroker3.util.WEB3LogUtility; import webbroker3.util.WEB3StringTypeUtility; /** * (FX振替注文UnitServiceImpl)<BR> * FX振替注文UnitService実装クラス<BR> * <BR> * Plugin時に自動トランザクションTransactionalInterceptor<BR> * (TransactionalInterceptor.TX_CREATE_NEW)を指定する。 <BR> * * @@author 鄭徳懇 * @@version 1.0 */ public class WEB3AdminFXTransferOrderUnitServiceImpl implements WEB3AdminFXTransferOrderUnitService { /** * ログ出力ユーティリティ。<BR> */ private static WEB3LogUtility log = WEB3LogUtility.getInstance(WEB3AdminFXTransferOrderUnitServiceImpl.class); /** * @@roseuid 43FC2F9D029F */ public WEB3AdminFXTransferOrderUnitServiceImpl() { } /** * 振替注文処理を行う。 <BR> * <BR> * シーケンス図 <BR> * 「為替保証金(FX振替注文UL)振替注文」 参照<BR> * @@param l_fxTransferOrderUploadCsv - (FX振替注文アップロードCSV)<BR> * @@param l_intLineNumber - (行番号)<BR> * @@param l_strAdministratorCode - (管理者コード)<BR> * @@param l_institution - (証券会社)<BR> * @@param l_strPassword - (暗証番号)<BR> * @@return WEB3GenResponse * @@throws WEB3BaseException * @@roseuid 43D0AA9D030C */ public WEB3GenResponse execute( WEB3AdminFXTransferOrderUploadCsv l_fxTransferOrderUploadCsv, int l_intLineNumber, String l_strAdministratorCode, Institution l_institution, String l_strPassword) throws WEB3BaseException { final String STR_METHOD_NAME = " execute(WEB3AdminFXTransferUploadCsv, int, String, Institution, String)"; log.entering(STR_METHOD_NAME); if (l_fxTransferOrderUploadCsv == null || l_institution == null) { log.debug("パラメータ値不正。"); log.exiting(STR_METHOD_NAME); throw new WEB3SystemLayerException( WEB3ErrorCatalog.SYSTEM_ERROR_80017, this.getClass().getName() + "," + STR_METHOD_NAME, "パラメータ値不正。"); } //1.1 get発注日( ) Date l_datOrderBizDate = WEB3GentradeTradingTimeManagement.getOrderBizDate(); //1.2 get顧客(int) WEB3GentradeMainAccount l_mainAccount = l_fxTransferOrderUploadCsv.getMainAccount(l_intLineNumber); //lock口座(証券会社コード : String, 部店コード : //String, 口座コード : String) FinApp l_finApp = (FinApp)Services.getService(FinApp.class); WEB3GentradeAccountManager l_accManager = (WEB3GentradeAccountManager)l_finApp.getAccountManager(); String l_strInstitutionCode = l_institution.getInstitutionCode(); String l_strBranchCode = l_mainAccount.getBranch().getBranchCode(); String l_strAccountCode = l_mainAccount.getAccountCode(); l_accManager.lockAccount(l_strInstitutionCode, l_strBranchCode, l_strAccountCode); //getSubAccount(arg0 : SubAccountTypeEnum) SubAccount l_subAccount = null; try { l_subAccount = l_mainAccount.getSubAccount(SubAccountTypeEnum.EQUITY_SUB_ACCOUNT); } catch (NotFoundException l_ex) { log.error("テーブルに該当するデータがありません。", l_ex); log.exiting(STR_METHOD_NAME); throw new WEB3SystemLayerException( WEB3ErrorCatalog.SYSTEM_ERROR_80005, this.getClass().getName() + "." + STR_METHOD_NAME, l_ex.getMessage(), l_ex); } //1.5 get新規識別コード(証券会社コード : String, 部店コード : //String, 銘柄タイプ : ProductTypeEnum) WEB3HostReqOrderNumberManageService l_hostReqOrderNumMgrService = (WEB3HostReqOrderNumberManageService) Services.getService(WEB3HostReqOrderNumberManageService.class); String l_strNewNumber = l_hostReqOrderNumMgrService.getNewNumber( l_strInstitutionCode, l_strBranchCode, ProductTypeEnum.CASH); //1.6 get会社別FXシステム条件(証券会社コード : String, 部店コード : String) WEB3FXDataControlService l_dataControlService = (WEB3FXDataControlService) Services.getService(WEB3FXDataControlService.class); CompFxConditionParams l_compFxConditionParams = null; FxAccountParams l_fxAccountParams = null; FxAccountCodeParams l_fxAccountCodeParams = null; FxTransferMasterParams l_fxTransferMasterParams = null; try { l_compFxConditionParams = l_dataControlService.getCompFxCondition(l_strInstitutionCode, l_strBranchCode); //getFX振替条件マスタ(long, String) //FX振替条件マスタParams取得する。 //【引数】 //FXシステム条件ID @= 会社別FXシステム条件.FXシステム条件ID //振替区分 = 0:入金 l_fxTransferMasterParams = l_dataControlService.getFxTransferMasterParams( l_compFxConditionParams.getFxSystemId(), WEB3AioTransferDivDef.CASHIN); //1.7 getFX顧客(証券会社コード : String, 部店コード : //String, FXシステムコード : String, 顧客コード : String) l_fxAccountParams = l_dataControlService.getFXAccount( l_strInstitutionCode, l_strBranchCode, l_compFxConditionParams.getFxSystemCode(), l_strAccountCode); //1.8 getFX口座番号(証券会社コード : String, //部店コード : String, 顧客コード : String, コース区分 : String) l_fxAccountCodeParams = l_dataControlService.getFXAccountCode( l_strInstitutionCode, l_strBranchCode, l_strAccountCode, WEB3GftTransStatusCourseDivDef.ONE_COSE); } catch (NotFoundException l_ex) { log.error("テーブルに該当するデータがありません。", l_ex); log.exiting(STR_METHOD_NAME); throw new WEB3SystemLayerException( WEB3ErrorCatalog.SYSTEM_ERROR_80005, this.getClass().getName() + "." + STR_METHOD_NAME, l_ex.getMessage(), l_ex); } //1.9 GFT依頼電文明細( ) WEB3FXGftAskingTelegramUnit l_telUnit = new WEB3FXGftAskingTelegramUnit(); //1.10 (*)プロパティセット //(*)GFT依頼電文明細に必要なプロパティをセットする //(下記以外のプロパティは設定しない) //DIR→GFT送信日時 :現在時刻(システムタイムスタンプ) l_telUnit.dirSendTime = WEB3DateUtility.formatDate(GtlUtils.getSystemTimestamp(), "yyyyMMddHHmmss"); //処理区分 :02(入金) l_telUnit.gftOperationDiv = WEB3GftMessageOperationDef.CASH_IN; //為替保証金口座番号 :getFX口座番号()の戻り値 l_telUnit.fxAccountCode = l_fxAccountCodeParams.getFxAccountCode(); //初期ログインID:FX顧客Params.FXログインID l_telUnit.fxFirstLoginId = String.valueOf(l_fxAccountParams.getFxLoginId()); //担当区分:会社別FXシステム条件Params.担当区分 l_telUnit.groupName = l_compFxConditionParams.getGroupName(); //入出金額 :引数.アップロードCSV.get出金額(引数.行番号) double l_dblCashOutAmt = l_fxTransferOrderUploadCsv.getCashOutAmt(l_intLineNumber); l_telUnit.cashinoutAmt = WEB3StringTypeUtility.formatNumber(l_dblCashOutAmt); //会社コード:引数.証券会社.証券会社コード l_telUnit.institutionCode = l_strInstitutionCode; //部店コード:顧客から取得した部店コード l_telUnit.branchCode = l_strBranchCode; //顧客コード:顧客から取得した顧客コード l_telUnit.accountCode = l_strAccountCode; //識別コード:get新規識別コード()の戻り値 l_telUnit.requestNumber = l_strNewNumber; //1.11 createNewOrderId( ) WEB3AioOrderManager l_orderManager = (WEB3AioOrderManager) l_finApp.getTradingModule(ProductTypeEnum.AIO).getOrderManager(); long l_lngOrderId = l_orderManager.createNewOrderId(); //1.12 get商品ID(証券会社 : Institution) long l_lngProductId = l_orderManager.getProductId(l_institution); //is信用口座開設(弁済区分 : String) //弁済区分: @"0"(指定無し) boolean l_blnIsMarginAccountEstablished = l_mainAccount.isMarginAccountEstablished(WEB3GentradeRepaymentDivDef.DEFAULT); Date l_datPaymentDate = l_fxTransferOrderUploadCsv.getPaymentDate(l_intLineNumber); //暗証番号: @OpLoginSecurityServiceより、ログインタイプ属性を取得し、 OpLoginSecurityService l_securityService = (OpLoginSecurityService)Services.getService(OpLoginSecurityService.class); OpLoginAdminService l_adminService = (OpLoginAdminService)Services.getService(OpLoginAdminService.class); LoginInfo l_loginInfo = l_securityService.getLoginInfo(); Map l_mapAttributes = l_adminService.getLoginTypeAttributes(l_loginInfo.getLoginTypeId()); String l_strAttribute = (String)l_mapAttributes.get(WEB3LoginTypeAttributeKeyDef.TRADING_PWD_ENV); //・取引パスワード設定 == ”DEFAULT” の場合、引数.暗証番号 String l_strTradingPassword = null; if (WEB3TradingPwdEnvDef.DEFAULT.equals(l_strAttribute)) { l_strTradingPassword = l_strPassword; } //取引パスワード設定 == ”取引パスワード使用” の場合 else if (WEB3TradingPwdEnvDef.USE_TRADING_PWD.equals(l_strAttribute)) { //顧客.getTradingPassword()の戻り値をWEB3Crypt.decrypt()で復号したもの WEB3Crypt l_web3Crypt = new WEB3Crypt(); l_strTradingPassword = l_web3Crypt.decrypt(l_mainAccount.getTradingPassword()); } //顧客が信用口座を開設している(is信用口座開設()==TRUE)場合、処理を行う if (l_blnIsMarginAccountEstablished) { //発注日==出金日の場合、処理を行う //発注日 == 出金日(get発注日() == 引数.アップロードCSV.get出金日(引数.行番号))の場合、処理を行う int l_intCompareToDay = WEB3DateUtility.compareToDay(l_datOrderBizDate, l_datPaymentDate); if (l_intCompareToDay == 0) { //submit保証金振替(顧客, Date, double, String) //顧客: @get顧客()の戻り値 //受渡日: @引数.アップロードCSV.get出金日(引数.行番号) //入金額: @引数.アップロードCSV.get入出金額(引数.行番号) //暗証番号 //代理入力者: @null WEB3MarginTransferService l_marginTransferService = (WEB3MarginTransferService)Services.getService(WEB3MarginTransferService.class); l_marginTransferService.submitMarginTransfer( l_mainAccount, l_datPaymentDate, l_dblCashOutAmt, l_strTradingPassword, null); } } //1.13 入出金注文内容(代理入力者 : Trader, 注文種別 : OrderTypeEnum, //振替タイプ : AssetTransferTypeEnum, 商品ID : long, 金額 : double, //記述 : String, 振替予定日 : Date, 決済機@関ID : String, 注文ID : Long, //摘要コード: String, 摘要名: String) WEB3AioNewOrderSpec l_aioNewOrderSpec = new WEB3AioNewOrderSpec( null, l_fxTransferMasterParams.getOrderType(), AssetTransferTypeEnum.CASH_IN, l_lngProductId, l_dblCashOutAmt, null, l_datPaymentDate, null, null, l_fxTransferMasterParams.getRemarkCode(), l_fxTransferMasterParams.getRemarkName()); //1.14 FX振替注文更新インタセプタ(入出金注文内容 : 入出金注文内容) WEB3FXTransferOrderUpdateInterceptor l_orderUpdateInterceptor = new WEB3FXTransferOrderUpdateInterceptor(l_aioNewOrderSpec); //1.15 (*)プロパティセット //(*)以下のとおりにプロパティをセットする。 //発注日: @get発注日()の戻り値 l_orderUpdateInterceptor.setOrderBizDate(l_datOrderBizDate); //受渡日: @引数.アップロードCSV.get出金日(引数.行番号) l_orderUpdateInterceptor.setDeliveryDate(l_datPaymentDate); //識別コード: @get新規識別コード()の戻り値 l_orderUpdateInterceptor.setOrderRequestNumber(l_strNewNumber); //MQステータス: @1(送信済み) l_orderUpdateInterceptor.setMQStatus(WEB3MqStatusDef.MAIL_SENDED); //1.6 submit振替注文(補助口座 : SubAccount, 銘柄タイプ : ProductTypeEnum, //注文種別 : OrderTypeEnum, 注文内容 : NewOrderSpec, //インタセプタ : AioOrderManagerPersistenceInterceptor, //注文ID : long, パスワード : String) l_orderManager.submitTransferOrder( l_subAccount, ProductTypeEnum.CASH, l_fxTransferMasterParams.getOrderType(), l_aioNewOrderSpec, l_orderUpdateInterceptor, l_lngOrderId, l_strTradingPassword); //1.17 余力再計算(補助口座 : 補助口座) WEB3TPTradingPowerService l_tradingPowerService = (WEB3TPTradingPowerService) Services.getService(WEB3TPTradingPowerService.class); l_tradingPowerService.reCalcTradingPower((WEB3GentradeSubAccount) l_subAccount); //1.18 insertGFT振替状況(GFT依頼電文明細 : GFT依頼電文明細, //コース区分 : String, 受渡予定日 : String, //信用振替用識別コード : String, 入出金番号 : String, 入出金一覧取引区分: String) l_dataControlService.insertGFTTransferStatus( l_telUnit, WEB3GftTransStatusCourseDivDef.ONE_COSE, WEB3DateUtility.formatDate(l_datPaymentDate, "yyyyMMdd"), null, l_fxTransferOrderUploadCsv.getCashInOutNumber(l_intLineNumber), l_fxTransferMasterParams.getIoListTradeDiv()); log.exiting(STR_METHOD_NAME); return null; } } @
SHIFT_JIS
Java
18,348
java
WEB3AdminFXTransferOrderUnitServiceImpl.java
Java
[ { "context": "ment\t@// @;\n\n\n1.1\ndate\t2011.03.16.05.31.02;\tauthor zhang-tengyu;\tstate Exp;\nbranches;\nnext\t;\ndeltatype\ttext;\nkopt", "end": 108, "score": 0.990943431854248, "start": 96, "tag": "USERNAME", "value": "zhang-tengyu" }, { "context": "rceptor.TX_CREATE_NEW)を指定する。 <BR>\n * \n * @@author 鄭徳懇\n * @@version 1.0\n */\npublic class WEB3AdminFXTran", "end": 3499, "score": 0.9998617172241211, "start": 3496, "tag": "NAME", "value": "鄭徳懇" }, { "context": "ibute))\n {\n l_strTradingPassword = l_strPassword;\n }\n //取引パスワード設定 == ”取引パスワード使用” の場合\n ", "end": 11916, "score": 0.9931963086128235, "start": 11903, "tag": "PASSWORD", "value": "l_strPassword" } ]
null
[]
head 1.1; access; symbols; locks; strict; comment @// @; 1.1 date 2011.03.16.05.31.02; author zhang-tengyu; state Exp; branches; next ; deltatype text; kopt kv; permissions 666; commitid 8f04d80403d696d; filename WEB3AdminFXTransferOrderUnitServiceImpl.java; desc @@ 1.1 log @*** empty log message *** @ text @/** Copyright : (株)大和総研 証券ソリューションシステム第二部 File Name : FX振替注文UnitServiceImpl(WEB3AdminFXTransferOrderUnitServiceImpl.java) Author Name : Daiwa Institute of Research Revesion History : 2006/02/23 鄭徳懇(中訊) 新規作成 Revesion History : 2007/07/12 趙林鵬(中訊) モデルNo.733 Revesion History : 2007/07/28 孟亜南(中訊) 仕様変更モデル744 Revesion History : 2009/03/11 王志葵(中訊) 仕様変更モデル1115 */ package webbroker3.aio.service.delegate.stdimpls; import java.util.Date; import java.util.Map; import com.fitechlabs.xtrade.kernel.boot.Services; import com.fitechlabs.xtrade.plugin.security.oplogin.LoginInfo; import com.fitechlabs.xtrade.plugin.security.oplogin.OpLoginAdminService; import com.fitechlabs.xtrade.plugin.security.oplogin.OpLoginSecurityService; import com.fitechlabs.xtrade.plugin.tc.gentrade.FinApp; import com.fitechlabs.xtrade.plugin.tc.gentrade.GtlUtils; import com.fitechlabs.xtrade.plugin.tc.gentrade.Institution; import com.fitechlabs.xtrade.plugin.tc.gentrade.NotFoundException; import com.fitechlabs.xtrade.plugin.tc.gentrade.ProductTypeEnum; import com.fitechlabs.xtrade.plugin.tc.gentrade.SubAccount; import com.fitechlabs.xtrade.plugin.tc.gentrade.SubAccountTypeEnum; import com.fitechlabs.xtrade.plugin.tc.xbaio.AssetTransferTypeEnum; import webbroker3.aio.WEB3AdminFXTransferOrderUploadCsv; import webbroker3.aio.WEB3AioNewOrderSpec; import webbroker3.aio.WEB3AioOrderManager; import webbroker3.aio.WEB3FXDataControlService; import webbroker3.aio.WEB3FXTransferOrderUpdateInterceptor; import webbroker3.aio.data.CompFxConditionParams; import webbroker3.aio.data.FxAccountCodeParams; import webbroker3.aio.data.FxAccountParams; import webbroker3.aio.data.FxTransferMasterParams; import webbroker3.aio.message.WEB3FXGftAskingTelegramUnit; import webbroker3.aio.service.delegate.WEB3AdminFXTransferOrderUnitService; import webbroker3.aio.service.delegate.WEB3MarginTransferService; import webbroker3.common.WEB3BaseException; import webbroker3.common.WEB3Crypt; import webbroker3.common.WEB3ErrorCatalog; import webbroker3.common.WEB3SystemLayerException; import webbroker3.common.define.WEB3AioTransferDivDef; import webbroker3.common.define.WEB3GftMessageOperationDef; import webbroker3.common.define.WEB3GftTransStatusCourseDivDef; import webbroker3.common.define.WEB3LoginTypeAttributeKeyDef; import webbroker3.common.define.WEB3MqStatusDef; import webbroker3.common.define.WEB3TradingPwdEnvDef; import webbroker3.common.message.WEB3GenResponse; import webbroker3.gentrade.WEB3GentradeAccountManager; import webbroker3.gentrade.WEB3GentradeMainAccount; import webbroker3.gentrade.WEB3GentradeSubAccount; import webbroker3.gentrade.WEB3GentradeTradingTimeManagement; import webbroker3.gentrade.WEB3HostReqOrderNumberManageService; import webbroker3.gentrade.define.WEB3GentradeRepaymentDivDef; import webbroker3.tradingpower.WEB3TPTradingPowerService; import webbroker3.util.WEB3DateUtility; import webbroker3.util.WEB3LogUtility; import webbroker3.util.WEB3StringTypeUtility; /** * (FX振替注文UnitServiceImpl)<BR> * FX振替注文UnitService実装クラス<BR> * <BR> * Plugin時に自動トランザクションTransactionalInterceptor<BR> * (TransactionalInterceptor.TX_CREATE_NEW)を指定する。 <BR> * * @@author 鄭徳懇 * @@version 1.0 */ public class WEB3AdminFXTransferOrderUnitServiceImpl implements WEB3AdminFXTransferOrderUnitService { /** * ログ出力ユーティリティ。<BR> */ private static WEB3LogUtility log = WEB3LogUtility.getInstance(WEB3AdminFXTransferOrderUnitServiceImpl.class); /** * @@roseuid 43FC2F9D029F */ public WEB3AdminFXTransferOrderUnitServiceImpl() { } /** * 振替注文処理を行う。 <BR> * <BR> * シーケンス図 <BR> * 「為替保証金(FX振替注文UL)振替注文」 参照<BR> * @@param l_fxTransferOrderUploadCsv - (FX振替注文アップロードCSV)<BR> * @@param l_intLineNumber - (行番号)<BR> * @@param l_strAdministratorCode - (管理者コード)<BR> * @@param l_institution - (証券会社)<BR> * @@param l_strPassword - (暗証番号)<BR> * @@return WEB3GenResponse * @@throws WEB3BaseException * @@roseuid 43D0AA9D030C */ public WEB3GenResponse execute( WEB3AdminFXTransferOrderUploadCsv l_fxTransferOrderUploadCsv, int l_intLineNumber, String l_strAdministratorCode, Institution l_institution, String l_strPassword) throws WEB3BaseException { final String STR_METHOD_NAME = " execute(WEB3AdminFXTransferUploadCsv, int, String, Institution, String)"; log.entering(STR_METHOD_NAME); if (l_fxTransferOrderUploadCsv == null || l_institution == null) { log.debug("パラメータ値不正。"); log.exiting(STR_METHOD_NAME); throw new WEB3SystemLayerException( WEB3ErrorCatalog.SYSTEM_ERROR_80017, this.getClass().getName() + "," + STR_METHOD_NAME, "パラメータ値不正。"); } //1.1 get発注日( ) Date l_datOrderBizDate = WEB3GentradeTradingTimeManagement.getOrderBizDate(); //1.2 get顧客(int) WEB3GentradeMainAccount l_mainAccount = l_fxTransferOrderUploadCsv.getMainAccount(l_intLineNumber); //lock口座(証券会社コード : String, 部店コード : //String, 口座コード : String) FinApp l_finApp = (FinApp)Services.getService(FinApp.class); WEB3GentradeAccountManager l_accManager = (WEB3GentradeAccountManager)l_finApp.getAccountManager(); String l_strInstitutionCode = l_institution.getInstitutionCode(); String l_strBranchCode = l_mainAccount.getBranch().getBranchCode(); String l_strAccountCode = l_mainAccount.getAccountCode(); l_accManager.lockAccount(l_strInstitutionCode, l_strBranchCode, l_strAccountCode); //getSubAccount(arg0 : SubAccountTypeEnum) SubAccount l_subAccount = null; try { l_subAccount = l_mainAccount.getSubAccount(SubAccountTypeEnum.EQUITY_SUB_ACCOUNT); } catch (NotFoundException l_ex) { log.error("テーブルに該当するデータがありません。", l_ex); log.exiting(STR_METHOD_NAME); throw new WEB3SystemLayerException( WEB3ErrorCatalog.SYSTEM_ERROR_80005, this.getClass().getName() + "." + STR_METHOD_NAME, l_ex.getMessage(), l_ex); } //1.5 get新規識別コード(証券会社コード : String, 部店コード : //String, 銘柄タイプ : ProductTypeEnum) WEB3HostReqOrderNumberManageService l_hostReqOrderNumMgrService = (WEB3HostReqOrderNumberManageService) Services.getService(WEB3HostReqOrderNumberManageService.class); String l_strNewNumber = l_hostReqOrderNumMgrService.getNewNumber( l_strInstitutionCode, l_strBranchCode, ProductTypeEnum.CASH); //1.6 get会社別FXシステム条件(証券会社コード : String, 部店コード : String) WEB3FXDataControlService l_dataControlService = (WEB3FXDataControlService) Services.getService(WEB3FXDataControlService.class); CompFxConditionParams l_compFxConditionParams = null; FxAccountParams l_fxAccountParams = null; FxAccountCodeParams l_fxAccountCodeParams = null; FxTransferMasterParams l_fxTransferMasterParams = null; try { l_compFxConditionParams = l_dataControlService.getCompFxCondition(l_strInstitutionCode, l_strBranchCode); //getFX振替条件マスタ(long, String) //FX振替条件マスタParams取得する。 //【引数】 //FXシステム条件ID @= 会社別FXシステム条件.FXシステム条件ID //振替区分 = 0:入金 l_fxTransferMasterParams = l_dataControlService.getFxTransferMasterParams( l_compFxConditionParams.getFxSystemId(), WEB3AioTransferDivDef.CASHIN); //1.7 getFX顧客(証券会社コード : String, 部店コード : //String, FXシステムコード : String, 顧客コード : String) l_fxAccountParams = l_dataControlService.getFXAccount( l_strInstitutionCode, l_strBranchCode, l_compFxConditionParams.getFxSystemCode(), l_strAccountCode); //1.8 getFX口座番号(証券会社コード : String, //部店コード : String, 顧客コード : String, コース区分 : String) l_fxAccountCodeParams = l_dataControlService.getFXAccountCode( l_strInstitutionCode, l_strBranchCode, l_strAccountCode, WEB3GftTransStatusCourseDivDef.ONE_COSE); } catch (NotFoundException l_ex) { log.error("テーブルに該当するデータがありません。", l_ex); log.exiting(STR_METHOD_NAME); throw new WEB3SystemLayerException( WEB3ErrorCatalog.SYSTEM_ERROR_80005, this.getClass().getName() + "." + STR_METHOD_NAME, l_ex.getMessage(), l_ex); } //1.9 GFT依頼電文明細( ) WEB3FXGftAskingTelegramUnit l_telUnit = new WEB3FXGftAskingTelegramUnit(); //1.10 (*)プロパティセット //(*)GFT依頼電文明細に必要なプロパティをセットする //(下記以外のプロパティは設定しない) //DIR→GFT送信日時 :現在時刻(システムタイムスタンプ) l_telUnit.dirSendTime = WEB3DateUtility.formatDate(GtlUtils.getSystemTimestamp(), "yyyyMMddHHmmss"); //処理区分 :02(入金) l_telUnit.gftOperationDiv = WEB3GftMessageOperationDef.CASH_IN; //為替保証金口座番号 :getFX口座番号()の戻り値 l_telUnit.fxAccountCode = l_fxAccountCodeParams.getFxAccountCode(); //初期ログインID:FX顧客Params.FXログインID l_telUnit.fxFirstLoginId = String.valueOf(l_fxAccountParams.getFxLoginId()); //担当区分:会社別FXシステム条件Params.担当区分 l_telUnit.groupName = l_compFxConditionParams.getGroupName(); //入出金額 :引数.アップロードCSV.get出金額(引数.行番号) double l_dblCashOutAmt = l_fxTransferOrderUploadCsv.getCashOutAmt(l_intLineNumber); l_telUnit.cashinoutAmt = WEB3StringTypeUtility.formatNumber(l_dblCashOutAmt); //会社コード:引数.証券会社.証券会社コード l_telUnit.institutionCode = l_strInstitutionCode; //部店コード:顧客から取得した部店コード l_telUnit.branchCode = l_strBranchCode; //顧客コード:顧客から取得した顧客コード l_telUnit.accountCode = l_strAccountCode; //識別コード:get新規識別コード()の戻り値 l_telUnit.requestNumber = l_strNewNumber; //1.11 createNewOrderId( ) WEB3AioOrderManager l_orderManager = (WEB3AioOrderManager) l_finApp.getTradingModule(ProductTypeEnum.AIO).getOrderManager(); long l_lngOrderId = l_orderManager.createNewOrderId(); //1.12 get商品ID(証券会社 : Institution) long l_lngProductId = l_orderManager.getProductId(l_institution); //is信用口座開設(弁済区分 : String) //弁済区分: @"0"(指定無し) boolean l_blnIsMarginAccountEstablished = l_mainAccount.isMarginAccountEstablished(WEB3GentradeRepaymentDivDef.DEFAULT); Date l_datPaymentDate = l_fxTransferOrderUploadCsv.getPaymentDate(l_intLineNumber); //暗証番号: @OpLoginSecurityServiceより、ログインタイプ属性を取得し、 OpLoginSecurityService l_securityService = (OpLoginSecurityService)Services.getService(OpLoginSecurityService.class); OpLoginAdminService l_adminService = (OpLoginAdminService)Services.getService(OpLoginAdminService.class); LoginInfo l_loginInfo = l_securityService.getLoginInfo(); Map l_mapAttributes = l_adminService.getLoginTypeAttributes(l_loginInfo.getLoginTypeId()); String l_strAttribute = (String)l_mapAttributes.get(WEB3LoginTypeAttributeKeyDef.TRADING_PWD_ENV); //・取引パスワード設定 == ”DEFAULT” の場合、引数.暗証番号 String l_strTradingPassword = null; if (WEB3TradingPwdEnvDef.DEFAULT.equals(l_strAttribute)) { l_strTradingPassword = <PASSWORD>; } //取引パスワード設定 == ”取引パスワード使用” の場合 else if (WEB3TradingPwdEnvDef.USE_TRADING_PWD.equals(l_strAttribute)) { //顧客.getTradingPassword()の戻り値をWEB3Crypt.decrypt()で復号したもの WEB3Crypt l_web3Crypt = new WEB3Crypt(); l_strTradingPassword = l_web3Crypt.decrypt(l_mainAccount.getTradingPassword()); } //顧客が信用口座を開設している(is信用口座開設()==TRUE)場合、処理を行う if (l_blnIsMarginAccountEstablished) { //発注日==出金日の場合、処理を行う //発注日 == 出金日(get発注日() == 引数.アップロードCSV.get出金日(引数.行番号))の場合、処理を行う int l_intCompareToDay = WEB3DateUtility.compareToDay(l_datOrderBizDate, l_datPaymentDate); if (l_intCompareToDay == 0) { //submit保証金振替(顧客, Date, double, String) //顧客: @get顧客()の戻り値 //受渡日: @引数.アップロードCSV.get出金日(引数.行番号) //入金額: @引数.アップロードCSV.get入出金額(引数.行番号) //暗証番号 //代理入力者: @null WEB3MarginTransferService l_marginTransferService = (WEB3MarginTransferService)Services.getService(WEB3MarginTransferService.class); l_marginTransferService.submitMarginTransfer( l_mainAccount, l_datPaymentDate, l_dblCashOutAmt, l_strTradingPassword, null); } } //1.13 入出金注文内容(代理入力者 : Trader, 注文種別 : OrderTypeEnum, //振替タイプ : AssetTransferTypeEnum, 商品ID : long, 金額 : double, //記述 : String, 振替予定日 : Date, 決済機@関ID : String, 注文ID : Long, //摘要コード: String, 摘要名: String) WEB3AioNewOrderSpec l_aioNewOrderSpec = new WEB3AioNewOrderSpec( null, l_fxTransferMasterParams.getOrderType(), AssetTransferTypeEnum.CASH_IN, l_lngProductId, l_dblCashOutAmt, null, l_datPaymentDate, null, null, l_fxTransferMasterParams.getRemarkCode(), l_fxTransferMasterParams.getRemarkName()); //1.14 FX振替注文更新インタセプタ(入出金注文内容 : 入出金注文内容) WEB3FXTransferOrderUpdateInterceptor l_orderUpdateInterceptor = new WEB3FXTransferOrderUpdateInterceptor(l_aioNewOrderSpec); //1.15 (*)プロパティセット //(*)以下のとおりにプロパティをセットする。 //発注日: @get発注日()の戻り値 l_orderUpdateInterceptor.setOrderBizDate(l_datOrderBizDate); //受渡日: @引数.アップロードCSV.get出金日(引数.行番号) l_orderUpdateInterceptor.setDeliveryDate(l_datPaymentDate); //識別コード: @get新規識別コード()の戻り値 l_orderUpdateInterceptor.setOrderRequestNumber(l_strNewNumber); //MQステータス: @1(送信済み) l_orderUpdateInterceptor.setMQStatus(WEB3MqStatusDef.MAIL_SENDED); //1.6 submit振替注文(補助口座 : SubAccount, 銘柄タイプ : ProductTypeEnum, //注文種別 : OrderTypeEnum, 注文内容 : NewOrderSpec, //インタセプタ : AioOrderManagerPersistenceInterceptor, //注文ID : long, パスワード : String) l_orderManager.submitTransferOrder( l_subAccount, ProductTypeEnum.CASH, l_fxTransferMasterParams.getOrderType(), l_aioNewOrderSpec, l_orderUpdateInterceptor, l_lngOrderId, l_strTradingPassword); //1.17 余力再計算(補助口座 : 補助口座) WEB3TPTradingPowerService l_tradingPowerService = (WEB3TPTradingPowerService) Services.getService(WEB3TPTradingPowerService.class); l_tradingPowerService.reCalcTradingPower((WEB3GentradeSubAccount) l_subAccount); //1.18 insertGFT振替状況(GFT依頼電文明細 : GFT依頼電文明細, //コース区分 : String, 受渡予定日 : String, //信用振替用識別コード : String, 入出金番号 : String, 入出金一覧取引区分: String) l_dataControlService.insertGFTTransferStatus( l_telUnit, WEB3GftTransStatusCourseDivDef.ONE_COSE, WEB3DateUtility.formatDate(l_datPaymentDate, "yyyyMMdd"), null, l_fxTransferOrderUploadCsv.getCashInOutNumber(l_intLineNumber), l_fxTransferMasterParams.getIoListTradeDiv()); log.exiting(STR_METHOD_NAME); return null; } } @
18,345
0.678166
0.660699
413
37.81356
26.586906
113
false
false
0
0
0
0
0
0
0.595642
false
false
5
1772ad4d4eb84abff6d92e1aa7a348dd34114743
16,690,242,964,659
df41c9d61b4ae6f6423f7b0f21bf446b0a37a0c9
/testdata/translation/stmts/BasicArithmetic.java
93081ba93d9448fe9b51ce7d8c6a7ab0efea7861
[ "BSD-3-Clause" ]
permissive
mhaeuser/NQJ-compiler
https://github.com/mhaeuser/NQJ-compiler
c3141f45430ace8eb4ac579c542abd1fb65f2bea
49785ec72b3c98a105550510bbfa03483789b517
refs/heads/master
2023-03-23T20:34:21.246000
2021-03-21T16:26:01
2021-03-21T17:05:54
350,054,286
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
int main() { printInt(2 + 5); printInt(2 - 5); printInt(-2 + 5); printInt(2 * 5); return 0; }
UTF-8
Java
103
java
BasicArithmetic.java
Java
[]
null
[]
int main() { printInt(2 + 5); printInt(2 - 5); printInt(-2 + 5); printInt(2 * 5); return 0; }
103
0.524272
0.436893
7
13.857142
6.033918
19
true
false
0
0
0
0
0
0
2.142857
false
false
5
c003abeb1fb32df34ff77aff95982eae36796deb
25,125,558,737,207
1c9f5ac52352ff82671e01440d1add4cdfbf79a0
/src/main/java/com/smolenskyi/service/EbmService.java
516e8a782824a2431c88190821dc9dc37a918afe
[]
no_license
oleksii-smolenskyi/lagermanager
https://github.com/oleksii-smolenskyi/lagermanager
a5f4523938665a96743d54eecb5c4a09de0cc7fa
d978ba145f5ede7dd401295e9a1dc2e45ff3e9cc
refs/heads/master
2020-09-15T10:29:49.507000
2020-09-09T08:36:20
2020-09-09T08:36:20
223,421,220
0
0
null
false
2020-02-21T18:16:52
2019-11-22T14:32:23
2020-02-21T18:16:26
2020-02-21T18:16:51
542
0
0
2
Java
false
false
package com.smolenskyi.service; import com.smolenskyi.exeptions.NoDataFoundException; import com.smolenskyi.model.ebm.Ebm; import com.smolenskyi.model.ebm.EbmFilterType; import com.smolenskyi.model.ebm.EbmPosition; import com.smolenskyi.model.ebm.EbmSortType; import com.smolenskyi.model.part.Part; import com.smolenskyi.repository.EbmRepository; import com.smolenskyi.util.EbmUtil; import com.smolenskyi.util.SecurityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.xml.bind.ValidationException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.util.*; // Сервіс замовлень @Service @Transactional(readOnly = true) public class EbmService { private static final Logger log = LoggerFactory.getLogger(EbmService.class); // репозиторій замовлень @Autowired private EbmRepository repository; // репозиторій запчастин @Autowired private PartService partService; /** * Повертає замовлення по локації з ідентифікатором locationId, які відповідають пошуковій фразі search, * відсортовані згідно типу сортування sortType, та відфільтровані згідно фільтру filterType. * * @param locationId - ідентифікатор локації, до якої відносяться замовлення. * @param search - пошукова фраза. * @param sortType - тип сортування, об'Єкт перечислення EbmSortType. * @param filterType - тип фільтрування, об'єкт перечислення EbmFilterType. * @return - список замовлень. */ public List<Ebm> getAll(int locationId, String search, EbmSortType sortType, EbmFilterType filterType) { System.out.println(repository.getAll(locationId, search, sortType, filterType)); return repository.getAll(locationId, search, sortType, filterType); } /** * Видаляє замовлення за ідентифікатором. * * @param id - ідентифікатор замовлення. * @return - true - якщо замовлення видалено успішно, false - якщо замовлення не вдалося видалити. */ @Transactional public boolean delete(int id) { Ebm ebm = get(id); if (ebm != null) { for (EbmPosition ebmPosition : ebm.getPositions()) { if (ebmPosition.getDateOfReceived() != null) throw new RuntimeException("Неможливо видалити замовлення з виконаними позиціями."); } } return repository.delete(id); } /** * Повертає замволення по ідентифікатору. * * @param id - ідентифікатор замовлення. * @return - об'єкт Ebm, або null, якщо замовлення за таким ідентифікатором не знайдено. */ public Ebm get(int id) { return repository.get(id); } /** * Метод збереження нового замовлення. Передає об'єкт замовлення для збереження в репозиторій. */ @Transactional public Ebm create(String ebmNr, // номер замовлення String supplier, // постачальник String comment, // коментар до замовлення Integer[] selectedPart, // ідентифікатори запчастини в базі Integer[] count, // кількість запчастин в позиції Double[] price, // кількість запчастин в позиції MultipartFile[] files) throws ValidationException { Ebm ebm = new Ebm(); ebm.setEbmNr(ebmNr); ebm.setSupplier(supplier); ebm.setDateStartOrder(LocalDate.now()); ebm.setOwner(SecurityUtil.getAuthUser()); ebm.setComment(comment); ebm.setPositions(parseEbmPositionsForNewEbm(selectedPart, count, price)); try { ebm.setFiles(uploadFiles(LocalDate.now(), files)); } catch (IOException e) { log.debug(e.getMessage()); } log.debug("create new ebm: " + ebm); return repository.save(ebm); } // Будує список позицій з набору масивів для нового замовлення List<EbmPosition> parseEbmPositionsForNewEbm(Integer[] selectedPart, // ідентифікатори запчастини в базі Integer[] count, // кількість запчастин в позиції Double[] price) throws ValidationException { // чи завчастини в сток чи в комірку log.debug("Parsing ebm positions. Input data -> " + "\n\t parts: " + Arrays.toString(selectedPart) + "\n\t count: " + Arrays.toString(count) + "\n\t price: " + Arrays.toString(price)); List<EbmPosition> parsedPositions = new ArrayList<>(); // перевірка вхідних масивів на одинакову кількість елементів. if (selectedPart == null) return new ArrayList<>(); if ((selectedPart == null || count == null || price == null) || (selectedPart.length != count.length || selectedPart.length != price.length)) { throw new ValidationException("Не правильний формат форми. Спробуйте ще раз."); } // прохід по всіх елементах масивів for (int i = 0; i < selectedPart.length; i++) { EbmPosition currentPosition = new EbmPosition(); Part currentPart = selectedPart[i] == null ? null : partService.get(selectedPart[i]); currentPosition.setPart(currentPart); currentPosition.setCount(count[i]); currentPosition.setPrice(price[i]); parsedPositions.add(currentPosition); } return parsedPositions; } /** * Update present order. * * @param id - ідентифікатор замовлення * @param ebmNr - номер замовлення * @param supplier - постачальник * @param comment - коментар до замовлення * @param positionid - масив ідентифікаторів позицій * @param selectedPart - масив ідентифікаторів обраних запчастин * @param count - масив кількостей запчастин в позиціях * @param price - ціна позицій * @param dateOfRecived - масив дат приходу позицій * @param toStock - масив прапорців чи позиції прибули в склад чи в комірку - 0 - в комірку; 1 - в складззззззззззззззз * @param files - список прикріплених файлів */ @Transactional public Ebm update(Integer id, String ebmNr, String supplier, String comment, Integer[] positionid, Integer[] selectedPart, Integer[] count, Double[] price, String[] dateOfRecived, Integer[] toStock, MultipartFile[] files) throws ValidationException { if (id == null) throw new ValidationException("Неможливо оновити замовлення. Такого замовлення не існує."); Ebm ebm = get(id); if (ebm == null) throw new ValidationException("Неможливо оновити замовлення. Такого замовлення не існує."); if (ebm.getOwner().getLocation().getId() != SecurityUtil.getAuthUser().getLocation().getId()) throw new RuntimeException("Неможливо оновити замовлення іншої локації."); ebm.setEbmNr(ebmNr); ebm.setSupplier(supplier); ebm.setComment(comment); List<EbmPosition> incomingEbmPositionList = parseEbmPositionsForEbm(positionid, selectedPart, count, price, dateOfRecived, toStock); // додаємо нові позиції в замовлення і апдейтим існуючі for (EbmPosition ebmPosition : incomingEbmPositionList) { if (ebmPosition.isNew()) { ebm.addPosition(ebmPosition); log.debug("add new position to ebm[" + ebm.getId() + "]: " + ebmPosition); } else { EbmPosition posFromDB = ebm.getPositions().get(ebm.getPositions().indexOf(ebmPosition)); if (posFromDB != null && posFromDB.getDateOfReceived() == null) { posFromDB.setPart(ebmPosition.getPart()); posFromDB.setCount(ebmPosition.getCount()); posFromDB.setPrice(ebmPosition.getPrice()); if (Objects.nonNull(ebmPosition.getDateOfReceived()) && Objects.isNull(posFromDB.getDateOfReceived())) { // якщо замовлення прийшло Part part = partService.get(ebmPosition.getPart().getId()); if (part == null) throw new NoDataFoundException("Не знайдено запчастини."); if (ebmPosition.isArrivedToStock()) { // якщо запчастини прийли в склад part.setStockCount(part.getStockCount() + ebmPosition.getCount()); } else { // якщо запчастини прийли в нумеровану комірку part.setCount(part.getCount() + ebmPosition.getCount()); } posFromDB.setDateOfReceived(ebmPosition.getDateOfReceived()); posFromDB.setArrivedToStock(ebmPosition.isArrivedToStock()); partService.update(part); } } } } try { ebm.getFiles().addAll(uploadFiles(ebm.getDateStartOrder(), files)); } catch (IOException e) { e.printStackTrace(); } removeDeletedPositionsFromEbm(ebm, incomingEbmPositionList); log.debug("save ebm to repository: " + ebm.toString()); return repository.save(ebm); } /** * Remove deleted positions from ebm. * * @param ebm - order * @param incomingEbmPositionList - list of incoming positions */ @Transactional void removeDeletedPositionsFromEbm(Ebm ebm, List<EbmPosition> incomingEbmPositionList) { // видаляємо видалені позиції List<EbmPosition> positionsForRemoving = new ArrayList<>(); Iterator<EbmPosition> iterator = ebm.getPositions().iterator(); while (iterator.hasNext()) { EbmPosition ebmPosition = iterator.next(); if (!ebmPosition.isNew() && incomingEbmPositionList.indexOf(ebmPosition) < 0) { positionsForRemoving.add(ebmPosition); } } for (EbmPosition position : positionsForRemoving) { ebm.removePosition(position); } } // Будує список позицій з набору масивів для існуючого замовлення List<EbmPosition> parseEbmPositionsForEbm(Integer[] positionId, // ідентифікатор позиції Integer[] selectedPart, // ідентифікатори запчастини в базі Integer[] count, // кількість запчастин в позиції Double[] price, // вартість позиції String[] dateOfRecived, // дата прибуття Integer[] toStock // прапорець чи позиція прибула в склад чи в комірку ) throws ValidationException { log.debug("Parsing ebm positions. Input data -> " + "\n\t positionId: " + Arrays.toString(positionId) + "\n\t parts: " + Arrays.toString(selectedPart) + "\n\t count: " + Arrays.toString(count) + "\n\t price: " + Arrays.toString(price) + "\n\t dateOfRecived: " + Arrays.toString(dateOfRecived) + "\n\t toStock: " + Arrays.toString(toStock)); List<EbmPosition> parsedPositions = new ArrayList<>(); // перевірка вхідних масивів на одинакову кількість елементів. if (selectedPart == null || selectedPart.length == 0) return new ArrayList<>(); if ((positionId == null || selectedPart == null || count == null || price == null || dateOfRecived == null || toStock == null) || (selectedPart.length != positionId.length || count.length != positionId.length || price.length != positionId.length || dateOfRecived.length != positionId.length || toStock.length != positionId.length)) { throw new ValidationException("Не правильний формат форми. Спробуйте ще раз."); } // прохід по всіх елементах масивів for (int i = 0; i < positionId.length; i++) { EbmPosition currentPosition = new EbmPosition(); currentPosition.setId(positionId[i]); Part currentPart = selectedPart[i] == null ? null : partService.get(selectedPart[i]); currentPosition.setPart(currentPart); currentPosition.setCount(count[i]); currentPosition.setPrice(price[i]); LocalDate positionDateRecived = null; try { positionDateRecived = dateOfRecived[i] != null ? LocalDate.parse(dateOfRecived[i]) : null; } catch (RuntimeException re) { } currentPosition.setDateOfReceived(positionDateRecived); int currentToStock = 0; if (toStock[i] != null && toStock[i] == 1) currentToStock = 1; currentPosition.setArrivedToStock(currentToStock == 1); parsedPositions.add(currentPosition); } log.debug("parsed positions: " + parsedPositions); return parsedPositions; } /** * Метод оновлення існуючого замовлення. Передає замовлення в репозиторій для оновлення в базі даних. * Оновлює дані кількостей в складі запчастин, якщо позиції прибули, або відбувається відміна прибуття позицій. * * @param ebm - об'єкт оновленого замовлення, яке потрібно оновити в базі даних. */ @Transactional public Ebm update(Ebm ebm) { Ebm ebmFromDB = get(ebm.getId()); // отрмуєм замовлення з бази даних на основі ідентифікатора вхідного замовлення(об'єкт якого ми намагаємся зберегти в базу даних) if (ebm.getFiles() != null) { ebm.getFiles().addAll(ebmFromDB.getFiles()); } else { ebm.setFiles(ebmFromDB.getFiles()); } for (EbmPosition positionFromDB : ebmFromDB.getPositions()) { // здійснюєм прохід по позиціям, для опрацювання руху кількостей запчастин if (EbmRepository.isPresentInListWithSuchId(ebm.getPositions(), positionFromDB) >= 0) { // якщо позиція існує вже в замовленні. інакше вона нова, і кількості не потрібно нікуди враховувати for (EbmPosition ebmPosition : ebm.getPositions()) { // прохід по позиціям вхідного об'єкту замовлення if (Objects.nonNull(positionFromDB.getId()) && positionFromDB.getId().equals(ebmPosition.getId())) { // якщо ідентифікатор позиції з бази і ідентифікатор вхідної позиції збігаються if (Objects.nonNull(ebmPosition.getDateOfReceived()) && Objects.isNull(positionFromDB.getDateOfReceived())) { // якщо замовлення прийшло Part part = partService.get(ebmPosition.getPart().getId()); if (part == null) throw new NoDataFoundException("Не знайдено запчастини."); if (ebmPosition.isArrivedToStock()) // якщо запчастини прийли в склад part.setStockCount(part.getStockCount() + ebmPosition.getCount()); else // якщо запчастини прийли в нумеровану комірку part.setCount(part.getCount() + ebmPosition.getCount()); partService.update(part); } if (Objects.isNull(ebmPosition.getDateOfReceived()) && Objects.nonNull(positionFromDB.getDateOfReceived())) { // якщо відміна приходу позиції Part part = partService.get(ebmPosition.getPart().getId()); if (part == null) throw new NoDataFoundException("Не знайдено запчастини."); if (positionFromDB.isArrivedToStock()) // якщо запчастини прийли в склад if ((part.getStockCount() - ebmPosition.getCount()) >= 0) part.setStockCount(part.getStockCount() - ebmPosition.getCount()); else throw new RuntimeException("Відсутня достатня кількість в складі."); else // якщо запчастини прийли в нумеровану комірку if ((part.getCount() - ebmPosition.getCount()) >= 0) part.setCount(part.getCount() - ebmPosition.getCount()); else throw new RuntimeException("Відсутня достатня кількість в комірці."); partService.update(part); } } } } } ebm.setPositions(EbmUtil.mergeEbmPositionsGroupByPartThatDidNotArrive(ebm.getPositions())); return repository.save(ebm); // зберігаєм замовлення в базу } /** * @param ebmId * @param positionid * @param selectedPart * @param count * @param dateOfReceived * @param toStock * @return * @throws ValidationException */ @Transactional public Ebm updateOnlyEbmPositions(Integer ebmId, String[] positionid, // ідентифікатори позицій в базі String[] selectedPart, // ідентифікатори запчастини в базі String[] count, // кількість запчастин в позиції String[] dateOfReceived, // кількість запчастин в позиції Integer[] toStock) throws ValidationException { List<Integer> comingPosIdsToStosk; // створюємо список з ідентифікаторами позицій, що зачислюються в склад if (Objects.nonNull(toStock)) comingPosIdsToStosk = Arrays.asList(toStock); // створюємо список ідентифікаторів позицій, які попадають в склад else comingPosIdsToStosk = new ArrayList<>(); // перевірка вхідних масивів на одинакову кількість елементів. if (selectedPart.length != count.length) { throw new ValidationException("Не правильний формат форми. Спробуйте ще раз."); } Ebm currentEbm = get(ebmId); // отримуєм замовлення з БД // прохід по всіх елементах масивів for (int i = 0; i < count.length; i++) { int positionIdItem; // номер позиції int countItem; // замовлена кількість try { // парсим значення з масивів if (positionid[i].startsWith("#")) { // якщо позиція нова, створена в результаті розбиття позиції. continue; // пропускаємо нові позиції, їх будемо створювати при обробці існуючих } else { positionIdItem = Integer.parseInt(positionid[i]); EbmPosition ebmPosition = currentEbm.getPositions().get(EbmRepository.getIndexInPositionsListByPositionId(currentEbm.getPositions(), positionIdItem)); // берем позицію з замовлення countItem = Integer.parseInt(count[i].substring(0, count[i].indexOf(" "))); // вхідна стрічка кількості у вигляді ( 500 pcs.), вирізаємо лише числове значення if (ebmPosition.getCount() > countItem && dateOfReceived[i] != null) { // якщо в існуючій позиції в БД кількість більша ніж в оновленій int newPositionCount = ebmPosition.getCount() - countItem; double newPositionPrice = ((int) (ebmPosition.getPrice() / ebmPosition.getCount() * newPositionCount * 100)) / 100.0; EbmPosition newPosition = new EbmPosition(ebmPosition.getPart(), newPositionCount, newPositionPrice); // створюємо нову позицію // newPosition.setEbm(currentEbm); currentEbm.getPositions().add(newPosition); ebmPosition.setCount(ebmPosition.getCount() - newPositionCount); ebmPosition.setPrice(ebmPosition.getPrice() - newPositionPrice); } if (ebmPosition.getDateOfReceived() == null && dateOfReceived[i] != null && !dateOfReceived[i].equals("")) { // якщо вказана дата приходу ebmPosition.setDateOfReceived(LocalDate.parse(dateOfReceived[i])); // задаєм дату приходу if (comingPosIdsToStosk.contains(ebmPosition.getId())) { // якщо позиція по приходу попадає в склад а не в нумеровану комірку ebmPosition.setArrivedToStock(true); } } } } catch (NumberFormatException nfe) { // перехоплюємо вийняток, що може відбутися під час парсингу чисел throw new RuntimeException("Не правильний формат форми. Спробуйте ще раз."); } } log.debug("updating ebm: " + currentEbm); return repository.save(currentEbm); } /** * Метод відміни приходу позиції на склад. * Витягує замовлення з БД за ідентифікатором ebmId. Перевіряє чи в замовлення є позиція з ідентифікатором - positionId. * Скидає дату приходу в позиції. Сам обрахунок даних при скиданні відбувається в методі update. * * @param ebmId - ідентифікатор замовлення, з якого відміняється прихід позиції. * @param positionId - ідентифікатор позиції прихід якої необхідно відмінити. * @return - true - в разі успішної відміни, false - якщо відмінити прихід позиції неможливо. */ @Transactional public EbmPosition cancelComingPosition(int ebmId, int positionId) { Ebm ebm = get(ebmId); if (ebm == null) throw new NoDataFoundException("Такого замовлення не занайдено."); if (ebm.getOwner().getLocation().getId() != SecurityUtil.getAuthUser().getLocation().getId()) throw new RuntimeException("Неможливо оновити замовлення іншої локації."); int indexEbmPosition = EbmRepository.getIndexInPositionsListByPositionId(ebm.getPositions(), positionId); // отримуємо ідентифікатор позиції приїзд якої, відміняється, з замовлення if (indexEbmPosition >= 0) { EbmPosition position = ebm.getPositions().get(indexEbmPosition); Part partFromDb = partService.get(position.getPart().getId()); if (position.getDateOfReceived() != null) { if (position.isArrivedToStock()) { partFromDb.setStockCount(partFromDb.getStockCount() - position.getCount()); if (partFromDb.getStockCount() < 0) { throw new RuntimeException("Недостатня кількість в стоці."); } } else { partFromDb.setCount(partFromDb.getCount() - position.getCount()); if (partFromDb.getCount() < 0) { throw new RuntimeException("Недостатня кількість в комірці."); } } partService.update(partFromDb); } position.setDateOfReceived(null); // скидаєм дату приходу position.setArrivedToStock(false); // скидаєм дату приходу if (repository.save(ebm) != null) // апдейтим замовлення. return repository.getPosition(positionId); else throw new RuntimeException("Somthing went wrong."); } else throw new NoDataFoundException("Такої позиції в замовленні не знайдено."); } /** * Повертає всі позиції, які ще не прибули по конкретній запчастині * * @param partId ідентифікатор запчастини * @return список позицій, які ще не прибули */ public List<EbmPosition> getInProccessPositionsByPartId(int partId) { return repository.getInProccessPositionsByPart(partId); } /** * Повертає кількість замовлених запчастин по ідентифікатору запчастини в базі даних. * * @param partId - ідентифікатор запчастини в базі даних. * @return - кількість замовлених запчастин, що ще не прибули по ідентифікатору запчастини. */ public long getTotalCountOrderedPartsByPart(int partId) { return repository.getTotalCountOrderedPartsByPart(partId); } static final String UPLOADED_FILES_PATH = System.getenv("LAGER_MANAGER_ROOT") + "/uploaded/ebms/"; /** * Method remove attached file in ebm. * * @param ebmId - ebm id. * @param filename - file name that must be deleted. * @return true if removal proccess is successful. */ @Transactional(rollbackFor = Exception.class) public boolean removeFileFromEbm(Integer ebmId, String filename) { Ebm ebmFromDb = get(ebmId); boolean isSavedEbm; if (ebmFromDb != null) { if (ebmFromDb.getOwner().getLocation().getId() != SecurityUtil.getAuthUser().getLocation().getId()) throw new RuntimeException("Неможливо редагувати замовлення іншої локації."); List<String> fileList = ebmFromDb.getFiles(); if (fileList.contains(filename)) { try { ebmFromDb.getFiles().remove(filename); isSavedEbm = repository.save(ebmFromDb) != null; } catch (Exception e) { log.debug("Problems with saving ebm: " + e.toString() + "\t" + e.getMessage()); throw new RuntimeException("Problems with saving ebm: " + e.getMessage()); } if (isSavedEbm) { try { Path fileForDelete = Paths.get(UPLOADED_FILES_PATH + ebmFromDb.getDateStartOrder().getYear() + "/" + filename); log.debug("deleting file: " + fileForDelete); if (Files.exists(fileForDelete)) { Files.delete(fileForDelete); } if (!Files.exists(fileForDelete)) { return true; } } catch (IOException e) { log.debug("file didn't delete: " + e.getMessage()); throw new RuntimeException("File " + filename + " didn't delete. Something went wrong."); } } } else { throw new RuntimeException("File " + filename + " doesn't contain in this EBM."); } } else { throw new RuntimeException("Such ebm doesn't present in database."); } return false; } // Завантажує файли, що прикріплені до замовлення private List<String> uploadFiles(LocalDate ebmStartedDate, MultipartFile[] files) throws IOException { List<String> filesList = new ArrayList<>(); if (files == null || files.length == 0) return filesList; for (MultipartFile file : files) { log.debug("try to save : " + file.getOriginalFilename()); if (file != null && !file.getOriginalFilename().isEmpty()) { File uploadDir = new File(UPLOADED_FILES_PATH + ebmStartedDate.getYear()); log.debug("path to save files: " + uploadDir); if (!uploadDir.exists()) { log.debug("create path:" + uploadDir.mkdirs()); } String resultFilename = file.getOriginalFilename(); File uploadedFileFullPath = new File(uploadDir + "/" + resultFilename); int i = 0; while (uploadedFileFullPath.exists()) { i++; uploadedFileFullPath = new File(uploadDir + "/(" + i + ")" + resultFilename); } file.transferTo(uploadedFileFullPath); filesList.add(uploadedFileFullPath.getName()); } } log.debug("loaded files: " + filesList); return filesList; } }
UTF-8
Java
33,167
java
EbmService.java
Java
[]
null
[]
package com.smolenskyi.service; import com.smolenskyi.exeptions.NoDataFoundException; import com.smolenskyi.model.ebm.Ebm; import com.smolenskyi.model.ebm.EbmFilterType; import com.smolenskyi.model.ebm.EbmPosition; import com.smolenskyi.model.ebm.EbmSortType; import com.smolenskyi.model.part.Part; import com.smolenskyi.repository.EbmRepository; import com.smolenskyi.util.EbmUtil; import com.smolenskyi.util.SecurityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.xml.bind.ValidationException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.util.*; // Сервіс замовлень @Service @Transactional(readOnly = true) public class EbmService { private static final Logger log = LoggerFactory.getLogger(EbmService.class); // репозиторій замовлень @Autowired private EbmRepository repository; // репозиторій запчастин @Autowired private PartService partService; /** * Повертає замовлення по локації з ідентифікатором locationId, які відповідають пошуковій фразі search, * відсортовані згідно типу сортування sortType, та відфільтровані згідно фільтру filterType. * * @param locationId - ідентифікатор локації, до якої відносяться замовлення. * @param search - пошукова фраза. * @param sortType - тип сортування, об'Єкт перечислення EbmSortType. * @param filterType - тип фільтрування, об'єкт перечислення EbmFilterType. * @return - список замовлень. */ public List<Ebm> getAll(int locationId, String search, EbmSortType sortType, EbmFilterType filterType) { System.out.println(repository.getAll(locationId, search, sortType, filterType)); return repository.getAll(locationId, search, sortType, filterType); } /** * Видаляє замовлення за ідентифікатором. * * @param id - ідентифікатор замовлення. * @return - true - якщо замовлення видалено успішно, false - якщо замовлення не вдалося видалити. */ @Transactional public boolean delete(int id) { Ebm ebm = get(id); if (ebm != null) { for (EbmPosition ebmPosition : ebm.getPositions()) { if (ebmPosition.getDateOfReceived() != null) throw new RuntimeException("Неможливо видалити замовлення з виконаними позиціями."); } } return repository.delete(id); } /** * Повертає замволення по ідентифікатору. * * @param id - ідентифікатор замовлення. * @return - об'єкт Ebm, або null, якщо замовлення за таким ідентифікатором не знайдено. */ public Ebm get(int id) { return repository.get(id); } /** * Метод збереження нового замовлення. Передає об'єкт замовлення для збереження в репозиторій. */ @Transactional public Ebm create(String ebmNr, // номер замовлення String supplier, // постачальник String comment, // коментар до замовлення Integer[] selectedPart, // ідентифікатори запчастини в базі Integer[] count, // кількість запчастин в позиції Double[] price, // кількість запчастин в позиції MultipartFile[] files) throws ValidationException { Ebm ebm = new Ebm(); ebm.setEbmNr(ebmNr); ebm.setSupplier(supplier); ebm.setDateStartOrder(LocalDate.now()); ebm.setOwner(SecurityUtil.getAuthUser()); ebm.setComment(comment); ebm.setPositions(parseEbmPositionsForNewEbm(selectedPart, count, price)); try { ebm.setFiles(uploadFiles(LocalDate.now(), files)); } catch (IOException e) { log.debug(e.getMessage()); } log.debug("create new ebm: " + ebm); return repository.save(ebm); } // Будує список позицій з набору масивів для нового замовлення List<EbmPosition> parseEbmPositionsForNewEbm(Integer[] selectedPart, // ідентифікатори запчастини в базі Integer[] count, // кількість запчастин в позиції Double[] price) throws ValidationException { // чи завчастини в сток чи в комірку log.debug("Parsing ebm positions. Input data -> " + "\n\t parts: " + Arrays.toString(selectedPart) + "\n\t count: " + Arrays.toString(count) + "\n\t price: " + Arrays.toString(price)); List<EbmPosition> parsedPositions = new ArrayList<>(); // перевірка вхідних масивів на одинакову кількість елементів. if (selectedPart == null) return new ArrayList<>(); if ((selectedPart == null || count == null || price == null) || (selectedPart.length != count.length || selectedPart.length != price.length)) { throw new ValidationException("Не правильний формат форми. Спробуйте ще раз."); } // прохід по всіх елементах масивів for (int i = 0; i < selectedPart.length; i++) { EbmPosition currentPosition = new EbmPosition(); Part currentPart = selectedPart[i] == null ? null : partService.get(selectedPart[i]); currentPosition.setPart(currentPart); currentPosition.setCount(count[i]); currentPosition.setPrice(price[i]); parsedPositions.add(currentPosition); } return parsedPositions; } /** * Update present order. * * @param id - ідентифікатор замовлення * @param ebmNr - номер замовлення * @param supplier - постачальник * @param comment - коментар до замовлення * @param positionid - масив ідентифікаторів позицій * @param selectedPart - масив ідентифікаторів обраних запчастин * @param count - масив кількостей запчастин в позиціях * @param price - ціна позицій * @param dateOfRecived - масив дат приходу позицій * @param toStock - масив прапорців чи позиції прибули в склад чи в комірку - 0 - в комірку; 1 - в складззззззззззззззз * @param files - список прикріплених файлів */ @Transactional public Ebm update(Integer id, String ebmNr, String supplier, String comment, Integer[] positionid, Integer[] selectedPart, Integer[] count, Double[] price, String[] dateOfRecived, Integer[] toStock, MultipartFile[] files) throws ValidationException { if (id == null) throw new ValidationException("Неможливо оновити замовлення. Такого замовлення не існує."); Ebm ebm = get(id); if (ebm == null) throw new ValidationException("Неможливо оновити замовлення. Такого замовлення не існує."); if (ebm.getOwner().getLocation().getId() != SecurityUtil.getAuthUser().getLocation().getId()) throw new RuntimeException("Неможливо оновити замовлення іншої локації."); ebm.setEbmNr(ebmNr); ebm.setSupplier(supplier); ebm.setComment(comment); List<EbmPosition> incomingEbmPositionList = parseEbmPositionsForEbm(positionid, selectedPart, count, price, dateOfRecived, toStock); // додаємо нові позиції в замовлення і апдейтим існуючі for (EbmPosition ebmPosition : incomingEbmPositionList) { if (ebmPosition.isNew()) { ebm.addPosition(ebmPosition); log.debug("add new position to ebm[" + ebm.getId() + "]: " + ebmPosition); } else { EbmPosition posFromDB = ebm.getPositions().get(ebm.getPositions().indexOf(ebmPosition)); if (posFromDB != null && posFromDB.getDateOfReceived() == null) { posFromDB.setPart(ebmPosition.getPart()); posFromDB.setCount(ebmPosition.getCount()); posFromDB.setPrice(ebmPosition.getPrice()); if (Objects.nonNull(ebmPosition.getDateOfReceived()) && Objects.isNull(posFromDB.getDateOfReceived())) { // якщо замовлення прийшло Part part = partService.get(ebmPosition.getPart().getId()); if (part == null) throw new NoDataFoundException("Не знайдено запчастини."); if (ebmPosition.isArrivedToStock()) { // якщо запчастини прийли в склад part.setStockCount(part.getStockCount() + ebmPosition.getCount()); } else { // якщо запчастини прийли в нумеровану комірку part.setCount(part.getCount() + ebmPosition.getCount()); } posFromDB.setDateOfReceived(ebmPosition.getDateOfReceived()); posFromDB.setArrivedToStock(ebmPosition.isArrivedToStock()); partService.update(part); } } } } try { ebm.getFiles().addAll(uploadFiles(ebm.getDateStartOrder(), files)); } catch (IOException e) { e.printStackTrace(); } removeDeletedPositionsFromEbm(ebm, incomingEbmPositionList); log.debug("save ebm to repository: " + ebm.toString()); return repository.save(ebm); } /** * Remove deleted positions from ebm. * * @param ebm - order * @param incomingEbmPositionList - list of incoming positions */ @Transactional void removeDeletedPositionsFromEbm(Ebm ebm, List<EbmPosition> incomingEbmPositionList) { // видаляємо видалені позиції List<EbmPosition> positionsForRemoving = new ArrayList<>(); Iterator<EbmPosition> iterator = ebm.getPositions().iterator(); while (iterator.hasNext()) { EbmPosition ebmPosition = iterator.next(); if (!ebmPosition.isNew() && incomingEbmPositionList.indexOf(ebmPosition) < 0) { positionsForRemoving.add(ebmPosition); } } for (EbmPosition position : positionsForRemoving) { ebm.removePosition(position); } } // Будує список позицій з набору масивів для існуючого замовлення List<EbmPosition> parseEbmPositionsForEbm(Integer[] positionId, // ідентифікатор позиції Integer[] selectedPart, // ідентифікатори запчастини в базі Integer[] count, // кількість запчастин в позиції Double[] price, // вартість позиції String[] dateOfRecived, // дата прибуття Integer[] toStock // прапорець чи позиція прибула в склад чи в комірку ) throws ValidationException { log.debug("Parsing ebm positions. Input data -> " + "\n\t positionId: " + Arrays.toString(positionId) + "\n\t parts: " + Arrays.toString(selectedPart) + "\n\t count: " + Arrays.toString(count) + "\n\t price: " + Arrays.toString(price) + "\n\t dateOfRecived: " + Arrays.toString(dateOfRecived) + "\n\t toStock: " + Arrays.toString(toStock)); List<EbmPosition> parsedPositions = new ArrayList<>(); // перевірка вхідних масивів на одинакову кількість елементів. if (selectedPart == null || selectedPart.length == 0) return new ArrayList<>(); if ((positionId == null || selectedPart == null || count == null || price == null || dateOfRecived == null || toStock == null) || (selectedPart.length != positionId.length || count.length != positionId.length || price.length != positionId.length || dateOfRecived.length != positionId.length || toStock.length != positionId.length)) { throw new ValidationException("Не правильний формат форми. Спробуйте ще раз."); } // прохід по всіх елементах масивів for (int i = 0; i < positionId.length; i++) { EbmPosition currentPosition = new EbmPosition(); currentPosition.setId(positionId[i]); Part currentPart = selectedPart[i] == null ? null : partService.get(selectedPart[i]); currentPosition.setPart(currentPart); currentPosition.setCount(count[i]); currentPosition.setPrice(price[i]); LocalDate positionDateRecived = null; try { positionDateRecived = dateOfRecived[i] != null ? LocalDate.parse(dateOfRecived[i]) : null; } catch (RuntimeException re) { } currentPosition.setDateOfReceived(positionDateRecived); int currentToStock = 0; if (toStock[i] != null && toStock[i] == 1) currentToStock = 1; currentPosition.setArrivedToStock(currentToStock == 1); parsedPositions.add(currentPosition); } log.debug("parsed positions: " + parsedPositions); return parsedPositions; } /** * Метод оновлення існуючого замовлення. Передає замовлення в репозиторій для оновлення в базі даних. * Оновлює дані кількостей в складі запчастин, якщо позиції прибули, або відбувається відміна прибуття позицій. * * @param ebm - об'єкт оновленого замовлення, яке потрібно оновити в базі даних. */ @Transactional public Ebm update(Ebm ebm) { Ebm ebmFromDB = get(ebm.getId()); // отрмуєм замовлення з бази даних на основі ідентифікатора вхідного замовлення(об'єкт якого ми намагаємся зберегти в базу даних) if (ebm.getFiles() != null) { ebm.getFiles().addAll(ebmFromDB.getFiles()); } else { ebm.setFiles(ebmFromDB.getFiles()); } for (EbmPosition positionFromDB : ebmFromDB.getPositions()) { // здійснюєм прохід по позиціям, для опрацювання руху кількостей запчастин if (EbmRepository.isPresentInListWithSuchId(ebm.getPositions(), positionFromDB) >= 0) { // якщо позиція існує вже в замовленні. інакше вона нова, і кількості не потрібно нікуди враховувати for (EbmPosition ebmPosition : ebm.getPositions()) { // прохід по позиціям вхідного об'єкту замовлення if (Objects.nonNull(positionFromDB.getId()) && positionFromDB.getId().equals(ebmPosition.getId())) { // якщо ідентифікатор позиції з бази і ідентифікатор вхідної позиції збігаються if (Objects.nonNull(ebmPosition.getDateOfReceived()) && Objects.isNull(positionFromDB.getDateOfReceived())) { // якщо замовлення прийшло Part part = partService.get(ebmPosition.getPart().getId()); if (part == null) throw new NoDataFoundException("Не знайдено запчастини."); if (ebmPosition.isArrivedToStock()) // якщо запчастини прийли в склад part.setStockCount(part.getStockCount() + ebmPosition.getCount()); else // якщо запчастини прийли в нумеровану комірку part.setCount(part.getCount() + ebmPosition.getCount()); partService.update(part); } if (Objects.isNull(ebmPosition.getDateOfReceived()) && Objects.nonNull(positionFromDB.getDateOfReceived())) { // якщо відміна приходу позиції Part part = partService.get(ebmPosition.getPart().getId()); if (part == null) throw new NoDataFoundException("Не знайдено запчастини."); if (positionFromDB.isArrivedToStock()) // якщо запчастини прийли в склад if ((part.getStockCount() - ebmPosition.getCount()) >= 0) part.setStockCount(part.getStockCount() - ebmPosition.getCount()); else throw new RuntimeException("Відсутня достатня кількість в складі."); else // якщо запчастини прийли в нумеровану комірку if ((part.getCount() - ebmPosition.getCount()) >= 0) part.setCount(part.getCount() - ebmPosition.getCount()); else throw new RuntimeException("Відсутня достатня кількість в комірці."); partService.update(part); } } } } } ebm.setPositions(EbmUtil.mergeEbmPositionsGroupByPartThatDidNotArrive(ebm.getPositions())); return repository.save(ebm); // зберігаєм замовлення в базу } /** * @param ebmId * @param positionid * @param selectedPart * @param count * @param dateOfReceived * @param toStock * @return * @throws ValidationException */ @Transactional public Ebm updateOnlyEbmPositions(Integer ebmId, String[] positionid, // ідентифікатори позицій в базі String[] selectedPart, // ідентифікатори запчастини в базі String[] count, // кількість запчастин в позиції String[] dateOfReceived, // кількість запчастин в позиції Integer[] toStock) throws ValidationException { List<Integer> comingPosIdsToStosk; // створюємо список з ідентифікаторами позицій, що зачислюються в склад if (Objects.nonNull(toStock)) comingPosIdsToStosk = Arrays.asList(toStock); // створюємо список ідентифікаторів позицій, які попадають в склад else comingPosIdsToStosk = new ArrayList<>(); // перевірка вхідних масивів на одинакову кількість елементів. if (selectedPart.length != count.length) { throw new ValidationException("Не правильний формат форми. Спробуйте ще раз."); } Ebm currentEbm = get(ebmId); // отримуєм замовлення з БД // прохід по всіх елементах масивів for (int i = 0; i < count.length; i++) { int positionIdItem; // номер позиції int countItem; // замовлена кількість try { // парсим значення з масивів if (positionid[i].startsWith("#")) { // якщо позиція нова, створена в результаті розбиття позиції. continue; // пропускаємо нові позиції, їх будемо створювати при обробці існуючих } else { positionIdItem = Integer.parseInt(positionid[i]); EbmPosition ebmPosition = currentEbm.getPositions().get(EbmRepository.getIndexInPositionsListByPositionId(currentEbm.getPositions(), positionIdItem)); // берем позицію з замовлення countItem = Integer.parseInt(count[i].substring(0, count[i].indexOf(" "))); // вхідна стрічка кількості у вигляді ( 500 pcs.), вирізаємо лише числове значення if (ebmPosition.getCount() > countItem && dateOfReceived[i] != null) { // якщо в існуючій позиції в БД кількість більша ніж в оновленій int newPositionCount = ebmPosition.getCount() - countItem; double newPositionPrice = ((int) (ebmPosition.getPrice() / ebmPosition.getCount() * newPositionCount * 100)) / 100.0; EbmPosition newPosition = new EbmPosition(ebmPosition.getPart(), newPositionCount, newPositionPrice); // створюємо нову позицію // newPosition.setEbm(currentEbm); currentEbm.getPositions().add(newPosition); ebmPosition.setCount(ebmPosition.getCount() - newPositionCount); ebmPosition.setPrice(ebmPosition.getPrice() - newPositionPrice); } if (ebmPosition.getDateOfReceived() == null && dateOfReceived[i] != null && !dateOfReceived[i].equals("")) { // якщо вказана дата приходу ebmPosition.setDateOfReceived(LocalDate.parse(dateOfReceived[i])); // задаєм дату приходу if (comingPosIdsToStosk.contains(ebmPosition.getId())) { // якщо позиція по приходу попадає в склад а не в нумеровану комірку ebmPosition.setArrivedToStock(true); } } } } catch (NumberFormatException nfe) { // перехоплюємо вийняток, що може відбутися під час парсингу чисел throw new RuntimeException("Не правильний формат форми. Спробуйте ще раз."); } } log.debug("updating ebm: " + currentEbm); return repository.save(currentEbm); } /** * Метод відміни приходу позиції на склад. * Витягує замовлення з БД за ідентифікатором ebmId. Перевіряє чи в замовлення є позиція з ідентифікатором - positionId. * Скидає дату приходу в позиції. Сам обрахунок даних при скиданні відбувається в методі update. * * @param ebmId - ідентифікатор замовлення, з якого відміняється прихід позиції. * @param positionId - ідентифікатор позиції прихід якої необхідно відмінити. * @return - true - в разі успішної відміни, false - якщо відмінити прихід позиції неможливо. */ @Transactional public EbmPosition cancelComingPosition(int ebmId, int positionId) { Ebm ebm = get(ebmId); if (ebm == null) throw new NoDataFoundException("Такого замовлення не занайдено."); if (ebm.getOwner().getLocation().getId() != SecurityUtil.getAuthUser().getLocation().getId()) throw new RuntimeException("Неможливо оновити замовлення іншої локації."); int indexEbmPosition = EbmRepository.getIndexInPositionsListByPositionId(ebm.getPositions(), positionId); // отримуємо ідентифікатор позиції приїзд якої, відміняється, з замовлення if (indexEbmPosition >= 0) { EbmPosition position = ebm.getPositions().get(indexEbmPosition); Part partFromDb = partService.get(position.getPart().getId()); if (position.getDateOfReceived() != null) { if (position.isArrivedToStock()) { partFromDb.setStockCount(partFromDb.getStockCount() - position.getCount()); if (partFromDb.getStockCount() < 0) { throw new RuntimeException("Недостатня кількість в стоці."); } } else { partFromDb.setCount(partFromDb.getCount() - position.getCount()); if (partFromDb.getCount() < 0) { throw new RuntimeException("Недостатня кількість в комірці."); } } partService.update(partFromDb); } position.setDateOfReceived(null); // скидаєм дату приходу position.setArrivedToStock(false); // скидаєм дату приходу if (repository.save(ebm) != null) // апдейтим замовлення. return repository.getPosition(positionId); else throw new RuntimeException("Somthing went wrong."); } else throw new NoDataFoundException("Такої позиції в замовленні не знайдено."); } /** * Повертає всі позиції, які ще не прибули по конкретній запчастині * * @param partId ідентифікатор запчастини * @return список позицій, які ще не прибули */ public List<EbmPosition> getInProccessPositionsByPartId(int partId) { return repository.getInProccessPositionsByPart(partId); } /** * Повертає кількість замовлених запчастин по ідентифікатору запчастини в базі даних. * * @param partId - ідентифікатор запчастини в базі даних. * @return - кількість замовлених запчастин, що ще не прибули по ідентифікатору запчастини. */ public long getTotalCountOrderedPartsByPart(int partId) { return repository.getTotalCountOrderedPartsByPart(partId); } static final String UPLOADED_FILES_PATH = System.getenv("LAGER_MANAGER_ROOT") + "/uploaded/ebms/"; /** * Method remove attached file in ebm. * * @param ebmId - ebm id. * @param filename - file name that must be deleted. * @return true if removal proccess is successful. */ @Transactional(rollbackFor = Exception.class) public boolean removeFileFromEbm(Integer ebmId, String filename) { Ebm ebmFromDb = get(ebmId); boolean isSavedEbm; if (ebmFromDb != null) { if (ebmFromDb.getOwner().getLocation().getId() != SecurityUtil.getAuthUser().getLocation().getId()) throw new RuntimeException("Неможливо редагувати замовлення іншої локації."); List<String> fileList = ebmFromDb.getFiles(); if (fileList.contains(filename)) { try { ebmFromDb.getFiles().remove(filename); isSavedEbm = repository.save(ebmFromDb) != null; } catch (Exception e) { log.debug("Problems with saving ebm: " + e.toString() + "\t" + e.getMessage()); throw new RuntimeException("Problems with saving ebm: " + e.getMessage()); } if (isSavedEbm) { try { Path fileForDelete = Paths.get(UPLOADED_FILES_PATH + ebmFromDb.getDateStartOrder().getYear() + "/" + filename); log.debug("deleting file: " + fileForDelete); if (Files.exists(fileForDelete)) { Files.delete(fileForDelete); } if (!Files.exists(fileForDelete)) { return true; } } catch (IOException e) { log.debug("file didn't delete: " + e.getMessage()); throw new RuntimeException("File " + filename + " didn't delete. Something went wrong."); } } } else { throw new RuntimeException("File " + filename + " doesn't contain in this EBM."); } } else { throw new RuntimeException("Such ebm doesn't present in database."); } return false; } // Завантажує файли, що прикріплені до замовлення private List<String> uploadFiles(LocalDate ebmStartedDate, MultipartFile[] files) throws IOException { List<String> filesList = new ArrayList<>(); if (files == null || files.length == 0) return filesList; for (MultipartFile file : files) { log.debug("try to save : " + file.getOriginalFilename()); if (file != null && !file.getOriginalFilename().isEmpty()) { File uploadDir = new File(UPLOADED_FILES_PATH + ebmStartedDate.getYear()); log.debug("path to save files: " + uploadDir); if (!uploadDir.exists()) { log.debug("create path:" + uploadDir.mkdirs()); } String resultFilename = file.getOriginalFilename(); File uploadedFileFullPath = new File(uploadDir + "/" + resultFilename); int i = 0; while (uploadedFileFullPath.exists()) { i++; uploadedFileFullPath = new File(uploadDir + "/(" + i + ")" + resultFilename); } file.transferTo(uploadedFileFullPath); filesList.add(uploadedFileFullPath.getName()); } } log.debug("loaded files: " + filesList); return filesList; } }
33,167
0.59316
0.592036
540
51.737038
37.947739
200
false
false
0
0
0
0
0
0
0.592593
false
false
5
99f93bb7c86a110b1b804e7e6ee461a818cf52f7
18,116,172,099,822
c0d334836e9b411e2d9f9dab6b1309795e1f3ec7
/src/main/java/com/example/jucdemo/unsafe/SetTest.java
d694f5f08d894850752af230fc07047e2c3750de
[]
no_license
gateEgg/JUCDemo
https://github.com/gateEgg/JUCDemo
7187a9f3b3e57d0e740d45ce4b4ec20bdaefe063
09e28d7cdfd0ae51890bc599873ab721b5d9c3ab
refs/heads/master
2023-08-26T15:07:46.172000
2021-10-25T11:03:07
2021-10-25T11:03:07
394,585,473
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.jucdemo.unsafe; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; /** * @author jiesi * @Description Set测试 * HashSet线程不安全 会产生ConcurrentModificationException异常 * @Date 2021/8/10 11:17 上午 */ public class SetTest { public static void main(String[] args) { // Set<String> set = new HashSet<>(); // 1.Set<String> set = Collections.synchronizedSet(new HashSet<>()); // 2 Set<String> set = new CopyOnWriteArraySet<>(); for (int i = 0; i < 11; i++) { new Thread(() -> { set.add(UUID.randomUUID().toString().substring(0, 5)); System.out.println(set); }, String.valueOf(i)).start(); } } }
UTF-8
Java
815
java
SetTest.java
Java
[ { "context": "il.concurrent.CopyOnWriteArraySet;\n\n/**\n * @author jiesi\n * @Description Set测试\n * HashSet线程不安全 会产生Concurre", "end": 177, "score": 0.9994571208953857, "start": 172, "tag": "USERNAME", "value": "jiesi" } ]
null
[]
package com.example.jucdemo.unsafe; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; /** * @author jiesi * @Description Set测试 * HashSet线程不安全 会产生ConcurrentModificationException异常 * @Date 2021/8/10 11:17 上午 */ public class SetTest { public static void main(String[] args) { // Set<String> set = new HashSet<>(); // 1.Set<String> set = Collections.synchronizedSet(new HashSet<>()); // 2 Set<String> set = new CopyOnWriteArraySet<>(); for (int i = 0; i < 11; i++) { new Thread(() -> { set.add(UUID.randomUUID().toString().substring(0, 5)); System.out.println(set); }, String.valueOf(i)).start(); } } }
815
0.603558
0.580686
27
28.148148
21.90333
76
false
false
0
0
0
0
0
0
0.518519
false
false
5
2660fef72f1d486d3f6583fbc3f9e588cea1352c
29,600,914,651,803
c2cb346c4e2e1b504c6e76a19aa349c4caff3b02
/src/main/java/by/jwd/restaurant/dao/impl/SQLUserDAO.java
7dc1fb568fabe5e598a29e60326f58dfb3687d27
[]
no_license
AlexandrOkolotovich/FinalProject
https://github.com/AlexandrOkolotovich/FinalProject
9e1001b82780fce8df4323fd3c7ffa1ce882f57b
96027a8e0b0c24fa349b1a38706fbff31a53417d
refs/heads/main
2023-04-23T16:59:13.810000
2021-05-12T01:33:02
2021-05-12T01:33:02
344,543,827
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.jwd.restaurant.dao.impl; import by.jwd.restaurant.entity.RegistrationInfo; import by.jwd.restaurant.dao.UserDAO; import by.jwd.restaurant.dao.connection.ConnectionPool; import by.jwd.restaurant.dao.exception.ConnectionPoolException; import by.jwd.restaurant.entity.Role; import by.jwd.restaurant.entity.User; import by.jwd.restaurant.dao.exception.DAOException; import java.sql.*; public class SQLUserDAO implements UserDAO { private static final String COLUMN_LABEL_USER_ID = "user_id"; private static final String COLUMN_LABEL_USER_PASSWORD = "user_password"; private static final String COLUMN_LABEL_USER_ROLE = "role_name"; private static final String COLUMN_LABEL_USER_NAME = "user_name"; private static final String COLUMN_LABEL_USER_SURNAME = "user_surname"; private static final String COLUMN_LABEL_USER_PHONE = "user_phone"; private static final String COLUMN_LABEL_USER_EMAIL = "user_email"; private static final String SELECT_USER_EMAIL_PASSWORD = "SELECT users.user_id, role_name FROM users JOIN roles ON users.role_id=roles.role_id WHERE user_email = ? AND user_password = ?"; private static final String SELECT_USER_ID = "SELECT user_id FROM users WHERE user_email = ? "; private static final String INSERT_REGISTRATION_USER = "INSERT INTO users (user_name, user_surname, user_phone, user_email, user_password, role_id) VALUES (?, ?, ?, ?, ?, ?)"; private static final String SELECT_USER_PASSWORD = "SELECT user_password FROM users WHERE user_email = ?"; private static final String SELECT_USER = "SELECT users.user_id, users.user_name, users.user_surname, users.user_phone, users.user_email, users.user_password, role_name FROM users JOIN roles ON users.role_id=roles.role_id WHERE user_email = ?"; static { MySQLDriverLoader.getInstance(); } @Override public User authorization(String login, String password) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; Integer id; String roleName; User user = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER_EMAIL_PASSWORD); prSt.setString(1, login); prSt.setString(2, password); resSet = prSt.executeQuery(); if(resSet.next()){ id = resSet.getInt(COLUMN_LABEL_USER_ID); roleName = resSet.getString(COLUMN_LABEL_USER_ROLE); Role role = Role.valueOf(roleName); user = new User(id, login, password, role); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return user; } @Override public boolean registration(RegistrationInfo user) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(INSERT_REGISTRATION_USER); prSt.setString(1, user.getName()); prSt.setString(2, user.getSurname()); prSt.setString(3, user.getPhone()); prSt.setString(4, user.getEmail()); prSt.setString(5, user.getPassword()); prSt.setInt(6, user.getRoleId()); prSt.executeUpdate(); } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return true; } @Override public Integer findId(String email) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; Integer id = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER_ID); prSt.setString(1, email); resSet = prSt.executeQuery(); if (resSet.next()) { id = resSet.getInt(COLUMN_LABEL_USER_ID); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return id; } @Override public String getPassword(String email) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; String password = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER_PASSWORD); prSt.setString(1, email); resSet = prSt.executeQuery(); if (resSet.next()) { password = resSet.getString(COLUMN_LABEL_USER_PASSWORD); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return password; } @Override public User getUser(String email) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; User user = new User(); try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER); prSt.setString(1, email); resSet = prSt.executeQuery(); while (resSet.next()) { user.setId(resSet.getInt(COLUMN_LABEL_USER_ID)); user.setName(resSet.getString(COLUMN_LABEL_USER_NAME)); user.setSurname(resSet.getString(COLUMN_LABEL_USER_SURNAME)); user.setPhone(resSet.getString(COLUMN_LABEL_USER_PHONE)); user.setEmail(resSet.getString(COLUMN_LABEL_USER_EMAIL)); user.setPassword(resSet.getString(COLUMN_LABEL_USER_PASSWORD)); user.setRole(Role.valueOf(resSet.getString(COLUMN_LABEL_USER_ROLE))); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return user; } }
UTF-8
Java
7,693
java
SQLUserDAO.java
Java
[ { "context": "static final String COLUMN_LABEL_USER_PASSWORD = \"user_password\";\r\n private static final String COLUMN_LABEL_U", "end": 595, "score": 0.9993507266044617, "start": 582, "tag": "PASSWORD", "value": "user_password" }, { "context": "L_USER_EMAIL));\r\n user.setPassword(resSet.getString(COLUMN_LABEL_USER_PASSWORD));\r\n ", "end": 7182, "score": 0.763737142086029, "start": 7179, "tag": "PASSWORD", "value": "res" } ]
null
[]
package by.jwd.restaurant.dao.impl; import by.jwd.restaurant.entity.RegistrationInfo; import by.jwd.restaurant.dao.UserDAO; import by.jwd.restaurant.dao.connection.ConnectionPool; import by.jwd.restaurant.dao.exception.ConnectionPoolException; import by.jwd.restaurant.entity.Role; import by.jwd.restaurant.entity.User; import by.jwd.restaurant.dao.exception.DAOException; import java.sql.*; public class SQLUserDAO implements UserDAO { private static final String COLUMN_LABEL_USER_ID = "user_id"; private static final String COLUMN_LABEL_USER_PASSWORD = "<PASSWORD>"; private static final String COLUMN_LABEL_USER_ROLE = "role_name"; private static final String COLUMN_LABEL_USER_NAME = "user_name"; private static final String COLUMN_LABEL_USER_SURNAME = "user_surname"; private static final String COLUMN_LABEL_USER_PHONE = "user_phone"; private static final String COLUMN_LABEL_USER_EMAIL = "user_email"; private static final String SELECT_USER_EMAIL_PASSWORD = "SELECT users.user_id, role_name FROM users JOIN roles ON users.role_id=roles.role_id WHERE user_email = ? AND user_password = ?"; private static final String SELECT_USER_ID = "SELECT user_id FROM users WHERE user_email = ? "; private static final String INSERT_REGISTRATION_USER = "INSERT INTO users (user_name, user_surname, user_phone, user_email, user_password, role_id) VALUES (?, ?, ?, ?, ?, ?)"; private static final String SELECT_USER_PASSWORD = "SELECT user_password FROM users WHERE user_email = ?"; private static final String SELECT_USER = "SELECT users.user_id, users.user_name, users.user_surname, users.user_phone, users.user_email, users.user_password, role_name FROM users JOIN roles ON users.role_id=roles.role_id WHERE user_email = ?"; static { MySQLDriverLoader.getInstance(); } @Override public User authorization(String login, String password) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; Integer id; String roleName; User user = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER_EMAIL_PASSWORD); prSt.setString(1, login); prSt.setString(2, password); resSet = prSt.executeQuery(); if(resSet.next()){ id = resSet.getInt(COLUMN_LABEL_USER_ID); roleName = resSet.getString(COLUMN_LABEL_USER_ROLE); Role role = Role.valueOf(roleName); user = new User(id, login, password, role); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return user; } @Override public boolean registration(RegistrationInfo user) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(INSERT_REGISTRATION_USER); prSt.setString(1, user.getName()); prSt.setString(2, user.getSurname()); prSt.setString(3, user.getPhone()); prSt.setString(4, user.getEmail()); prSt.setString(5, user.getPassword()); prSt.setInt(6, user.getRoleId()); prSt.executeUpdate(); } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return true; } @Override public Integer findId(String email) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; Integer id = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER_ID); prSt.setString(1, email); resSet = prSt.executeQuery(); if (resSet.next()) { id = resSet.getInt(COLUMN_LABEL_USER_ID); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return id; } @Override public String getPassword(String email) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; String password = null; try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER_PASSWORD); prSt.setString(1, email); resSet = prSt.executeQuery(); if (resSet.next()) { password = resSet.getString(COLUMN_LABEL_USER_PASSWORD); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return password; } @Override public User getUser(String email) throws DAOException { ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; PreparedStatement prSt = null; ResultSet resSet; User user = new User(); try { connection = connectionPool.takeConnection(); prSt = connection.prepareStatement(SELECT_USER); prSt.setString(1, email); resSet = prSt.executeQuery(); while (resSet.next()) { user.setId(resSet.getInt(COLUMN_LABEL_USER_ID)); user.setName(resSet.getString(COLUMN_LABEL_USER_NAME)); user.setSurname(resSet.getString(COLUMN_LABEL_USER_SURNAME)); user.setPhone(resSet.getString(COLUMN_LABEL_USER_PHONE)); user.setEmail(resSet.getString(COLUMN_LABEL_USER_EMAIL)); user.setPassword(resSet.getString(COLUMN_LABEL_USER_PASSWORD)); user.setRole(Role.valueOf(resSet.getString(COLUMN_LABEL_USER_ROLE))); } } catch (SQLException | ConnectionPoolException e) { throw new DAOException(e); } finally { try { connectionPool.closeConnection(connection, prSt); }catch (ConnectionPoolException e){ throw new DAOException(e); } } return user; } }
7,690
0.600156
0.598726
199
36.658291
33.144028
248
false
false
0
0
0
0
0
0
0.743719
false
false
5
a7372f55727591c8e34644ec0e8c28f6642306ae
22,290,880,316,284
388ace3ff85f5b0deb0ecdfe2ba0dfc1415e8918
/appmodule/appdatabase/src/main/java/com/slc/appdatabase/DaoMaster.java
085241d6de5a6ed9477153ba63fa1112318ae691
[]
no_license
shang1313/MobileCommand
https://github.com/shang1313/MobileCommand
6e56261692f3f0f15c2635112388afa39532f850
4b05e2814de2dbc9d28838cd917a8de21dad37b8
refs/heads/master
2023-03-27T05:13:43.542000
2021-03-18T03:53:50
2021-03-18T03:53:50
346,631,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.slc.appdatabase; import com.alibaba.android.arouter.launcher.ARouter; import com.slc.appdatabase.service.DaoService; import com.slc.appdatabase.version.TableVersion; import com.slc.appdatabase.version.TableVersion_; import java.util.concurrent.ConcurrentHashMap; public class DaoMaster { private final static ConcurrentHashMap<Class, DaoService> serviceMap = new ConcurrentHashMap<>(); /** * 获取服务 * * @param tClass * @param <T> * @return */ public static <T extends DaoService> T getService(Class<T> tClass) { T service = (T) serviceMap.get(tClass); if (service == null) { synchronized (DaoMaster.class) { service = (T) serviceMap.get(tClass); if (service == null) { service = ARouter.getInstance().navigation(tClass); serviceMap.put(tClass, service); } } } return service; } public static int getVersionByTableName(String tableName) { return getTableVersionByName(tableName).getVersion(); } public static void updateVersionByName(String tableName, int version) { TableVersion tableVersion = getTableVersionByName(tableName); if (tableVersion.getVersion() >= version) { throw new IllegalStateException("新的version必须大于当前的version"); } tableVersion.setVersion(version); ObjectBox.getBox(TableVersion.class).put(tableVersion); } public static TableVersion getTableVersionByName(String tableName) { if (tableName == null) { throw new NullPointerException("tableName 不能为空"); } TableVersion tableVersion = ObjectBox.getBox(TableVersion.class).query().equal(TableVersion_.tableName, tableName).build().findFirst(); if (tableVersion == null) { tableVersion = new TableVersion(); tableVersion.setVersion(0); tableVersion.setTableName(tableName); } return tableVersion; } public interface DaoElementListener<T> { void onRemove(int dataDiversityVersion, T data); void onPut(int dataDiversityVersion, T data); void onComplete(); } }
UTF-8
Java
2,276
java
DaoMaster.java
Java
[]
null
[]
package com.slc.appdatabase; import com.alibaba.android.arouter.launcher.ARouter; import com.slc.appdatabase.service.DaoService; import com.slc.appdatabase.version.TableVersion; import com.slc.appdatabase.version.TableVersion_; import java.util.concurrent.ConcurrentHashMap; public class DaoMaster { private final static ConcurrentHashMap<Class, DaoService> serviceMap = new ConcurrentHashMap<>(); /** * 获取服务 * * @param tClass * @param <T> * @return */ public static <T extends DaoService> T getService(Class<T> tClass) { T service = (T) serviceMap.get(tClass); if (service == null) { synchronized (DaoMaster.class) { service = (T) serviceMap.get(tClass); if (service == null) { service = ARouter.getInstance().navigation(tClass); serviceMap.put(tClass, service); } } } return service; } public static int getVersionByTableName(String tableName) { return getTableVersionByName(tableName).getVersion(); } public static void updateVersionByName(String tableName, int version) { TableVersion tableVersion = getTableVersionByName(tableName); if (tableVersion.getVersion() >= version) { throw new IllegalStateException("新的version必须大于当前的version"); } tableVersion.setVersion(version); ObjectBox.getBox(TableVersion.class).put(tableVersion); } public static TableVersion getTableVersionByName(String tableName) { if (tableName == null) { throw new NullPointerException("tableName 不能为空"); } TableVersion tableVersion = ObjectBox.getBox(TableVersion.class).query().equal(TableVersion_.tableName, tableName).build().findFirst(); if (tableVersion == null) { tableVersion = new TableVersion(); tableVersion.setVersion(0); tableVersion.setTableName(tableName); } return tableVersion; } public interface DaoElementListener<T> { void onRemove(int dataDiversityVersion, T data); void onPut(int dataDiversityVersion, T data); void onComplete(); } }
2,276
0.64273
0.642284
67
32.477612
28.829067
143
false
false
0
0
0
0
0
0
0.477612
false
false
5
b69eed07c3fbacba816efe40a5f5b0c145c655ab
22,290,880,316,578
491f022af5e2a66cea7d83bc5a04f92b1d8d713d
/day1012/PersonTest03.java
597883827d4e51fa28fd675de19d4e88959a6aa3
[]
no_license
seouuuu/javaStudy
https://github.com/seouuuu/javaStudy
c9e9c252243bf89e0ee444864e0eddcc072610fa
dcda56d209efe0528e73689e762ca80106cd4de5
refs/heads/main
2023-08-31T20:17:02.146000
2021-10-25T08:47:39
2021-10-25T08:47:39
411,869,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Person { private String name; public void setName(String name){ name = name; //매개변수에 저장된 것을 매개변수에 저장. 멤버에는 저장x } public String getName(){ return name; } } class PersonTest03 { public static void main(String[] args) { Person p1 = new Person(); p1.setName("홍길동"); System.out.println(p1.getName()); } }
UHC
Java
412
java
PersonTest03.java
Java
[ { "context": "gs) \n\t{\n\t\tPerson p1 = new Person();\n\t\tp1.setName(\"홍길동\");\n\t\tSystem.out.println(p1.getName());\n\t}\n}\n", "end": 315, "score": 0.9996275901794434, "start": 312, "tag": "NAME", "value": "홍길동" } ]
null
[]
class Person { private String name; public void setName(String name){ name = name; //매개변수에 저장된 것을 매개변수에 저장. 멤버에는 저장x } public String getName(){ return name; } } class PersonTest03 { public static void main(String[] args) { Person p1 = new Person(); p1.setName("홍길동"); System.out.println(p1.getName()); } }
412
0.602778
0.588889
19
17.947369
19.508362
79
false
false
0
0
0
0
0
0
1.263158
false
false
5
0c0ea8bc790751fb93984c692eb8191247ff82c7
16,149,077,099,504
6b2975101d1fec85dba63e7898be2681918815e6
/JavaPrac/src/chp1_ArrayAndString/Reader4.java
1344ce31e573e5a985cc4fb059e09bc9a4ed0591
[]
no_license
JulyKikuAkita/JavaPrac
https://github.com/JulyKikuAkita/JavaPrac
dae0e25995d4399c586d6efd48ebb8aac4782425
1de3d4e8c6b40b001f98ea8caf70ce5752af9344
refs/heads/master
2021-01-21T16:48:22.322000
2017-05-20T17:15:05
2017-05-20T17:15:05
91,906,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package chp1_ArrayAndString; import java.util.Arrays; public class Reader4 { /* # python code # The read4 API is already defined for you. # @param buf, a list of characters # @return an integer def read4(buf): global file_content i = 0 while i < len(file_content) and i < 4: buf[i] = file_content[i] i += 1 if len(file_content) > 4: file_content = file_content[4:] else: file_content = "" return i */ public int read4(char[] buf){ // read4 saves 4 char to buf ? char[] file_content = "fileInput".toCharArray(); int i = 0; while( i < file_content.length && i < 4){ buf[i] = file_content[i]; i += 1; } if(file_content.length > 4){ // System.arraycopy(src, srcPos, dest, destPos, length) //Arrays.copyOfRange(original, from, to); char[] rest = Arrays.copyOfRange(file_content, 4, file_content.length); file_content = rest; }else{ file_content = null; } return i; } public static void main(String[] args) { char[] file_content = "fileInput".toCharArray(); System.out.println(Arrays.copyOfRange(file_content, 4, file_content.length)); } }
UTF-8
Java
1,231
java
Reader4.java
Java
[]
null
[]
/** * */ package chp1_ArrayAndString; import java.util.Arrays; public class Reader4 { /* # python code # The read4 API is already defined for you. # @param buf, a list of characters # @return an integer def read4(buf): global file_content i = 0 while i < len(file_content) and i < 4: buf[i] = file_content[i] i += 1 if len(file_content) > 4: file_content = file_content[4:] else: file_content = "" return i */ public int read4(char[] buf){ // read4 saves 4 char to buf ? char[] file_content = "fileInput".toCharArray(); int i = 0; while( i < file_content.length && i < 4){ buf[i] = file_content[i]; i += 1; } if(file_content.length > 4){ // System.arraycopy(src, srcPos, dest, destPos, length) //Arrays.copyOfRange(original, from, to); char[] rest = Arrays.copyOfRange(file_content, 4, file_content.length); file_content = rest; }else{ file_content = null; } return i; } public static void main(String[] args) { char[] file_content = "fileInput".toCharArray(); System.out.println(Arrays.copyOfRange(file_content, 4, file_content.length)); } }
1,231
0.584078
0.569456
57
19.596491
20.131027
79
false
false
0
0
0
0
0
0
1.403509
false
false
5
fae44f32b3446c08261e99d83b566397b6b1632d
23,527,830,904,284
52fbe7a7ed03593c05356c469bdb858c68d391d0
/src/main/java/org/demo/data/repository/jpa/StockCategoryJpaRepository.java
2f271970d355ef240a5ecd44a6bbb8d9d10a0379
[]
no_license
altansenel/maven-project
https://github.com/altansenel/maven-project
4d165cb10da24159f58d083f4d5e4442ab3265b2
0f2e392553e5fb031235c9df776a4a01b077c349
refs/heads/master
2016-08-12T05:51:51.359000
2016-02-25T07:26:28
2016-02-25T07:26:28
52,504,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.demo.data.repository.jpa; import org.springframework.data.repository.PagingAndSortingRepository; import org.demo.bean.jpa.StockCategoryEntity; /** * Repository : StockCategory. */ public interface StockCategoryJpaRepository extends PagingAndSortingRepository<StockCategoryEntity, Integer> { }
UTF-8
Java
310
java
StockCategoryJpaRepository.java
Java
[]
null
[]
package org.demo.data.repository.jpa; import org.springframework.data.repository.PagingAndSortingRepository; import org.demo.bean.jpa.StockCategoryEntity; /** * Repository : StockCategory. */ public interface StockCategoryJpaRepository extends PagingAndSortingRepository<StockCategoryEntity, Integer> { }
310
0.829032
0.829032
11
27.181818
34.622162
110
false
false
0
0
0
0
0
0
0.363636
false
false
5
f6e09c57fd5b6041ed66e797ae11918c112bf7b2
9,131,100,525,134
168e07e35fc53bec00e27be9f9d191a6a12b3376
/src/main/java/br/com/fabio/studentapi/exceptions/StudentNotFoundException.java
37c84f2eb34e6d4a9f954b890c370da4788dbe8a
[]
no_license
fabio-leandro/studentsapi
https://github.com/fabio-leandro/studentsapi
a9de9677927bd9cf022505e71ed556e08d5e33da
4087cd651a8e4e4bcccb52c46ece51f58a5601c1
refs/heads/main
2023-08-29T15:30:34.437000
2021-09-17T13:13:22
2021-09-17T13:13:22
400,502,122
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.fabio.studentapi.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class StudentNotFoundException extends Exception{ private static final long serialVersionUID = 1L; public StudentNotFoundException(Long id) { super(String.format("Student with ID %s not found!", id)); } }
UTF-8
Java
417
java
StudentNotFoundException.java
Java
[]
null
[]
package br.com.fabio.studentapi.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class StudentNotFoundException extends Exception{ private static final long serialVersionUID = 1L; public StudentNotFoundException(Long id) { super(String.format("Student with ID %s not found!", id)); } }
417
0.791367
0.788969
17
23.529411
24.848051
62
false
false
0
0
0
0
0
0
0.882353
false
false
5
1249f707ede95d158f9b8805f94651a1115de599
35,270,271,462,774
e334f5ecc5d3469c71b0539486e3c17fa0cdbd52
/MiRepaso/Tema2/ej2T2.java
23d1c5781f2f6092e2228be8cf296576a72249c7
[]
no_license
estherhitos/MiRepositorio
https://github.com/estherhitos/MiRepositorio
1de70c4566a0e3832c15df0ee4cdc8a5d6652011
1bed9bf9830551d67b985080bc3b02ee391c4824
refs/heads/master
2023-02-22T12:49:17.590000
2021-01-25T08:34:07
2021-01-25T08:34:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Ejercicio 2 | tema 2 * * Crea la variable nombre y asígnale tu nombre completo. Muestra su valor por * pantalla de tal forma que el resultado del programa sea el mismo que en el * ejercicio 1 del capítulo 1. * * * @autora Esther Hitos Garcia */ public class ej2T2{ public static void main(String [] args){ String nombre = "Esther Hitos Garcia"; System.out.println("Yo me llamo, "+ nombre); } }
UTF-8
Java
429
java
ej2T2.java
Java
[ { "context": "\n * ejercicio 1 del capítulo 1.\n * \n * \n * @autora Esther Hitos Garcia\n */ \n \npublic class ej2T2{\n public static void m", "end": 257, "score": 0.9998878240585327, "start": 238, "tag": "NAME", "value": "Esther Hitos Garcia" }, { "context": "tic void main(String [] args){\n String nombre = \"Esther Hitos Garcia\";\n\n System.out.println(\"Yo me llamo, \"+ nombre);", "end": 366, "score": 0.9998866319656372, "start": 347, "tag": "NAME", "value": "Esther Hitos Garcia" } ]
null
[]
/* * Ejercicio 2 | tema 2 * * Crea la variable nombre y asígnale tu nombre completo. Muestra su valor por * pantalla de tal forma que el resultado del programa sea el mismo que en el * ejercicio 1 del capítulo 1. * * * @autora <NAME> */ public class ej2T2{ public static void main(String [] args){ String nombre = "<NAME>"; System.out.println("Yo me llamo, "+ nombre); } }
403
0.674473
0.660422
19
21.473684
24.592186
78
false
false
0
0
0
0
0
0
0.263158
false
false
5
f0512c91a098d4f997fe5a94342f62c80a7f45ab
23,828,478,608,877
e9840acd552ab3dd135c2e815447cc02f34ef865
/items/src/main/java/eu/kgorecki/rpgame/items/domain/Type.java
7b34c29aaa4f10fa521c245e3c0e2829f6f9916d
[]
no_license
karolgurecki/rpgame
https://github.com/karolgurecki/rpgame
de7658bc9686cc867974f63ba5db96c8f882ba33
753e5d448d18041b7f53831cf1fed9357807266a
refs/heads/master
2021-06-16T05:51:01.352000
2019-06-27T19:54:33
2019-06-27T19:54:33
194,159,402
0
0
null
false
2021-04-26T19:17:25
2019-06-27T20:32:27
2019-06-27T20:34:42
2021-04-26T19:17:25
202
0
0
1
Java
false
false
package eu.kgorecki.rpgame.items.domain; public enum Type { WEAPON, SHIELD }
UTF-8
Java
86
java
Type.java
Java
[]
null
[]
package eu.kgorecki.rpgame.items.domain; public enum Type { WEAPON, SHIELD }
86
0.697674
0.697674
6
13.333333
13.412267
40
false
false
0
0
0
0
0
0
0.333333
false
false
5
7e4662e19ac04d4beae8529b6ae92b8bcbd1c031
35,150,012,378,319
73a528fa7a17c5d19c2474bde1e2d634552b058e
/pje-android/ProjetContact/app/src/main/java/com/example/projetcontact/NewGroupInContact.java
9b3d10feea802c8aeb6528598a3ad1b0afdf3abb
[]
no_license
GregPhi/m1s1
https://github.com/GregPhi/m1s1
87247305ed4a669478cadeaa31d3f99727038e1a
a60c0d21ee16200224840ce05a25455fad35676a
refs/heads/master
2020-08-01T20:52:13.916000
2020-01-07T15:50:49
2020-01-07T15:50:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.projetcontact; import android.content.Intent; import android.os.Bundle; import com.example.projetcontact.view.group.GroupViewModel; import com.example.projetcontact.view.contactgroup.GroupInContactListAdapter; import com.example.projetcontact.objet.Groups; import java.util.List; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class NewGroupInContact extends AppCompatActivity { public static GroupViewModel mGroupViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_group_in_contact); RecyclerView recyclerView = findViewById(R.id.recyclerview_grp_in_contact); final GroupInContactListAdapter adapter = new GroupInContactListAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); mGroupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class); mGroupViewModel.getmAllGroups().observe(this, new Observer<List<Groups>>() { @Override public void onChanged(@Nullable final List<Groups> groups) { // Update the cached copy of the words in the adapter. adapter.setGroups(groups); } }); } public void addGroup(int id, Groups groups){ Intent intent = new Intent(NewGroupInContact.this, InfoContactActivity.class); intent.putExtra("Id",id); intent.putExtra("Groups",groups); setResult(RESULT_OK, intent); finish(); } }
UTF-8
Java
1,828
java
NewGroupInContact.java
Java
[]
null
[]
package com.example.projetcontact; import android.content.Intent; import android.os.Bundle; import com.example.projetcontact.view.group.GroupViewModel; import com.example.projetcontact.view.contactgroup.GroupInContactListAdapter; import com.example.projetcontact.objet.Groups; import java.util.List; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class NewGroupInContact extends AppCompatActivity { public static GroupViewModel mGroupViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_group_in_contact); RecyclerView recyclerView = findViewById(R.id.recyclerview_grp_in_contact); final GroupInContactListAdapter adapter = new GroupInContactListAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); mGroupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class); mGroupViewModel.getmAllGroups().observe(this, new Observer<List<Groups>>() { @Override public void onChanged(@Nullable final List<Groups> groups) { // Update the cached copy of the words in the adapter. adapter.setGroups(groups); } }); } public void addGroup(int id, Groups groups){ Intent intent = new Intent(NewGroupInContact.this, InfoContactActivity.class); intent.putExtra("Id",id); intent.putExtra("Groups",groups); setResult(RESULT_OK, intent); finish(); } }
1,828
0.734683
0.734683
48
37.083332
27.327362
86
false
false
0
0
0
0
0
0
0.708333
false
false
5
5a71fec861625b2ef9e4f62079fccce1c68aea62
4,028,679,365,775
d2af0633e063e055ec8f93bd8d3e91e750bb8488
/src/dss/views/sections/detail/Detail.java
76bfc054a0fca17068466c53a905c610665f42a5
[]
no_license
semgroup15/dss
https://github.com/semgroup15/dss
32f9c8daffc2a3df9c630184ca4bfc472ec811f0
4318586b169ff7ad876f0fc2bdf01565fb05ce57
refs/heads/master
2021-01-01T19:10:30.470000
2016-01-04T20:19:13
2016-01-04T20:19:13
42,875,199
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dss.views.sections.detail; import dss.Developer; import dss.models.base.Model; import dss.models.device.Device; import dss.models.review.Review; import dss.views.base.State; import dss.views.base.Widget; import dss.views.base.components.Rating; import dss.views.sections.detail.fields.*; import dss.views.sections.detail.fields.base.DeviceBinding; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.util.Callback; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URL; import java.util.ResourceBundle; @Developer({ Developer.Value.ISAR, Developer.Value.JIM, }) public class Detail extends Widget implements Initializable, State.LevelListener, Model.Observer.Listener<Review> { @FXML ImageView image; @FXML Rating overallRating; @FXML Rating responsivenessRating; @FXML Rating screenRating; @FXML Rating batteryRating; @FXML NameField name; @FXML ManufacturerField manufacturer; @FXML PlatformField platform; @FXML SIMField sim; @FXML DisplayField display; @FXML BodyField body; @FXML ColorField color; @FXML BatteryField battery; @FXML CameraField camera; @FXML ComField com; @FXML SensorField sensor; @FXML MemoryField memory; @FXML SlotField slot; @FXML NetworkField network; @FXML SoundField sound; @FXML Button save; @FXML Button delete; @FXML Label login; @FXML ListView<Review> reviews; @FXML VBox review; @FXML TextArea text; @FXML Button submit; private DeviceBinding[] bindings() { return new DeviceBinding[]{ name, manufacturer, platform, sim, display, body, color, battery, camera, com, sensor, memory, slot, network, sound }; } private Device device; public void setDevice(Device device) { this.device = device; File file = device.getImageFile(); if (file == null) { image.setVisible(false); image.setManaged(false); } else { image.setVisible(true); image.setManaged(true); try { image.setImage(new Image(new FileInputStream(file))); } catch (FileNotFoundException exception) { // Image not found } } for (DeviceBinding binding : bindings()) { binding.syncFromDevice(device); } overallRating.setValue(device.overallRating); responsivenessRating.setValue(device.responsivenessRating); screenRating.setValue(device.screenRating); batteryRating.setValue(device.batteryRating); setReviewVisible(false); // Load reviews reviews.setItems(FXCollections.observableArrayList(device.getReviews())); } @FXML public void initialize(URL location, ResourceBundle resourceBundle) { responsivenessRating.addListener((value) -> setReviewVisible(true)); screenRating.addListener((value) -> setReviewVisible(true)); batteryRating.addListener((value) -> setReviewVisible(true)); // Listen to state State.get().addLevelListener(this); // Listen to review changes Review.observer.addListener(this); // Set reviews list cell factory reviews.setCellFactory(new Callback<ListView<Review>, ListCell<Review>>() { @Override public ListCell<Review> call(ListView<Review> reviewListView) { return new ReviewCell(); } }); } @Override public void onLevelChange(State.Level level) { switch (level) { case ANONYMOUS: save.setVisible(false); save.setManaged(false); delete.setVisible(false); delete.setManaged(false); login.setVisible(true); login.setManaged(true); break; case AUTHORIZED: save.setVisible(true); save.setManaged(true); delete.setVisible(true); delete.setManaged(true); login.setVisible(false); login.setManaged(false); break; } } @Override public void onModelEvent(Model.Observer.Event event, Review review) { switch (event) { case DELETE: reviews.getItems().remove(review); break; case INSERT: if (review.deviceId == device.id) { reviews.getItems().add(review); } break; } } @FXML public void onDelete() { // Delete device device.delete(); // Leave detail view State state = State.get(); state.setLocation(new State.Location(State.Location.Section.LISTING)); } @FXML public void onSave() { for (DeviceBinding binding : bindings()) { binding.syncToDevice(device); } // Save device device.save(); // Leave detail view State state = State.get(); state.setLocation(new State.Location(State.Location.Section.LISTING)); } private void setReviewVisible(boolean visible) { review.setVisible(visible); review.setManaged(visible); text.setText(""); if (visible) { setReviewDone(false); } } private void setReviewDone(boolean done) { text.setDisable(done); submit.setDisable(done); submit.setText(done ? "Submitted" : "Submit"); } /** * Submit text review. */ @FXML @Developer({ Developer.Value.ISAR, Developer.Value.JIM, }) public void onSubmit() { setReviewDone(true); // Create review Review review = new Review(); review.deviceId = device.id; review.text = text.getText(); review.responsiveness = responsivenessRating.getValue(); review.screen = screenRating.getValue(); review.battery = batteryRating.getValue(); review.save(); } }
UTF-8
Java
6,674
java
Detail.java
Java
[]
null
[]
package dss.views.sections.detail; import dss.Developer; import dss.models.base.Model; import dss.models.device.Device; import dss.models.review.Review; import dss.views.base.State; import dss.views.base.Widget; import dss.views.base.components.Rating; import dss.views.sections.detail.fields.*; import dss.views.sections.detail.fields.base.DeviceBinding; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.util.Callback; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URL; import java.util.ResourceBundle; @Developer({ Developer.Value.ISAR, Developer.Value.JIM, }) public class Detail extends Widget implements Initializable, State.LevelListener, Model.Observer.Listener<Review> { @FXML ImageView image; @FXML Rating overallRating; @FXML Rating responsivenessRating; @FXML Rating screenRating; @FXML Rating batteryRating; @FXML NameField name; @FXML ManufacturerField manufacturer; @FXML PlatformField platform; @FXML SIMField sim; @FXML DisplayField display; @FXML BodyField body; @FXML ColorField color; @FXML BatteryField battery; @FXML CameraField camera; @FXML ComField com; @FXML SensorField sensor; @FXML MemoryField memory; @FXML SlotField slot; @FXML NetworkField network; @FXML SoundField sound; @FXML Button save; @FXML Button delete; @FXML Label login; @FXML ListView<Review> reviews; @FXML VBox review; @FXML TextArea text; @FXML Button submit; private DeviceBinding[] bindings() { return new DeviceBinding[]{ name, manufacturer, platform, sim, display, body, color, battery, camera, com, sensor, memory, slot, network, sound }; } private Device device; public void setDevice(Device device) { this.device = device; File file = device.getImageFile(); if (file == null) { image.setVisible(false); image.setManaged(false); } else { image.setVisible(true); image.setManaged(true); try { image.setImage(new Image(new FileInputStream(file))); } catch (FileNotFoundException exception) { // Image not found } } for (DeviceBinding binding : bindings()) { binding.syncFromDevice(device); } overallRating.setValue(device.overallRating); responsivenessRating.setValue(device.responsivenessRating); screenRating.setValue(device.screenRating); batteryRating.setValue(device.batteryRating); setReviewVisible(false); // Load reviews reviews.setItems(FXCollections.observableArrayList(device.getReviews())); } @FXML public void initialize(URL location, ResourceBundle resourceBundle) { responsivenessRating.addListener((value) -> setReviewVisible(true)); screenRating.addListener((value) -> setReviewVisible(true)); batteryRating.addListener((value) -> setReviewVisible(true)); // Listen to state State.get().addLevelListener(this); // Listen to review changes Review.observer.addListener(this); // Set reviews list cell factory reviews.setCellFactory(new Callback<ListView<Review>, ListCell<Review>>() { @Override public ListCell<Review> call(ListView<Review> reviewListView) { return new ReviewCell(); } }); } @Override public void onLevelChange(State.Level level) { switch (level) { case ANONYMOUS: save.setVisible(false); save.setManaged(false); delete.setVisible(false); delete.setManaged(false); login.setVisible(true); login.setManaged(true); break; case AUTHORIZED: save.setVisible(true); save.setManaged(true); delete.setVisible(true); delete.setManaged(true); login.setVisible(false); login.setManaged(false); break; } } @Override public void onModelEvent(Model.Observer.Event event, Review review) { switch (event) { case DELETE: reviews.getItems().remove(review); break; case INSERT: if (review.deviceId == device.id) { reviews.getItems().add(review); } break; } } @FXML public void onDelete() { // Delete device device.delete(); // Leave detail view State state = State.get(); state.setLocation(new State.Location(State.Location.Section.LISTING)); } @FXML public void onSave() { for (DeviceBinding binding : bindings()) { binding.syncToDevice(device); } // Save device device.save(); // Leave detail view State state = State.get(); state.setLocation(new State.Location(State.Location.Section.LISTING)); } private void setReviewVisible(boolean visible) { review.setVisible(visible); review.setManaged(visible); text.setText(""); if (visible) { setReviewDone(false); } } private void setReviewDone(boolean done) { text.setDisable(done); submit.setDisable(done); submit.setText(done ? "Submitted" : "Submit"); } /** * Submit text review. */ @FXML @Developer({ Developer.Value.ISAR, Developer.Value.JIM, }) public void onSubmit() { setReviewDone(true); // Create review Review review = new Review(); review.deviceId = device.id; review.text = text.getText(); review.responsiveness = responsivenessRating.getValue(); review.screen = screenRating.getValue(); review.battery = batteryRating.getValue(); review.save(); } }
6,674
0.58226
0.58226
300
21.246666
18.800508
83
false
false
0
0
0
0
0
0
0.453333
false
false
5
d03084f5dd0ab610e1cc10f0f54b052a6739fab1
35,192,962,049,247
bf3acf44455aff71f08e0143e7c0d36c45181c41
/src/org/opensha/refFaultParamDb/dao/db/DeformationModelPrefDataDB_DAO.java
790397973a87365fc8045da13b6b02f8b54d3907
[]
no_license
bpeng/step_opensha
https://github.com/bpeng/step_opensha
52d03d78c7135d3b63aa7708228410ac14312f23
520a2741467f13568a78253d9107b129a48d0d15
refs/heads/master
2021-02-09T15:20:38.516000
2020-03-02T21:29:06
2020-03-02T21:59:20
244,296,857
0
0
null
false
2021-07-11T21:04:08
2020-03-02T06:28:06
2020-03-02T22:05:58
2020-04-20T01:24:39
36,872
0
0
0
Java
false
false
/** * */ package org.opensha.refFaultParamDb.dao.db; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import org.opensha.commons.data.estimate.NormalEstimate; import org.opensha.refFaultParamDb.dao.exception.InsertException; import org.opensha.refFaultParamDb.dao.exception.QueryException; import org.opensha.refFaultParamDb.dao.exception.UpdateException; import org.opensha.refFaultParamDb.gui.infotools.SessionInfo; import org.opensha.refFaultParamDb.vo.DeformationModelSummary; import org.opensha.refFaultParamDb.vo.EstimateInstances; import org.opensha.refFaultParamDb.vo.FaultSectionData; import org.opensha.refFaultParamDb.vo.FaultSectionPrefData; /** * * Get the preferred slip and aseismic slip factor from the deformation model * * @author vipingupta * */ public class DeformationModelPrefDataDB_DAO { private final static String TABLE_NAME = "Pref_Deformation_Model_Data"; private final static String DEFORMATION_MODEL_ID = "Deformation_Model_Id"; private final static String SECTION_ID = "Section_Id"; private final static String PREF_LONG_TERM_SLIP_RATE = "Pref_Long_Term_Slip_Rate"; private final static String SLIP_STD_DEV = "Slip_Std_Dev"; private final static String PREF_ASEISMIC_SLIP = "Pref_Aseismic_Slip"; private static HashMap slipRateMap; private static HashMap aseismicSlipMap; private static HashMap stdDevMap; private static int selectedDefModelId = -1; private DB_AccessAPI dbAccess; private PrefFaultSectionDataDB_DAO prefFaultSectionDAO; private DeformationModelDB_DAO deformationModelDB_DAO; private static ArrayList faultSectionIdList; public DeformationModelPrefDataDB_DAO(DB_AccessAPI dbAccess) { setDB_Connection(dbAccess); } /** * Set the database connection * @param dbAccess */ public void setDB_Connection(DB_AccessAPI dbAccess) { this.dbAccess = dbAccess; prefFaultSectionDAO = new PrefFaultSectionDataDB_DAO(dbAccess); deformationModelDB_DAO = new DeformationModelDB_DAO(dbAccess); } /** * Remove the exisiting data from preferred data table and re-populate it. * */ public void rePopulatePrefDataTable() { removeAll(); // remove all the pref data // iterate over all deformation Models DeformationModelSummaryDB_DAO defModelSumDAO = new DeformationModelSummaryDB_DAO(this.dbAccess); ArrayList deformationModelList = defModelSumDAO.getAllDeformationModels(); int faultSectionId, deformationModelId; double aseismicSlipFactor, slipRate; for(int i=0; i<deformationModelList.size(); ++i) { DeformationModelSummary defModelSummary = (DeformationModelSummary)deformationModelList.get(i); deformationModelId = defModelSummary.getDeformationModelId(); // get the fault sections in each deformation model ArrayList faultSectionIdList = deformationModelDB_DAO.getFaultSectionIdsForDeformationModel(deformationModelId); for(int j=0; j<faultSectionIdList.size(); ++j) { faultSectionId = ((Integer)faultSectionIdList.get(j)).intValue(); aseismicSlipFactor = FaultSectionData.getPrefForEstimate(deformationModelDB_DAO.getAseismicSlipEstimate(deformationModelId, faultSectionId)); /*if(aseismicSlipFactor==1) { System.out.println(deformationModelId+","+faultSectionId+","+deformationModelDB_DAO.getAseismicSlipEstimate(deformationModelId, faultSectionId)); System.exit(0); }*/ EstimateInstances estimateInstance = deformationModelDB_DAO.getSlipRateEstimate(deformationModelId, faultSectionId); slipRate = FaultSectionData.getPrefForEstimate(estimateInstance); double slipRateStdDev = Double.NaN; //System.out.println(faultSectionId); if(!Double.isNaN(slipRate)) { if(estimateInstance.getEstimate() instanceof NormalEstimate) slipRateStdDev = ((NormalEstimate)estimateInstance.getEstimate()).getStdDev(); } addToTable(deformationModelId, faultSectionId, aseismicSlipFactor, slipRate, slipRateStdDev); } } } /** * Add data to table * @param deformationModelId * @param faultSectionId * @param aseismicSlipFactor * @param slipRate */ private void addToTable(int deformationModelId, int faultSectionId, double aseismicSlipFactor, double slipRate, double slipRateStdDev) { String columnNames = ""; String colVals = ""; if(!Double.isNaN(slipRate)) { columnNames +=PREF_LONG_TERM_SLIP_RATE+","; colVals +=slipRate+","; } if(!Double.isNaN(slipRateStdDev)) { columnNames +=SLIP_STD_DEV+","; colVals +=slipRateStdDev+","; } String sql = "insert into "+TABLE_NAME+" ("+DEFORMATION_MODEL_ID+","+ SECTION_ID+","+columnNames+PREF_ASEISMIC_SLIP+") values ("+ deformationModelId+","+faultSectionId+","+colVals+aseismicSlipFactor+")"; try { dbAccess.insertUpdateOrDeleteData(sql); } catch(SQLException e) { throw new InsertException(e.getMessage()); } } /** * Get a list of all fault sections within this deformation model * @param deformationModelId * @return */ public ArrayList getFaultSectionIdsForDeformationModel(int deformationModelId) { if(selectedDefModelId!=deformationModelId) this.cache(deformationModelId); return faultSectionIdList; } /** * Get Fault Section Pref data for a deformation model ID and Fault section Id * @param deformationModelId * @param faultSectionId * @return */ public FaultSectionPrefData getFaultSectionPrefData(int deformationModelId, int faultSectionId) { FaultSectionPrefData faultSectionPrefData = prefFaultSectionDAO.getFaultSectionPrefData(faultSectionId); // get slip rate and aseimic slip factor from deformation model faultSectionPrefData.setAseismicSlipFactor(this.getAseismicSlipFactor(deformationModelId, faultSectionId)); faultSectionPrefData.setAveLongTermSlipRate(this.getSlipRate(deformationModelId, faultSectionId)); faultSectionPrefData.setSlipRateStdDev(this.getSlipStdDev(deformationModelId, faultSectionId)); return faultSectionPrefData; } /** * Get the preferred Slip Rate value for selected Deformation Model and Fault Section * Returns NaN if Slip rate is not available * * @param deformationModelId * @param faultSectionId * @return */ public double getSlipRate(int deformationModelId, int faultSectionId) { if(this.selectedDefModelId!=deformationModelId) this.cache(deformationModelId); Double slipRate = (Double)slipRateMap.get(new Integer(faultSectionId)); if(slipRate==null) return Double.NaN; else return slipRate.doubleValue(); } /** * Get the Std Dev for Slip Rate value for selected Deformation Model and Fault Section * Returns NaN if Std Dev is not available * * @param deformationModelId * @param faultSectionId * @return */ public double getSlipStdDev(int deformationModelId, int faultSectionId) { if(this.selectedDefModelId!=deformationModelId) this.cache(deformationModelId); Double stdDev = (Double)stdDevMap.get(new Integer(faultSectionId)); if(stdDev==null) return Double.NaN; else return stdDev.doubleValue(); } /** * Get the preferred Aseismic Slip Factor for selected Deformation Model and Fault Section * * * @param deformationModelId * @param faultSectionId * @return */ public double getAseismicSlipFactor(int deformationModelId, int faultSectionId) { if(this.selectedDefModelId!=deformationModelId) this.cache(deformationModelId); Double aseismicSlip = (Double)aseismicSlipMap.get(new Integer(faultSectionId)); if(aseismicSlip == null) return Double.NaN; else return aseismicSlip.doubleValue(); } private void cache(int defModelId) { slipRateMap = new HashMap(); aseismicSlipMap = new HashMap(); stdDevMap = new HashMap(); faultSectionIdList = new ArrayList(); String sql= "select "+SECTION_ID+"," + " ("+PREF_ASEISMIC_SLIP+"+0) "+PREF_ASEISMIC_SLIP+","+ " ("+SLIP_STD_DEV+"+0) "+SLIP_STD_DEV+","+ " ("+PREF_LONG_TERM_SLIP_RATE+"+0) "+PREF_LONG_TERM_SLIP_RATE+ " from "+TABLE_NAME+" where " + DEFORMATION_MODEL_ID+"="+defModelId; double aseismicSlipFactor=Double.NaN,slip=Double.NaN, stdDev=Double.NaN; Integer sectionId; try { ResultSet rs = this.dbAccess.queryData(sql); while(rs.next()) { aseismicSlipFactor = rs.getFloat(PREF_ASEISMIC_SLIP); if(rs.wasNull()) aseismicSlipFactor = Double.NaN; slip = rs.getFloat(PREF_LONG_TERM_SLIP_RATE); if(rs.wasNull()) slip = Double.NaN; stdDev = rs.getFloat(SLIP_STD_DEV); if(rs.wasNull()) stdDev = Double.NaN; sectionId = new Integer(rs.getInt(SECTION_ID)); this.faultSectionIdList.add(sectionId); slipRateMap.put(sectionId, new Double(slip)) ; aseismicSlipMap.put(sectionId, new Double(aseismicSlipFactor)); stdDevMap.put(sectionId, new Double(stdDev)); } } catch (SQLException e) { throw new QueryException(e.getMessage()); } this.selectedDefModelId = defModelId; } /** * Remove all preferred data */ private void removeAll() { String sql = "delete from "+TABLE_NAME; try { dbAccess.insertUpdateOrDeleteData(sql); } catch(SQLException e) { throw new UpdateException(e.getMessage()); } } public static void main(String[] args) { DB_AccessAPI dbAccessAPI = new ServerDB_Access(); SessionInfo.setUserName(args[0]); SessionInfo.setPassword(args[1]); SessionInfo.setContributorInfo(); DeformationModelPrefDataDB_DAO defModelPrefDataDB_DAO = new DeformationModelPrefDataDB_DAO(dbAccessAPI); defModelPrefDataDB_DAO.rePopulatePrefDataTable(); System.exit(0); } }
UTF-8
Java
9,475
java
DeformationModelPrefDataDB_DAO.java
Java
[ { "context": "p factor from the deformation model\n * \n * @author vipingupta\n *\n */\npublic class DeformationModelPrefDataDB_DA", "end": 833, "score": 0.9976691007614136, "start": 823, "tag": "USERNAME", "value": "vipingupta" } ]
null
[]
/** * */ package org.opensha.refFaultParamDb.dao.db; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import org.opensha.commons.data.estimate.NormalEstimate; import org.opensha.refFaultParamDb.dao.exception.InsertException; import org.opensha.refFaultParamDb.dao.exception.QueryException; import org.opensha.refFaultParamDb.dao.exception.UpdateException; import org.opensha.refFaultParamDb.gui.infotools.SessionInfo; import org.opensha.refFaultParamDb.vo.DeformationModelSummary; import org.opensha.refFaultParamDb.vo.EstimateInstances; import org.opensha.refFaultParamDb.vo.FaultSectionData; import org.opensha.refFaultParamDb.vo.FaultSectionPrefData; /** * * Get the preferred slip and aseismic slip factor from the deformation model * * @author vipingupta * */ public class DeformationModelPrefDataDB_DAO { private final static String TABLE_NAME = "Pref_Deformation_Model_Data"; private final static String DEFORMATION_MODEL_ID = "Deformation_Model_Id"; private final static String SECTION_ID = "Section_Id"; private final static String PREF_LONG_TERM_SLIP_RATE = "Pref_Long_Term_Slip_Rate"; private final static String SLIP_STD_DEV = "Slip_Std_Dev"; private final static String PREF_ASEISMIC_SLIP = "Pref_Aseismic_Slip"; private static HashMap slipRateMap; private static HashMap aseismicSlipMap; private static HashMap stdDevMap; private static int selectedDefModelId = -1; private DB_AccessAPI dbAccess; private PrefFaultSectionDataDB_DAO prefFaultSectionDAO; private DeformationModelDB_DAO deformationModelDB_DAO; private static ArrayList faultSectionIdList; public DeformationModelPrefDataDB_DAO(DB_AccessAPI dbAccess) { setDB_Connection(dbAccess); } /** * Set the database connection * @param dbAccess */ public void setDB_Connection(DB_AccessAPI dbAccess) { this.dbAccess = dbAccess; prefFaultSectionDAO = new PrefFaultSectionDataDB_DAO(dbAccess); deformationModelDB_DAO = new DeformationModelDB_DAO(dbAccess); } /** * Remove the exisiting data from preferred data table and re-populate it. * */ public void rePopulatePrefDataTable() { removeAll(); // remove all the pref data // iterate over all deformation Models DeformationModelSummaryDB_DAO defModelSumDAO = new DeformationModelSummaryDB_DAO(this.dbAccess); ArrayList deformationModelList = defModelSumDAO.getAllDeformationModels(); int faultSectionId, deformationModelId; double aseismicSlipFactor, slipRate; for(int i=0; i<deformationModelList.size(); ++i) { DeformationModelSummary defModelSummary = (DeformationModelSummary)deformationModelList.get(i); deformationModelId = defModelSummary.getDeformationModelId(); // get the fault sections in each deformation model ArrayList faultSectionIdList = deformationModelDB_DAO.getFaultSectionIdsForDeformationModel(deformationModelId); for(int j=0; j<faultSectionIdList.size(); ++j) { faultSectionId = ((Integer)faultSectionIdList.get(j)).intValue(); aseismicSlipFactor = FaultSectionData.getPrefForEstimate(deformationModelDB_DAO.getAseismicSlipEstimate(deformationModelId, faultSectionId)); /*if(aseismicSlipFactor==1) { System.out.println(deformationModelId+","+faultSectionId+","+deformationModelDB_DAO.getAseismicSlipEstimate(deformationModelId, faultSectionId)); System.exit(0); }*/ EstimateInstances estimateInstance = deformationModelDB_DAO.getSlipRateEstimate(deformationModelId, faultSectionId); slipRate = FaultSectionData.getPrefForEstimate(estimateInstance); double slipRateStdDev = Double.NaN; //System.out.println(faultSectionId); if(!Double.isNaN(slipRate)) { if(estimateInstance.getEstimate() instanceof NormalEstimate) slipRateStdDev = ((NormalEstimate)estimateInstance.getEstimate()).getStdDev(); } addToTable(deformationModelId, faultSectionId, aseismicSlipFactor, slipRate, slipRateStdDev); } } } /** * Add data to table * @param deformationModelId * @param faultSectionId * @param aseismicSlipFactor * @param slipRate */ private void addToTable(int deformationModelId, int faultSectionId, double aseismicSlipFactor, double slipRate, double slipRateStdDev) { String columnNames = ""; String colVals = ""; if(!Double.isNaN(slipRate)) { columnNames +=PREF_LONG_TERM_SLIP_RATE+","; colVals +=slipRate+","; } if(!Double.isNaN(slipRateStdDev)) { columnNames +=SLIP_STD_DEV+","; colVals +=slipRateStdDev+","; } String sql = "insert into "+TABLE_NAME+" ("+DEFORMATION_MODEL_ID+","+ SECTION_ID+","+columnNames+PREF_ASEISMIC_SLIP+") values ("+ deformationModelId+","+faultSectionId+","+colVals+aseismicSlipFactor+")"; try { dbAccess.insertUpdateOrDeleteData(sql); } catch(SQLException e) { throw new InsertException(e.getMessage()); } } /** * Get a list of all fault sections within this deformation model * @param deformationModelId * @return */ public ArrayList getFaultSectionIdsForDeformationModel(int deformationModelId) { if(selectedDefModelId!=deformationModelId) this.cache(deformationModelId); return faultSectionIdList; } /** * Get Fault Section Pref data for a deformation model ID and Fault section Id * @param deformationModelId * @param faultSectionId * @return */ public FaultSectionPrefData getFaultSectionPrefData(int deformationModelId, int faultSectionId) { FaultSectionPrefData faultSectionPrefData = prefFaultSectionDAO.getFaultSectionPrefData(faultSectionId); // get slip rate and aseimic slip factor from deformation model faultSectionPrefData.setAseismicSlipFactor(this.getAseismicSlipFactor(deformationModelId, faultSectionId)); faultSectionPrefData.setAveLongTermSlipRate(this.getSlipRate(deformationModelId, faultSectionId)); faultSectionPrefData.setSlipRateStdDev(this.getSlipStdDev(deformationModelId, faultSectionId)); return faultSectionPrefData; } /** * Get the preferred Slip Rate value for selected Deformation Model and Fault Section * Returns NaN if Slip rate is not available * * @param deformationModelId * @param faultSectionId * @return */ public double getSlipRate(int deformationModelId, int faultSectionId) { if(this.selectedDefModelId!=deformationModelId) this.cache(deformationModelId); Double slipRate = (Double)slipRateMap.get(new Integer(faultSectionId)); if(slipRate==null) return Double.NaN; else return slipRate.doubleValue(); } /** * Get the Std Dev for Slip Rate value for selected Deformation Model and Fault Section * Returns NaN if Std Dev is not available * * @param deformationModelId * @param faultSectionId * @return */ public double getSlipStdDev(int deformationModelId, int faultSectionId) { if(this.selectedDefModelId!=deformationModelId) this.cache(deformationModelId); Double stdDev = (Double)stdDevMap.get(new Integer(faultSectionId)); if(stdDev==null) return Double.NaN; else return stdDev.doubleValue(); } /** * Get the preferred Aseismic Slip Factor for selected Deformation Model and Fault Section * * * @param deformationModelId * @param faultSectionId * @return */ public double getAseismicSlipFactor(int deformationModelId, int faultSectionId) { if(this.selectedDefModelId!=deformationModelId) this.cache(deformationModelId); Double aseismicSlip = (Double)aseismicSlipMap.get(new Integer(faultSectionId)); if(aseismicSlip == null) return Double.NaN; else return aseismicSlip.doubleValue(); } private void cache(int defModelId) { slipRateMap = new HashMap(); aseismicSlipMap = new HashMap(); stdDevMap = new HashMap(); faultSectionIdList = new ArrayList(); String sql= "select "+SECTION_ID+"," + " ("+PREF_ASEISMIC_SLIP+"+0) "+PREF_ASEISMIC_SLIP+","+ " ("+SLIP_STD_DEV+"+0) "+SLIP_STD_DEV+","+ " ("+PREF_LONG_TERM_SLIP_RATE+"+0) "+PREF_LONG_TERM_SLIP_RATE+ " from "+TABLE_NAME+" where " + DEFORMATION_MODEL_ID+"="+defModelId; double aseismicSlipFactor=Double.NaN,slip=Double.NaN, stdDev=Double.NaN; Integer sectionId; try { ResultSet rs = this.dbAccess.queryData(sql); while(rs.next()) { aseismicSlipFactor = rs.getFloat(PREF_ASEISMIC_SLIP); if(rs.wasNull()) aseismicSlipFactor = Double.NaN; slip = rs.getFloat(PREF_LONG_TERM_SLIP_RATE); if(rs.wasNull()) slip = Double.NaN; stdDev = rs.getFloat(SLIP_STD_DEV); if(rs.wasNull()) stdDev = Double.NaN; sectionId = new Integer(rs.getInt(SECTION_ID)); this.faultSectionIdList.add(sectionId); slipRateMap.put(sectionId, new Double(slip)) ; aseismicSlipMap.put(sectionId, new Double(aseismicSlipFactor)); stdDevMap.put(sectionId, new Double(stdDev)); } } catch (SQLException e) { throw new QueryException(e.getMessage()); } this.selectedDefModelId = defModelId; } /** * Remove all preferred data */ private void removeAll() { String sql = "delete from "+TABLE_NAME; try { dbAccess.insertUpdateOrDeleteData(sql); } catch(SQLException e) { throw new UpdateException(e.getMessage()); } } public static void main(String[] args) { DB_AccessAPI dbAccessAPI = new ServerDB_Access(); SessionInfo.setUserName(args[0]); SessionInfo.setPassword(args[1]); SessionInfo.setContributorInfo(); DeformationModelPrefDataDB_DAO defModelPrefDataDB_DAO = new DeformationModelPrefDataDB_DAO(dbAccessAPI); defModelPrefDataDB_DAO.rePopulatePrefDataTable(); System.exit(0); } }
9,475
0.755356
0.754195
255
36.156864
30.967897
150
false
false
0
0
0
0
0
0
2.247059
false
false
5
45536fc6ab1bf3a4ae3642a8a3700f5af291547c
24,988,119,788,139
de15633a08c9a4771226cfbbb291e599c7dbaea4
/app/src/main/java/com/telpa/ecommerce/activities/activityM/IScreenMView.java
78a2bbbb7d460e4f244c63f722485eecaae0d68e
[]
no_license
metalcoder/E-Commerce
https://github.com/metalcoder/E-Commerce
8dda594f5fdeca9bea3713e873ea62a5faf90b4f
618d74315f9832d376e29a2d2fe8ade1aee553bf
refs/heads/master
2020-05-22T05:44:16.653000
2017-04-14T11:25:21
2017-04-14T11:25:21
63,149,806
6
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.telpa.ecommerce.activities.activityM; /** * Created by musta on 17.08.2016. */ public interface IScreenMView { void proceedClick(); void itemUp(int price); void itemDown(int price); void setTexts(int price,int number); }
UTF-8
Java
252
java
IScreenMView.java
Java
[ { "context": "ecommerce.activities.activityM;\n\n/**\n * Created by musta on 17.08.2016.\n */\npublic interface IScreenMView ", "end": 74, "score": 0.9948697090148926, "start": 69, "tag": "USERNAME", "value": "musta" } ]
null
[]
package com.telpa.ecommerce.activities.activityM; /** * Created by musta on 17.08.2016. */ public interface IScreenMView { void proceedClick(); void itemUp(int price); void itemDown(int price); void setTexts(int price,int number); }
252
0.702381
0.670635
11
21.90909
16.522461
49
false
false
0
0
0
0
0
0
0.545455
false
false
5
38b78f55fda5c4cca16b3cbadaefcb44c5c15a9b
26,087,631,414,319
b20f460803574a4c6a4849333ab0172786c7517a
/src/main/java/com/sevil/starblocksmod/blocks/BlockBeamCornerSouthB.java
1a39ab12670829784702ff9f847f4f7fcb116873
[]
no_license
fronczek7f/StarBlocksMod
https://github.com/fronczek7f/StarBlocksMod
fc994f47c09f74edb128bdf8d4897013f40de3bd
40b884776bf44781edce04323fb9ebb2e59b475c
refs/heads/master
2019-03-21T01:33:36.965000
2018-06-29T10:06:39
2018-06-29T10:10:57
124,087,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sevil.starblocksmod.blocks; import com.sevil.starblocksmod.blocks.entityblock.TileEntityBeamCornerSouthB; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class BlockBeamCornerSouthB extends BlockContainer { public BlockBeamCornerSouthB(String unlocalizedName, Material material) { super(material); this.setBlockName(unlocalizedName); this.setHardness(2.0F); this.setResistance(6.0F); this.setStepSound(soundTypeMetal); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileEntityBeamCornerSouthB(); } @Override public void registerBlockIcons(IIconRegister reg) {} public int getRenderType() { return -1; } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public int getRenderBlockPass() { return 1; } @Override public int damageDropped(int meta) { return meta; } }
UTF-8
Java
1,204
java
BlockBeamCornerSouthB.java
Java
[]
null
[]
package com.sevil.starblocksmod.blocks; import com.sevil.starblocksmod.blocks.entityblock.TileEntityBeamCornerSouthB; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class BlockBeamCornerSouthB extends BlockContainer { public BlockBeamCornerSouthB(String unlocalizedName, Material material) { super(material); this.setBlockName(unlocalizedName); this.setHardness(2.0F); this.setResistance(6.0F); this.setStepSound(soundTypeMetal); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileEntityBeamCornerSouthB(); } @Override public void registerBlockIcons(IIconRegister reg) {} public int getRenderType() { return -1; } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public int getRenderBlockPass() { return 1; } @Override public int damageDropped(int meta) { return meta; } }
1,204
0.716777
0.711794
49
22.571428
22.006493
77
false
false
0
0
0
0
0
0
1.040816
false
false
5
b08f1e61fb734c389d2e506a95c8ad84a878ea3b
377,957,125,323
bc0f3e90e66936846e4eff3223ea8f05c306dfdc
/src/Main67.java
70b91a8f4070494e96fdbb1d33b39df590227e8b
[]
no_license
myobot/JavaPrograms
https://github.com/myobot/JavaPrograms
e92f17f9eac662095dc9207e09a8593bf30e8b48
a0e4895dd7a477dd40fc8ff109c732058a38ffda
refs/heads/master
2021-01-20T04:04:26.756000
2017-08-25T07:51:42
2017-08-25T07:51:42
101,379,783
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Created by WZW on 2017/08/11. */ import java.util.*; public class Main67{ public static void main(String args[]) { Scanner in = new Scanner(System.in); String str = in.nextLine(); String s[] = str.split(" "); char c[] = s[0].toCharArray(); char c2[] = s[1].toCharArray(); int a[] = new int[c.length]; int b[] = new int[c2.length]; boolean flag = true; for (int i = 0; i < c.length; i++) { if (c[i] > '9' || c[i] < '0') { flag = false; } a[i] = c[i] - '0'; } for (int i = 0; i < c2.length; i++) { if (c2[i] > '9' || c2[i] < '0') { flag = false; } b[i] = c2[i] - '0'; } if (flag) { int d[] = new int[Math.max(a.length, b.length) + 1]; int indexa = a.length - 1; int indexb = b.length - 1; int indexd = d.length - 1; while (indexa >= 0 && indexb >= 0) { d[indexd--] = a[indexa--] + b[indexb--]; } while (indexa >= 0) { d[indexd--] = a[indexa--]; } while (indexb >= 0) { d[indexd--] = b[indexb--]; } for (int i = d.length - 1; i > 0; i--) { if (d[i] > 10) { int temp = d[i] / 10; d[i] = d[i] % 10; d[i - 1] += temp; } } for (int i = 0; i < d.length; i++) { if (i==0&&d[i] == 0) { continue; } System.out.print(d[i]); } }else{ System.out.println("Error"); } } }
UTF-8
Java
1,784
java
Main67.java
Java
[ { "context": "/**\n * Created by WZW on 2017/08/11.\n */\nimport java.util.*;\npublic cla", "end": 21, "score": 0.9992914199829102, "start": 18, "tag": "USERNAME", "value": "WZW" } ]
null
[]
/** * Created by WZW on 2017/08/11. */ import java.util.*; public class Main67{ public static void main(String args[]) { Scanner in = new Scanner(System.in); String str = in.nextLine(); String s[] = str.split(" "); char c[] = s[0].toCharArray(); char c2[] = s[1].toCharArray(); int a[] = new int[c.length]; int b[] = new int[c2.length]; boolean flag = true; for (int i = 0; i < c.length; i++) { if (c[i] > '9' || c[i] < '0') { flag = false; } a[i] = c[i] - '0'; } for (int i = 0; i < c2.length; i++) { if (c2[i] > '9' || c2[i] < '0') { flag = false; } b[i] = c2[i] - '0'; } if (flag) { int d[] = new int[Math.max(a.length, b.length) + 1]; int indexa = a.length - 1; int indexb = b.length - 1; int indexd = d.length - 1; while (indexa >= 0 && indexb >= 0) { d[indexd--] = a[indexa--] + b[indexb--]; } while (indexa >= 0) { d[indexd--] = a[indexa--]; } while (indexb >= 0) { d[indexd--] = b[indexb--]; } for (int i = d.length - 1; i > 0; i--) { if (d[i] > 10) { int temp = d[i] / 10; d[i] = d[i] % 10; d[i - 1] += temp; } } for (int i = 0; i < d.length; i++) { if (i==0&&d[i] == 0) { continue; } System.out.print(d[i]); } }else{ System.out.println("Error"); } } }
1,784
0.344731
0.318946
58
29.758621
14.764018
64
false
false
0
0
0
0
0
0
0.672414
false
false
5
57730a29565804fa67d2f3712fca4d165a07d9d8
1,365,799,606,464
ce0a770205f372cfe665af4b1ff8566f791c665f
/MyJavaProject/src/com/exceptionhandling/Emp.java
86e18fb297420e952f1bbb5cd55d9d84a3ba105d
[]
no_license
HarshithPrabhakar/JavaProject
https://github.com/HarshithPrabhakar/JavaProject
a531176888418ff3c1a59602b7bed0d47b7e2708
92dd6359e11c5f31dd665c04ff7f0e0710510a8e
refs/heads/master
2022-03-14T07:01:06.384000
2019-11-22T04:07:51
2019-11-22T04:07:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.exceptionhandling; class Emp { static void salaryDetail(double salary) { if(salary>1000) System.out.println("Thank you"); else throw new SalaryException(); } public static void main(String[] args) { System.out.println("from main"); salaryDetail(200); System.out.println("main ends"); } }
UTF-8
Java
345
java
Emp.java
Java
[]
null
[]
package com.exceptionhandling; class Emp { static void salaryDetail(double salary) { if(salary>1000) System.out.println("Thank you"); else throw new SalaryException(); } public static void main(String[] args) { System.out.println("from main"); salaryDetail(200); System.out.println("main ends"); } }
345
0.652174
0.631884
19
16.157894
15.523372
41
false
false
0
0
0
0
0
0
1.473684
false
false
5
f8ce1530b1a6e32c096f9a71462e06c966acd6ed
9,002,251,461,745
de3c2d89f623527b35cc5dd936773f32946025d2
/src/main/java/iko/dmaz/lloq/SyncField.java
0473d9453d854b9e591ca0aceb966ccb802516c7
[]
no_license
ren19890419/lvxing
https://github.com/ren19890419/lvxing
5f89f7b118df59fd1da06aaba43bd9b41b5da1e6
239875461cb39e58183ac54e93565ec5f7f28ddb
refs/heads/master
2023-04-15T08:56:25.048000
2020-06-05T10:46:05
2020-06-05T10:46:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package iko.dmaz.lloq; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface SyncField { /* renamed from: a */ boolean mo38800a() default false; /* renamed from: b */ int mo38801b() default -1; }
UTF-8
Java
405
java
SyncField.java
Java
[]
null
[]
package iko.dmaz.lloq; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface SyncField { /* renamed from: a */ boolean mo38800a() default false; /* renamed from: b */ int mo38801b() default -1; }
405
0.745679
0.718518
16
24.3125
15.002995
44
false
false
0
0
0
0
0
0
0.4375
false
false
5
4177361d647ac7d8aeb9835a8775712df5ed6272
18,081,812,322,059
ee8dc478ee1fee2f8464b1dd14b49e8a8ee6310f
/study/study-jdk/studyJavaAll/src/main/java/com/openjava/study/reflect/sample/TestFactoryCreate.java
7ce29828715783f8a963dc73f0cf5b0e45990731
[]
no_license
sangyuruo/myopenjava
https://github.com/sangyuruo/myopenjava
1ac6fe29c6e231a8ebf5e816a350e2a2ac4e9c15
c2460b6a2b8195838d7a928140584b9f368c369c
refs/heads/master
2020-05-21T03:08:04.760000
2019-07-04T04:35:19
2019-07-04T04:35:19
42,656,524
2
0
null
false
2021-01-14T19:56:18
2015-09-17T13:03:31
2019-07-04T04:42:46
2021-01-14T19:56:17
48,185
1
0
36
Java
false
false
package com.openjava.study.reflect.sample; public class TestFactoryCreate { public static void main(String[] args) { ConnCacheKey key = new ConnCacheKey(); key.setAppType("twitter"); ConnectorFactory connectorFactory = new DefaultConnectorFactory(); ConnectorFactory proxy = ConnectorFactoryFactory .create(connectorFactory); Connector conn = proxy.create(key); conn.doSomething(); } }
UTF-8
Java
406
java
TestFactoryCreate.java
Java
[]
null
[]
package com.openjava.study.reflect.sample; public class TestFactoryCreate { public static void main(String[] args) { ConnCacheKey key = new ConnCacheKey(); key.setAppType("twitter"); ConnectorFactory connectorFactory = new DefaultConnectorFactory(); ConnectorFactory proxy = ConnectorFactoryFactory .create(connectorFactory); Connector conn = proxy.create(key); conn.doSomething(); } }
406
0.763547
0.763547
14
28
20.206081
68
false
false
0
0
0
0
0
0
1.785714
false
false
5
802f64001a39ff3264c4502639cf6525b76649ef
27,350,351,747,962
86e642c11805be63e007ef3b0a0e716acdf498ec
/src/main/java/com/thoughtworks/tw101/exercises/exercise7/Guess.java
c9a8176fdf005a58f85c4d126450f2ba66491a57
[]
no_license
MsLarissaaa/tw101-exercises
https://github.com/MsLarissaaa/tw101-exercises
c47fd12f4470e6626dec877b39c1272aa64559bb
bb0956a50c8d984d63f1bf236c1c8e09937429ab
refs/heads/master
2021-01-12T05:39:36.124000
2017-01-04T05:48:15
2017-01-04T05:48:15
77,162,180
0
0
null
true
2017-01-04T05:48:17
2016-12-22T17:06:40
2016-12-22T17:10:20
2017-01-04T05:48:16
108
0
0
0
Java
null
null
package com.thoughtworks.tw101.exercises.exercise7; import java.util.Scanner; class Guess { int guess; Guess() { Scanner input = new Scanner(System.in); System.out.println("Guess a number between 1 and 100: "); guess = input.nextInt(); } }
UTF-8
Java
282
java
Guess.java
Java
[]
null
[]
package com.thoughtworks.tw101.exercises.exercise7; import java.util.Scanner; class Guess { int guess; Guess() { Scanner input = new Scanner(System.in); System.out.println("Guess a number between 1 and 100: "); guess = input.nextInt(); } }
282
0.631206
0.602837
14
19
21.027193
65
false
false
0
0
0
0
0
0
0.428571
false
false
5
136fbf336fb294979f5043cfe80c24122a6663d3
28,071,906,284,616
c921ec52fc90eb7e69ade043824748fbf9a5276a
/twoPlayerWordGame/src/main/java/edu/neu/madcourse/adibalwani/twoplayerwordgame/WaitForTurnDialogFragment.java
3ef154e1530ca995a639ca970da80bbf391b53e6
[]
no_license
adibalwani/Android
https://github.com/adibalwani/Android
2a65cb559dcc317bb986f7d977a68525d86f033d
18ffd3160c89848e5c0863d69308bb4814367455
refs/heads/master
2016-09-16T22:56:25.682000
2016-07-08T20:01:56
2016-07-08T20:01:56
62,914,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.neu.madcourse.adibalwani.twoplayerwordgame; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; public class WaitForTurnDialogFragment extends DialogFragment { private static final String BUNDLE_LAYOUT_ID = "1"; private Activity mActivity; private int mLayoutId; private DismissListener mDismissListener; private BroadcastReceiver mBroadcastReceiver; private GamePlayManager mGamePlayManager; private boolean registered; public interface DismissListener { /** * Method to call on Dismiss */ void onDismiss(boolean hasGameTurn); /** * Method to call on GameEnd * * @param score Game score */ void onGameEnd(int score); } /** * Create new instance of WaitDialogFragment, providing layoutId * as an argument * * @param layoutId The id of Layout to display in dialog * @return Instance of WaitDialogFragment */ static WaitForTurnDialogFragment newInstance(int layoutId, DismissListener listener) { WaitForTurnDialogFragment dialogFragment = new WaitForTurnDialogFragment(); dialogFragment.setDismissListener(listener); Bundle args = new Bundle(); args.putInt(BUNDLE_LAYOUT_ID, layoutId); dialogFragment.setArguments(args); return dialogFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = getActivity(); mLayoutId = getArguments().getInt(BUNDLE_LAYOUT_ID); mGamePlayManager = new GamePlayManager(mActivity); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); LayoutInflater inflater = mActivity.getLayoutInflater(); View view = inflater.inflate(mLayoutId, null); builder.setView(view) .setPositiveButton(R.string.twoplayerwordgame_wait_dialog_end, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDismissListener.onDismiss(false); registered = false; mActivity.unregisterReceiver(mBroadcastReceiver); mActivity.finish(); } } ); return builder.create(); } @Override public void onResume() { super.onResume(); if (mGamePlayManager.hasGameTurn()) { mDismissListener.onDismiss(mGamePlayManager.hasGameTurn()); WaitForTurnDialogFragment.this.getDialog().cancel(); } registerBroadcastReceiver(); } @Override public void onPause() { super.onPause(); if (registered) { mActivity.unregisterReceiver(mBroadcastReceiver); } } /** * Register a broadcast receiver to handle player found */ private void registerBroadcastReceiver() { registered = true; final IntentFilter filter = new IntentFilter("com.google.android.c2dm.intent.RECEIVE"); filter.addCategory(mActivity.getPackageName()); filter.setPriority(2); mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (!extras.isEmpty()) { String gameData = extras.getString("gamestate"); String wait = extras.getString("wait"); if (gameData != null && wait != null) { mActivity.unregisterReceiver(mBroadcastReceiver); registered = false; abortBroadcast(); if (gameData.equals("null")) { String score = extras.getString("score"); mGamePlayManager.removeGamePlay(); mDismissListener.onGameEnd(Integer.parseInt(score)); } else { mGamePlayManager.putGamePlay(gameData, Boolean.valueOf(wait)); mDismissListener.onDismiss(mGamePlayManager.hasGameTurn()); } WaitForTurnDialogFragment.this.getDialog().cancel(); } } } }; mActivity.registerReceiver( mBroadcastReceiver, filter, "com.google.android.c2dm.permission.SEND", null ); } private void setDismissListener(DismissListener dismissListener) { this.mDismissListener = dismissListener; } }
UTF-8
Java
5,295
java
WaitForTurnDialogFragment.java
Java
[]
null
[]
package edu.neu.madcourse.adibalwani.twoplayerwordgame; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; public class WaitForTurnDialogFragment extends DialogFragment { private static final String BUNDLE_LAYOUT_ID = "1"; private Activity mActivity; private int mLayoutId; private DismissListener mDismissListener; private BroadcastReceiver mBroadcastReceiver; private GamePlayManager mGamePlayManager; private boolean registered; public interface DismissListener { /** * Method to call on Dismiss */ void onDismiss(boolean hasGameTurn); /** * Method to call on GameEnd * * @param score Game score */ void onGameEnd(int score); } /** * Create new instance of WaitDialogFragment, providing layoutId * as an argument * * @param layoutId The id of Layout to display in dialog * @return Instance of WaitDialogFragment */ static WaitForTurnDialogFragment newInstance(int layoutId, DismissListener listener) { WaitForTurnDialogFragment dialogFragment = new WaitForTurnDialogFragment(); dialogFragment.setDismissListener(listener); Bundle args = new Bundle(); args.putInt(BUNDLE_LAYOUT_ID, layoutId); dialogFragment.setArguments(args); return dialogFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = getActivity(); mLayoutId = getArguments().getInt(BUNDLE_LAYOUT_ID); mGamePlayManager = new GamePlayManager(mActivity); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); LayoutInflater inflater = mActivity.getLayoutInflater(); View view = inflater.inflate(mLayoutId, null); builder.setView(view) .setPositiveButton(R.string.twoplayerwordgame_wait_dialog_end, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDismissListener.onDismiss(false); registered = false; mActivity.unregisterReceiver(mBroadcastReceiver); mActivity.finish(); } } ); return builder.create(); } @Override public void onResume() { super.onResume(); if (mGamePlayManager.hasGameTurn()) { mDismissListener.onDismiss(mGamePlayManager.hasGameTurn()); WaitForTurnDialogFragment.this.getDialog().cancel(); } registerBroadcastReceiver(); } @Override public void onPause() { super.onPause(); if (registered) { mActivity.unregisterReceiver(mBroadcastReceiver); } } /** * Register a broadcast receiver to handle player found */ private void registerBroadcastReceiver() { registered = true; final IntentFilter filter = new IntentFilter("com.google.android.c2dm.intent.RECEIVE"); filter.addCategory(mActivity.getPackageName()); filter.setPriority(2); mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (!extras.isEmpty()) { String gameData = extras.getString("gamestate"); String wait = extras.getString("wait"); if (gameData != null && wait != null) { mActivity.unregisterReceiver(mBroadcastReceiver); registered = false; abortBroadcast(); if (gameData.equals("null")) { String score = extras.getString("score"); mGamePlayManager.removeGamePlay(); mDismissListener.onGameEnd(Integer.parseInt(score)); } else { mGamePlayManager.putGamePlay(gameData, Boolean.valueOf(wait)); mDismissListener.onDismiss(mGamePlayManager.hasGameTurn()); } WaitForTurnDialogFragment.this.getDialog().cancel(); } } } }; mActivity.registerReceiver( mBroadcastReceiver, filter, "com.google.android.c2dm.permission.SEND", null ); } private void setDismissListener(DismissListener dismissListener) { this.mDismissListener = dismissListener; } }
5,295
0.596978
0.596223
147
35.020409
24.784094
95
false
false
0
0
0
0
0
0
0.52381
false
false
5
0799fb2a7baf8811c0c820405ec93662042442e5
32,633,161,562,031
09c826fb768612aba65e3a8008e6a22a87e08a1f
/RoomDatabaseDemo2/app/src/main/java/com/example/roomdatabasedemo2/User.java
849169a381394b9f8593bebfda6520b1b06e2067
[]
no_license
thiencd/test
https://github.com/thiencd/test
bb4b705d5c65cff85df6ce386cfe146f9acc0e7c
c34d38b7a08af160555109ecf8ee5aab65724f2d
refs/heads/master
2020-05-25T02:30:58.407000
2019-05-20T06:07:07
2019-05-20T06:07:07
187,580,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.roomdatabasedemo2; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; @Entity(tableName = "user") public class User { @PrimaryKey private int id; @ColumnInfo(name = "user_name") private String mane; @ColumnInfo(name="user_email") private String email; public User(int id, String mane, String email) { this.id = id; this.mane = mane; this.email = email; } public User(){}; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMane() { return mane; } public void setMane(String mane) { this.mane = mane; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
UTF-8
Java
930
java
User.java
Java
[]
null
[]
package com.example.roomdatabasedemo2; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; @Entity(tableName = "user") public class User { @PrimaryKey private int id; @ColumnInfo(name = "user_name") private String mane; @ColumnInfo(name="user_email") private String email; public User(int id, String mane, String email) { this.id = id; this.mane = mane; this.email = email; } public User(){}; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMane() { return mane; } public void setMane(String mane) { this.mane = mane; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
930
0.606452
0.605376
50
17.6
15.520309
52
false
false
0
0
0
0
0
0
0.38
false
false
5
bcce72973fdb529dbf09662b0f33830cf3797d67
6,511,170,480,205
37ff20ba64353717e362767e6b718f2d17e20e72
/app/src/main/java/com/example/neven/firebaseintegrationapp/dagger/modules/ResetPasswordModule.java
ccfcfae6dd24ce6dc391b7a3530e818309e23906
[]
no_license
Nenco1993/FirebaseIntegrationApp
https://github.com/Nenco1993/FirebaseIntegrationApp
6e615ce1631ef0190c3359984fde577df01366bf
da7bab5eaafcabda21882180ab99c6705d1a4175
refs/heads/master
2021-01-22T06:02:05.601000
2017-05-29T20:39:24
2017-05-29T20:39:24
92,516,006
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.neven.firebaseintegrationapp.dagger.modules; import android.app.Activity; import com.example.neven.firebaseintegrationapp.dagger.scopes.ActivityScope; import com.example.neven.firebaseintegrationapp.models.User; import com.example.neven.firebaseintegrationapp.presenters.ResetPasswordPresenter; import com.example.neven.firebaseintegrationapp.presenters.ResetPasswordPresenterImpl; import com.example.neven.firebaseintegrationapp.views.ResetPasswordView; import dagger.Module; import dagger.Provides; /** * Created by Neven on 26.5.2017.. */ @Module public class ResetPasswordModule { private Activity activity; private ResetPasswordView view; public ResetPasswordModule(Activity activity, ResetPasswordView view) { this.activity = activity; this.view = view; } @Provides @ActivityScope ResetPasswordPresenter providePresenter(ResetPasswordPresenterImpl presenter){ return presenter; } @Provides @ActivityScope ResetPasswordView provideView(){ return view; } @Provides @ActivityScope User provideUser(){ return new User(); } }
UTF-8
Java
1,167
java
ResetPasswordModule.java
Java
[ { "context": "Module;\nimport dagger.Provides;\n\n/**\n * Created by Neven on 26.5.2017..\n */\n@Module\npublic class ResetPass", "end": 546, "score": 0.9830257892608643, "start": 541, "tag": "USERNAME", "value": "Neven" } ]
null
[]
package com.example.neven.firebaseintegrationapp.dagger.modules; import android.app.Activity; import com.example.neven.firebaseintegrationapp.dagger.scopes.ActivityScope; import com.example.neven.firebaseintegrationapp.models.User; import com.example.neven.firebaseintegrationapp.presenters.ResetPasswordPresenter; import com.example.neven.firebaseintegrationapp.presenters.ResetPasswordPresenterImpl; import com.example.neven.firebaseintegrationapp.views.ResetPasswordView; import dagger.Module; import dagger.Provides; /** * Created by Neven on 26.5.2017.. */ @Module public class ResetPasswordModule { private Activity activity; private ResetPasswordView view; public ResetPasswordModule(Activity activity, ResetPasswordView view) { this.activity = activity; this.view = view; } @Provides @ActivityScope ResetPasswordPresenter providePresenter(ResetPasswordPresenterImpl presenter){ return presenter; } @Provides @ActivityScope ResetPasswordView provideView(){ return view; } @Provides @ActivityScope User provideUser(){ return new User(); } }
1,167
0.75407
0.748072
50
22.34
25.787291
86
false
false
0
0
0
0
0
0
0.34
false
false
5
3ad0b702be7a82a4d2b18601a7f1f9e0c8a505c7
7,318,624,273,480
aec861c3e8186635edb8ba92877dafa3d7e0bc94
/com/midgardabc/day14/shop/view/Splash.java
0ca55695085236b51c51874969a238340970c233
[]
no_license
AA0700KA/AndrewRepository
https://github.com/AA0700KA/AndrewRepository
e670f451d633a2bec4efac114ac0b79d55704611
fd8c3d2484b03146bf7bfbaec04da575fb2698f3
refs/heads/master
2021-01-13T00:41:22.577000
2015-12-14T09:56:28
2015-12-14T09:56:28
47,965,703
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.midgardabc.day14.shop.view; import java.awt.*; /** * Created by user on 03.09.2015. */ public class Splash { private int percent = 0; public void createSplash() throws InterruptedException { SplashScreen splash = SplashScreen.getSplashScreen(); Graphics2D g = splash.createGraphics(); g.setColor(Color.blue); int loading = 0; while (loading < 600) { g.fillRect(0, 400, loading, 2); if (loading % 100 == 0) { draw(g); } Thread.sleep(500); loading += 20; splash.update(); } Thread.sleep(2000); splash.close(); } private void draw(Graphics g) { if (percent <= 100) { g.drawString("Loading..." + percent + " %", 15, 370); percent += 20; } } }
UTF-8
Java
872
java
Splash.java
Java
[ { "context": ".shop.view;\n\nimport java.awt.*;\n\n/**\n * Created by user on 03.09.2015.\n */\npublic class Splash {\n\n pri", "end": 83, "score": 0.6866554617881775, "start": 79, "tag": "USERNAME", "value": "user" } ]
null
[]
package com.midgardabc.day14.shop.view; import java.awt.*; /** * Created by user on 03.09.2015. */ public class Splash { private int percent = 0; public void createSplash() throws InterruptedException { SplashScreen splash = SplashScreen.getSplashScreen(); Graphics2D g = splash.createGraphics(); g.setColor(Color.blue); int loading = 0; while (loading < 600) { g.fillRect(0, 400, loading, 2); if (loading % 100 == 0) { draw(g); } Thread.sleep(500); loading += 20; splash.update(); } Thread.sleep(2000); splash.close(); } private void draw(Graphics g) { if (percent <= 100) { g.drawString("Loading..." + percent + " %", 15, 370); percent += 20; } } }
872
0.512615
0.462156
38
21.947369
18.253979
65
false
false
0
0
0
0
0
0
0.552632
false
false
5
6ceb56c16c3b722abdf30d7e215d544e52827e19
13,580,686,643,447
1272e0af6c6ab10523dfe21f21bd5df85f964116
/com.zutubi.pulse.master/src/java/com/zutubi/pulse/master/events/HostUpgradeCompleteEvent.java
330fddd733bcdce0a4578e1d911975491b7824f3
[ "Apache-2.0" ]
permissive
ppsravan/pulse
https://github.com/ppsravan/pulse
083e57932423ea6360e3642f3934e17ea450be75
6a41105ae8438018b055611268c20dac5585f890
refs/heads/master
2022-03-10T23:17:58.540000
2017-04-14T12:00:02
2017-04-14T12:00:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2017 Zutubi Pty Ltd * * 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.zutubi.pulse.master.events; import com.zutubi.pulse.master.agent.Host; /** * Event raised with a host upgrade completes, indicating if it succeeded. */ public class HostUpgradeCompleteEvent extends HostEvent { private boolean successful; public HostUpgradeCompleteEvent(Object source, Host host, boolean successful) { super(source, host); this.successful = successful; } public boolean isSuccessful() { return successful; } @Override public String toString() { return "Host Upgrade Complete Event: " + getHost().getLocation() + ": " + successful; } }
UTF-8
Java
1,268
java
HostUpgradeCompleteEvent.java
Java
[]
null
[]
/* Copyright 2017 Zutubi Pty Ltd * * 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.zutubi.pulse.master.events; import com.zutubi.pulse.master.agent.Host; /** * Event raised with a host upgrade completes, indicating if it succeeded. */ public class HostUpgradeCompleteEvent extends HostEvent { private boolean successful; public HostUpgradeCompleteEvent(Object source, Host host, boolean successful) { super(source, host); this.successful = successful; } public boolean isSuccessful() { return successful; } @Override public String toString() { return "Host Upgrade Complete Event: " + getHost().getLocation() + ": " + successful; } }
1,268
0.690852
0.684543
43
27.83721
28.398272
93
false
false
0
0
0
0
0
0
0.372093
false
false
5
cf1e65a4e1726ec5a3b63529019e57c5caae4117
16,286,516,021,458
33dce3f6a08aaad723cf5665f11e5cd7307a64d9
/src/main/java/br/datainfo/utilitarios/MensagensSistema.java
bebe1915a81eb3a8247291d9767c1f7a21dc0865
[]
no_license
RaulBBrito/dataInfoDesafio
https://github.com/RaulBBrito/dataInfoDesafio
fb3ba2fbfb87379432f1f12dcfa2dfd1d9685f8d
66b735df1cb9127b236cd6b0b7f6b343741335ef
refs/heads/master
2020-05-18T15:03:23.546000
2019-05-01T22:04:49
2019-05-01T22:04:49
184,486,734
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.datainfo.utilitarios; public class MensagensSistema { private String mensagem; public MensagensSistema(){} public MensagensSistema(String mensagem){ this.mensagem = mensagem; } public String getMensagem() { return mensagem; } public void setMensagem(String string) { this.mensagem = string; } }
UTF-8
Java
331
java
MensagensSistema.java
Java
[]
null
[]
package br.datainfo.utilitarios; public class MensagensSistema { private String mensagem; public MensagensSistema(){} public MensagensSistema(String mensagem){ this.mensagem = mensagem; } public String getMensagem() { return mensagem; } public void setMensagem(String string) { this.mensagem = string; } }
331
0.731118
0.731118
21
14.714286
15.25386
42
false
false
0
0
0
0
0
0
1.047619
false
false
5
fc480cb3536938dc9b3c8180452a4d85fec5f553
17,849,884,105,856
fc6c869ee0228497e41bf357e2803713cdaed63e
/weixin6519android1140/src/sourcecode/com/tencent/mm/plugin/appbrand/jsapi/i/d.java
8ec6985d409b64c650204247027358c00bd7059a
[]
no_license
hyb1234hi/reverse-wechat
https://github.com/hyb1234hi/reverse-wechat
cbd26658a667b0c498d2a26a403f93dbeb270b72
75d3fd35a2c8a0469dbb057cd16bca3b26c7e736
refs/heads/master
2020-09-26T10:12:47.484000
2017-11-16T06:54:20
2017-11-16T06:54:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.mm.plugin.appbrand.jsapi.i; import com.tencent.gmtrace.GMTrace; import com.tencent.mm.plugin.appbrand.c; import com.tencent.mm.plugin.appbrand.c.b; import com.tencent.mm.plugin.appbrand.j; import com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.plugin.appbrand.ui.banner.AppBrandStickyBannerLogic.a; import org.json.JSONObject; public final class d extends a { private static final int CTRL_INDEX = 241; private static final String NAME = "setTopBarText"; public d() { GMTrace.i(17379853598720L, 129490); GMTrace.o(17379853598720L, 129490); } public final void a(final j paramj, JSONObject paramJSONObject, int paramInt) { GMTrace.i(17379987816448L, 129491); paramJSONObject = paramJSONObject.optString("text"); AppBrandStickyBannerLogic.a.bo(paramj.hyD, paramJSONObject); paramj.v(paramInt, d("ok", null)); c.a(paramj.hyD, new c.b() { public final void onDestroy() { GMTrace.i(17671374503936L, 131662); AppBrandStickyBannerLogic.a.bo(paramj.hyD, ""); GMTrace.o(17671374503936L, 131662); } }); GMTrace.o(17379987816448L, 129491); } } /* Location: D:\tools\apktool\weixin6519android1140\jar\classes2-dex2jar.jar!\com\tencent\mm\plugin\appbrand\jsapi\i\d.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
1,385
java
d.java
Java
[]
null
[]
package com.tencent.mm.plugin.appbrand.jsapi.i; import com.tencent.gmtrace.GMTrace; import com.tencent.mm.plugin.appbrand.c; import com.tencent.mm.plugin.appbrand.c.b; import com.tencent.mm.plugin.appbrand.j; import com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.plugin.appbrand.ui.banner.AppBrandStickyBannerLogic.a; import org.json.JSONObject; public final class d extends a { private static final int CTRL_INDEX = 241; private static final String NAME = "setTopBarText"; public d() { GMTrace.i(17379853598720L, 129490); GMTrace.o(17379853598720L, 129490); } public final void a(final j paramj, JSONObject paramJSONObject, int paramInt) { GMTrace.i(17379987816448L, 129491); paramJSONObject = paramJSONObject.optString("text"); AppBrandStickyBannerLogic.a.bo(paramj.hyD, paramJSONObject); paramj.v(paramInt, d("ok", null)); c.a(paramj.hyD, new c.b() { public final void onDestroy() { GMTrace.i(17671374503936L, 131662); AppBrandStickyBannerLogic.a.bo(paramj.hyD, ""); GMTrace.o(17671374503936L, 131662); } }); GMTrace.o(17379987816448L, 129491); } } /* Location: D:\tools\apktool\weixin6519android1140\jar\classes2-dex2jar.jar!\com\tencent\mm\plugin\appbrand\jsapi\i\d.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
1,385
0.703249
0.602166
46
29.130434
27.305525
137
false
false
0
0
0
0
0
0
0.73913
false
false
5
4cd0b67ee5845050a3cd744d23db915dbaa23134
24,481,313,606,493
becd67661be19f100bf45aab8095ab48036a05ad
/app/src/main/java/pl/lukaszdutka/apiproject/activities/MainActivity.java
33a7b4ed05f017ac477fe335bf123c91557bbcc6
[]
no_license
lukaszdutka/ApiProject
https://github.com/lukaszdutka/ApiProject
552a7d75b7c521ecf0e27a494746643fd5357788
0a84d75550684f07c493c0ba127e112a74a2fb39
refs/heads/master
2020-03-16T23:03:41.232000
2018-05-11T16:28:35
2018-05-11T16:28:35
133,063,173
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.lukaszdutka.apiproject.activities; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import pl.lukaszdutka.apiproject.R; import pl.lukaszdutka.apiproject.adapter.ApiItemsAdapter; import pl.lukaszdutka.apiproject.apiaccess.ApiEmployee; import pl.lukaszdutka.apiproject.apiaccess.EmployeeApiService; import pl.lukaszdutka.apiproject.apiaccess.EmployeesResponseBody; import java.util.ArrayList; import java.util.List; import butterknife.BindString; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { //@BindString(R.string.missingSearchData) String missingSearchData; @BindString(R.string.apiFailure) String apiFailure; private List<ApiEmployee> employeeList = new ArrayList<>(); private Retrofit retrofit; private EmployeeApiService service; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private ContentResolver contentResolver; private Window window; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = findViewById(R.id.m_recyclerview); ButterKnife.bind(this); initializeActionBar(); initializeRetrofit(); //readEmployeeList(); } private void initializeActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); CollapsingToolbarLayout collapsingToolbar = findViewById(R.id.collapse_toolbar); collapsingToolbar.setTitleEnabled(false); } private void initializeRetrofit() { retrofit = new Retrofit.Builder() .baseUrl("http://dummy.restapiexample.com/api/v1/") .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(EmployeeApiService.class); } private void initializeViewAdapter() { mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new ApiItemsAdapter(employeeList, getApplicationContext()); mRecyclerView.setAdapter(mAdapter); } private void hideKeyboard() { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } private void readEmployeeList() { service.getAllEmployeesList().enqueue(new Callback<EmployeesResponseBody>() { @Override public void onResponse(Call<EmployeesResponseBody> call, Response<EmployeesResponseBody> response) { for (ApiEmployee employee : response.body().getEmployees()) { employeeList.add(employee); } initializeViewAdapter(); } @Override public void onFailure(Call<EmployeesResponseBody> call, Throwable t) { Toast.makeText(getApplicationContext(), apiFailure, Toast.LENGTH_SHORT).show(); } }); } }
UTF-8
Java
4,056
java
MainActivity.java
Java
[]
null
[]
package pl.lukaszdutka.apiproject.activities; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import pl.lukaszdutka.apiproject.R; import pl.lukaszdutka.apiproject.adapter.ApiItemsAdapter; import pl.lukaszdutka.apiproject.apiaccess.ApiEmployee; import pl.lukaszdutka.apiproject.apiaccess.EmployeeApiService; import pl.lukaszdutka.apiproject.apiaccess.EmployeesResponseBody; import java.util.ArrayList; import java.util.List; import butterknife.BindString; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { //@BindString(R.string.missingSearchData) String missingSearchData; @BindString(R.string.apiFailure) String apiFailure; private List<ApiEmployee> employeeList = new ArrayList<>(); private Retrofit retrofit; private EmployeeApiService service; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private ContentResolver contentResolver; private Window window; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = findViewById(R.id.m_recyclerview); ButterKnife.bind(this); initializeActionBar(); initializeRetrofit(); //readEmployeeList(); } private void initializeActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); CollapsingToolbarLayout collapsingToolbar = findViewById(R.id.collapse_toolbar); collapsingToolbar.setTitleEnabled(false); } private void initializeRetrofit() { retrofit = new Retrofit.Builder() .baseUrl("http://dummy.restapiexample.com/api/v1/") .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(EmployeeApiService.class); } private void initializeViewAdapter() { mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new ApiItemsAdapter(employeeList, getApplicationContext()); mRecyclerView.setAdapter(mAdapter); } private void hideKeyboard() { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } private void readEmployeeList() { service.getAllEmployeesList().enqueue(new Callback<EmployeesResponseBody>() { @Override public void onResponse(Call<EmployeesResponseBody> call, Response<EmployeesResponseBody> response) { for (ApiEmployee employee : response.body().getEmployees()) { employeeList.add(employee); } initializeViewAdapter(); } @Override public void onFailure(Call<EmployeesResponseBody> call, Throwable t) { Toast.makeText(getApplicationContext(), apiFailure, Toast.LENGTH_SHORT).show(); } }); } }
4,056
0.725838
0.723373
120
32.799999
25.304018
112
false
false
0
0
0
0
0
0
0.591667
false
false
5
c907699f219d4f3761a8fa643655a346360ac573
6,794,638,290,143
3ce0f9e74cf9eb5d7b56f5fd6995550bb741256f
/app/src/main/java/com/babylon/vasco/tecnicalvasco/BasicDetailsActivity.java
57302b340a470eb2d147f8c33ade7e35e70eafc5
[]
no_license
vascofermandes/TecnicalVasco
https://github.com/vascofermandes/TecnicalVasco
478c1fec6af702cf1efedff00dd0bcf13a2b951c
cf4303bb5e9ca891d0db6bf7280ab0e8033c7d8e
refs/heads/master
2016-06-08T09:27:52.457000
2016-04-13T11:48:22
2016-04-13T11:48:22
56,012,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.babylon.vasco.tecnicalvasco; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import java.util.ArrayList; import java.util.List; public class BasicDetailsActivity extends AppCompatActivity { BabylonTestDBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_basic_details); final TextView title = (TextView) findViewById(R.id.bTitle); final TextView body = (TextView) findViewById(R.id.bBody); final TextView name = (TextView) findViewById(R.id.bName); final TextView comments = (TextView) findViewById(R.id.bComments); dbHelper = BabylonTestDBHelper.getInstance(this); Intent intent = getIntent(); int postId = intent.getIntExtra("postid", 0); BasicInfo info = dbHelper.getBasicPost(postId); title.setText("POST TITLE: "+info.postTitle); body.setText("POST BODY: "+info.postBody); name.setText("USER NAME: "+info.name); comments.setText("COMMENTS COUNT: "+String.valueOf(info.commentsCount)); } }
UTF-8
Java
1,634
java
BasicDetailsActivity.java
Java
[]
null
[]
package com.babylon.vasco.tecnicalvasco; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import java.util.ArrayList; import java.util.List; public class BasicDetailsActivity extends AppCompatActivity { BabylonTestDBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_basic_details); final TextView title = (TextView) findViewById(R.id.bTitle); final TextView body = (TextView) findViewById(R.id.bBody); final TextView name = (TextView) findViewById(R.id.bName); final TextView comments = (TextView) findViewById(R.id.bComments); dbHelper = BabylonTestDBHelper.getInstance(this); Intent intent = getIntent(); int postId = intent.getIntExtra("postid", 0); BasicInfo info = dbHelper.getBasicPost(postId); title.setText("POST TITLE: "+info.postTitle); body.setText("POST BODY: "+info.postBody); name.setText("USER NAME: "+info.name); comments.setText("COMMENTS COUNT: "+String.valueOf(info.commentsCount)); } }
1,634
0.732558
0.730722
62
25.354839
24.05444
80
false
false
0
0
0
0
0
0
0.564516
false
false
5
228ced089cc272b52b4b5e1ecfc7e4546879acc0
9,672,266,384,053
883d345065cd10ed845390093400d199a8c05b2d
/src/main/java/com/hospitalproject/config/SpringConfig.java
199d6d13cc2e8746d0c310f294ffae659449c977
[]
no_license
Chismur/HospitalProject
https://github.com/Chismur/HospitalProject
b9905a5cf0d7abece967eb2a198c7a4b07c0fc34
33a4b070fc60ad7538126181da8ad867320342dc
refs/heads/master
2021-08-30T10:54:28.496000
2017-12-17T15:14:15
2017-12-17T15:14:15
110,894,056
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hospitalproject.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; /** * Created by kingm on 14.11.2017. */ @Configuration @ComponentScan("com.hospitalproject") @ImportResource("classpath:spring.xml") public class SpringConfig { }
UTF-8
Java
389
java
SpringConfig.java
Java
[ { "context": "text.annotation.ImportResource;\n\n/**\n * Created by kingm on 14.11.2017.\n */\n@Configuration\n@ComponentScan(", "end": 245, "score": 0.9996052980422974, "start": 240, "tag": "USERNAME", "value": "kingm" } ]
null
[]
package com.hospitalproject.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; /** * Created by kingm on 14.11.2017. */ @Configuration @ComponentScan("com.hospitalproject") @ImportResource("classpath:spring.xml") public class SpringConfig { }
389
0.81491
0.794344
15
24.933332
22.819485
61
false
false
0
0
0
0
0
0
0.266667
false
false
5
d1a9c99e9b283e50512e6404ffce9ab185ba712c
22,273,700,432,366
4c65f1d94077bfa97fa3dafb82a2c605d43acc6a
/digitalfarmer/src/main/java/com/sergiogutierrez/digitalfarmer/dao/FieldDAO.java
4bd6a83ba646f7eb4585e031a7f6b3a7aa6b69fd
[]
no_license
sergio8221/digitalfarmer-back
https://github.com/sergio8221/digitalfarmer-back
0f07fa95cf0d9e086bedfd3cc12993bc784e0c5d
60b8809cbc5c49909ea2e0e3d7235b5a9c5e6e93
refs/heads/develop
2021-07-09T08:58:55.990000
2020-11-19T21:49:10
2020-11-19T21:49:10
213,720,645
0
0
null
false
2019-12-13T22:15:30
2019-10-08T18:28:24
2019-10-08T18:28:27
2019-12-13T22:15:29
67
0
0
0
null
false
false
package com.sergiogutierrez.digitalfarmer.dao; import java.util.List; import com.sergiogutierrez.digitalfarmer.entity.Field; public interface FieldDAO { public List<Field> getAll(); public Field getById(int id); public void save(Field field); public void delete(int id); }
UTF-8
Java
285
java
FieldDAO.java
Java
[]
null
[]
package com.sergiogutierrez.digitalfarmer.dao; import java.util.List; import com.sergiogutierrez.digitalfarmer.entity.Field; public interface FieldDAO { public List<Field> getAll(); public Field getById(int id); public void save(Field field); public void delete(int id); }
285
0.768421
0.768421
17
15.764706
17.998463
54
false
false
0
0
0
0
0
0
0.647059
false
false
5
713cae3d3114c2019045e191d63c71c88956fe5d
28,638,841,979,552
31502f04c93ab58513e7e20a2b6416bd336a6e03
/DotaGame/src/Heroes/Agility.java
a3db9760cd9ef91776456913e633a9af5cbb3ff6
[]
no_license
maxxxdj/DotaGame
https://github.com/maxxxdj/DotaGame
6670bb8fa9a1c61a481dddc730a1121c250bdee3
790740bf97ec7973a1ee50500b6ffed5c9b4388e
refs/heads/main
2023-02-25T04:59:53.897000
2021-02-07T14:55:33
2021-02-07T14:55:33
336,101,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Heroes; public class Agility extends Hero{ public Agility(String name) { super(name); super.setStrength(25); super.setAgility(100); super.setIntelligence(15); super.setHitPoints(650); super.setDamage(120); } }
UTF-8
Java
275
java
Agility.java
Java
[]
null
[]
package Heroes; public class Agility extends Hero{ public Agility(String name) { super(name); super.setStrength(25); super.setAgility(100); super.setIntelligence(15); super.setHitPoints(650); super.setDamage(120); } }
275
0.614545
0.567273
12
21.916666
12.757078
34
false
false
0
0
0
0
0
0
0.583333
false
false
5
d458ee42675b288554cced14a57117505bcbf6da
8,667,244,034,979
0801d546cf759ab607096dfcfb277b9fe12fb4e5
/net/minecraft/server/v1_12_R1/BlockTripwireHook.java
b8452a3bd0ce17e0d227a2f2d8a5614b25d679d1
[]
no_license
Balafre78/spigot-1.12
https://github.com/Balafre78/spigot-1.12
379e68c4982a399692cc5a15b6a4b87be1f00fa4
439b0d0119620470fabf6cba656401f5a272ba45
refs/heads/master
2022-04-24T05:26:00.677000
2020-04-21T11:36:20
2020-04-21T11:36:20
257,556,135
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* */ package net.minecraft.server.v1_12_R1; /* */ /* */ import com.google.common.base.MoreObjects; /* */ import java.util.Iterator; /* */ import java.util.Random; /* */ import javax.annotation.Nullable; /* */ import org.bukkit.block.Block; /* */ import org.bukkit.event.Event; /* */ import org.bukkit.event.block.BlockRedstoneEvent; /* */ /* */ public class BlockTripwireHook extends Block { /* 12 */ public static final BlockStateDirection FACING = BlockFacingHorizontal.FACING; /* 13 */ public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); /* 14 */ public static final BlockStateBoolean ATTACHED = BlockStateBoolean.of("attached"); /* 15 */ protected static final AxisAlignedBB d = new AxisAlignedBB(0.3125D, 0.0D, 0.625D, 0.6875D, 0.625D, 1.0D); /* 16 */ protected static final AxisAlignedBB e = new AxisAlignedBB(0.3125D, 0.0D, 0.0D, 0.6875D, 0.625D, 0.375D); /* 17 */ protected static final AxisAlignedBB f = new AxisAlignedBB(0.625D, 0.0D, 0.3125D, 1.0D, 0.625D, 0.6875D); /* 18 */ protected static final AxisAlignedBB g = new AxisAlignedBB(0.0D, 0.0D, 0.3125D, 0.375D, 0.625D, 0.6875D); /* */ /* */ public BlockTripwireHook() { /* 21 */ super(Material.ORIENTABLE); /* 22 */ w(this.blockStateList.getBlockData().<Comparable, EnumDirection>set(FACING, EnumDirection.NORTH).<Comparable, Boolean>set(POWERED, Boolean.valueOf(false)).set(ATTACHED, Boolean.valueOf(false))); /* 23 */ a(CreativeModeTab.d); /* 24 */ a(true); /* */ } /* */ /* */ public AxisAlignedBB b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { /* 28 */ switch ((EnumDirection)iblockdata.get(FACING)) { /* */ /* */ default: /* 31 */ return g; /* */ /* */ case WEST: /* 34 */ return f; /* */ /* */ case SOUTH: /* 37 */ return e; /* */ case NORTH: /* */ break; /* 40 */ } return d; /* */ } /* */ /* */ /* */ @Nullable /* */ public AxisAlignedBB a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { /* 46 */ return k; /* */ } /* */ /* */ public boolean b(IBlockData iblockdata) { /* 50 */ return false; /* */ } /* */ /* */ public boolean c(IBlockData iblockdata) { /* 54 */ return false; /* */ } /* */ /* */ public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { /* 58 */ EnumDirection enumdirection1 = enumdirection.opposite(); /* 59 */ BlockPosition blockposition1 = blockposition.shift(enumdirection1); /* 60 */ IBlockData iblockdata = world.getType(blockposition1); /* 61 */ boolean flag = c(iblockdata.getBlock()); /* */ /* 63 */ return (!flag && enumdirection.k().c() && iblockdata.d(world, blockposition1, enumdirection) == EnumBlockFaceShape.SOLID && !iblockdata.m()); /* */ } /* */ public boolean canPlace(World world, BlockPosition blockposition) { /* */ EnumDirection enumdirection; /* 67 */ Iterator<EnumDirection> iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); /* */ /* */ /* */ /* */ do { /* 72 */ if (!iterator.hasNext()) { /* 73 */ return false; /* */ } /* */ /* 76 */ enumdirection = iterator.next(); /* 77 */ } while (!canPlace(world, blockposition, enumdirection)); /* */ /* 79 */ return true; /* */ } /* */ /* */ public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { /* 83 */ IBlockData iblockdata = getBlockData().<Comparable, Boolean>set(POWERED, Boolean.valueOf(false)).set(ATTACHED, Boolean.valueOf(false)); /* */ /* 85 */ if (enumdirection.k().c()) { /* 86 */ iblockdata = iblockdata.set(FACING, enumdirection); /* */ } /* */ /* 89 */ return iblockdata; /* */ } /* */ /* */ public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { /* 93 */ a(world, blockposition, iblockdata, false, false, -1, (IBlockData)null); /* */ } /* */ /* */ public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1) { /* 97 */ if (block != this && /* 98 */ e(world, blockposition, iblockdata)) { /* 99 */ EnumDirection enumdirection = iblockdata.<EnumDirection>get(FACING); /* */ /* 101 */ if (!canPlace(world, blockposition, enumdirection)) { /* 102 */ b(world, blockposition, iblockdata, 0); /* 103 */ world.setAir(blockposition); /* */ } /* */ } /* */ } /* */ /* */ /* */ public void a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean flag1, int i, @Nullable IBlockData iblockdata1) { /* */ int n; /* 111 */ EnumDirection enumdirection = iblockdata.<EnumDirection>get(FACING); /* 112 */ int flag2 = ((Boolean)iblockdata.<Boolean>get(ATTACHED)).booleanValue(); /* 113 */ boolean flag3 = ((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue(); /* 114 */ boolean flag4 = !flag; /* 115 */ boolean flag5 = false; /* 116 */ int j = 0; /* 117 */ IBlockData[] aiblockdata = new IBlockData[42]; /* */ /* */ /* */ /* 121 */ for (int k = 1; k < 42; k++) { /* 122 */ BlockPosition blockposition1 = blockposition.shift(enumdirection, k); /* 123 */ IBlockData iblockdata2 = world.getType(blockposition1); /* */ /* 125 */ if (iblockdata2.getBlock() == Blocks.TRIPWIRE_HOOK) { /* 126 */ if (iblockdata2.get(FACING) == enumdirection.opposite()) { /* 127 */ j = k; /* */ } /* */ /* */ break; /* */ } /* 132 */ if (iblockdata2.getBlock() != Blocks.TRIPWIRE && k != i) { /* 133 */ aiblockdata[k] = null; /* 134 */ flag4 = false; /* */ } else { /* 136 */ if (k == i) { /* 137 */ iblockdata2 = (IBlockData)MoreObjects.firstNonNull(iblockdata1, iblockdata2); /* */ } /* */ /* 140 */ boolean flag6 = !((Boolean)iblockdata2.<Boolean>get(BlockTripwire.DISARMED)).booleanValue(); /* 141 */ boolean flag7 = ((Boolean)iblockdata2.<Boolean>get(BlockTripwire.POWERED)).booleanValue(); /* */ /* 143 */ n = flag5 | ((flag6 && flag7) ? 1 : 0); /* 144 */ aiblockdata[k] = iblockdata2; /* 145 */ if (k == i) { /* 146 */ world.a(blockposition, this, a(world)); /* 147 */ flag4 &= flag6; /* */ } /* */ } /* */ } /* */ /* 152 */ int m = flag4 & ((j > 1) ? 1 : 0); /* 153 */ n &= m; /* 154 */ IBlockData iblockdata3 = getBlockData().<Comparable, Boolean>set(ATTACHED, Boolean.valueOf(m)).set(POWERED, Boolean.valueOf(n)); /* */ /* 156 */ if (j > 0) { /* 157 */ BlockPosition blockposition1 = blockposition.shift(enumdirection, j); /* 158 */ EnumDirection enumdirection1 = enumdirection.opposite(); /* */ /* 160 */ world.setTypeAndData(blockposition1, iblockdata3.set(FACING, enumdirection1), 3); /* 161 */ a(world, blockposition1, enumdirection1); /* 162 */ a(world, blockposition1, m, n, flag2, flag3); /* */ } /* */ /* */ /* 166 */ Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); /* */ /* 168 */ BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, 15, 0); /* 169 */ world.getServer().getPluginManager().callEvent((Event)eventRedstone); /* */ /* 171 */ if (eventRedstone.getNewCurrent() > 0) { /* */ return; /* */ } /* */ /* */ /* 176 */ a(world, blockposition, m, n, flag2, flag3); /* 177 */ if (!flag) { /* 178 */ world.setTypeAndData(blockposition, iblockdata3.set(FACING, enumdirection), 3); /* 179 */ if (flag1) { /* 180 */ a(world, blockposition, enumdirection); /* */ } /* */ } /* */ /* 184 */ if (flag2 != m) { /* 185 */ for (int l = 1; l < j; l++) { /* 186 */ BlockPosition blockposition2 = blockposition.shift(enumdirection, l); /* 187 */ IBlockData iblockdata4 = aiblockdata[l]; /* */ /* 189 */ if (iblockdata4 != null && world.getType(blockposition2).getMaterial() != Material.AIR) { /* 190 */ world.setTypeAndData(blockposition2, iblockdata4.set(ATTACHED, Boolean.valueOf(m)), 3); /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* */ public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) {} /* */ /* */ public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { /* 200 */ a(world, blockposition, iblockdata, false, true, -1, (IBlockData)null); /* */ } /* */ /* */ private void a(World world, BlockPosition blockposition, boolean flag, boolean flag1, boolean flag2, boolean flag3) { /* 204 */ if (flag1 && !flag3) { /* 205 */ world.a(null, blockposition, SoundEffects.ia, SoundCategory.BLOCKS, 0.4F, 0.6F); /* 206 */ } else if (!flag1 && flag3) { /* 207 */ world.a(null, blockposition, SoundEffects.hZ, SoundCategory.BLOCKS, 0.4F, 0.5F); /* 208 */ } else if (flag && !flag2) { /* 209 */ world.a(null, blockposition, SoundEffects.hY, SoundCategory.BLOCKS, 0.4F, 0.7F); /* 210 */ } else if (!flag && flag2) { /* 211 */ world.a(null, blockposition, SoundEffects.ib, SoundCategory.BLOCKS, 0.4F, 1.2F / (world.random.nextFloat() * 0.2F + 0.9F)); /* */ } /* */ } /* */ /* */ /* */ private void a(World world, BlockPosition blockposition, EnumDirection enumdirection) { /* 217 */ world.applyPhysics(blockposition, this, false); /* 218 */ world.applyPhysics(blockposition.shift(enumdirection.opposite()), this, false); /* */ } /* */ /* */ private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { /* 222 */ if (!canPlace(world, blockposition)) { /* 223 */ b(world, blockposition, iblockdata, 0); /* 224 */ world.setAir(blockposition); /* 225 */ return false; /* */ } /* 227 */ return true; /* */ } /* */ /* */ /* */ public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { /* 232 */ boolean flag = ((Boolean)iblockdata.<Boolean>get(ATTACHED)).booleanValue(); /* 233 */ boolean flag1 = ((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue(); /* */ /* 235 */ if (flag || flag1) { /* 236 */ a(world, blockposition, iblockdata, true, false, -1, (IBlockData)null); /* */ } /* */ /* 239 */ if (flag1) { /* 240 */ world.applyPhysics(blockposition, this, false); /* 241 */ world.applyPhysics(blockposition.shift(((EnumDirection)iblockdata.<EnumDirection>get(FACING)).opposite()), this, false); /* */ } /* */ /* 244 */ super.remove(world, blockposition, iblockdata); /* */ } /* */ /* */ public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { /* 248 */ return ((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue() ? 15 : 0; /* */ } /* */ /* */ public int c(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { /* 252 */ return !((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue() ? 0 : ((iblockdata.get(FACING) == enumdirection) ? 15 : 0); /* */ } /* */ /* */ public boolean isPowerSource(IBlockData iblockdata) { /* 256 */ return true; /* */ } /* */ /* */ public IBlockData fromLegacyData(int i) { /* 260 */ return getBlockData().<Comparable, EnumDirection>set(FACING, EnumDirection.fromType2(i & 0x3)).<Comparable, Boolean>set(POWERED, Boolean.valueOf(((i & 0x8) > 0))).set(ATTACHED, Boolean.valueOf(((i & 0x4) > 0))); /* */ } /* */ /* */ public int toLegacyData(IBlockData iblockdata) { /* 264 */ byte b0 = 0; /* 265 */ int i = b0 | ((EnumDirection)iblockdata.<EnumDirection>get(FACING)).get2DRotationValue(); /* */ /* 267 */ if (((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue()) { /* 268 */ i |= 0x8; /* */ } /* */ /* 271 */ if (((Boolean)iblockdata.<Boolean>get(ATTACHED)).booleanValue()) { /* 272 */ i |= 0x4; /* */ } /* */ /* 275 */ return i; /* */ } /* */ /* */ public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { /* 279 */ return iblockdata.set(FACING, enumblockrotation.a(iblockdata.<EnumDirection>get(FACING))); /* */ } /* */ /* */ public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { /* 283 */ return iblockdata.a(enumblockmirror.a(iblockdata.<EnumDirection>get(FACING))); /* */ } /* */ /* */ protected BlockStateList getStateList() { /* 287 */ return new BlockStateList(this, (IBlockState<?>[])new IBlockState[] { FACING, POWERED, ATTACHED }); /* */ } /* */ /* */ public EnumBlockFaceShape a(IBlockAccess iblockaccess, IBlockData iblockdata, BlockPosition blockposition, EnumDirection enumdirection) { /* 291 */ return EnumBlockFaceShape.UNDEFINED; /* */ } /* */ } /* Location: C:\Users\Utilisateur\Desktop\spigot-1.12.jar!\net\minecraft\server\v1_12_R1\BlockTripwireHook.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
UTF-8
Java
14,497
java
BlockTripwireHook.java
Java
[]
null
[]
/* */ package net.minecraft.server.v1_12_R1; /* */ /* */ import com.google.common.base.MoreObjects; /* */ import java.util.Iterator; /* */ import java.util.Random; /* */ import javax.annotation.Nullable; /* */ import org.bukkit.block.Block; /* */ import org.bukkit.event.Event; /* */ import org.bukkit.event.block.BlockRedstoneEvent; /* */ /* */ public class BlockTripwireHook extends Block { /* 12 */ public static final BlockStateDirection FACING = BlockFacingHorizontal.FACING; /* 13 */ public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); /* 14 */ public static final BlockStateBoolean ATTACHED = BlockStateBoolean.of("attached"); /* 15 */ protected static final AxisAlignedBB d = new AxisAlignedBB(0.3125D, 0.0D, 0.625D, 0.6875D, 0.625D, 1.0D); /* 16 */ protected static final AxisAlignedBB e = new AxisAlignedBB(0.3125D, 0.0D, 0.0D, 0.6875D, 0.625D, 0.375D); /* 17 */ protected static final AxisAlignedBB f = new AxisAlignedBB(0.625D, 0.0D, 0.3125D, 1.0D, 0.625D, 0.6875D); /* 18 */ protected static final AxisAlignedBB g = new AxisAlignedBB(0.0D, 0.0D, 0.3125D, 0.375D, 0.625D, 0.6875D); /* */ /* */ public BlockTripwireHook() { /* 21 */ super(Material.ORIENTABLE); /* 22 */ w(this.blockStateList.getBlockData().<Comparable, EnumDirection>set(FACING, EnumDirection.NORTH).<Comparable, Boolean>set(POWERED, Boolean.valueOf(false)).set(ATTACHED, Boolean.valueOf(false))); /* 23 */ a(CreativeModeTab.d); /* 24 */ a(true); /* */ } /* */ /* */ public AxisAlignedBB b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { /* 28 */ switch ((EnumDirection)iblockdata.get(FACING)) { /* */ /* */ default: /* 31 */ return g; /* */ /* */ case WEST: /* 34 */ return f; /* */ /* */ case SOUTH: /* 37 */ return e; /* */ case NORTH: /* */ break; /* 40 */ } return d; /* */ } /* */ /* */ /* */ @Nullable /* */ public AxisAlignedBB a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { /* 46 */ return k; /* */ } /* */ /* */ public boolean b(IBlockData iblockdata) { /* 50 */ return false; /* */ } /* */ /* */ public boolean c(IBlockData iblockdata) { /* 54 */ return false; /* */ } /* */ /* */ public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { /* 58 */ EnumDirection enumdirection1 = enumdirection.opposite(); /* 59 */ BlockPosition blockposition1 = blockposition.shift(enumdirection1); /* 60 */ IBlockData iblockdata = world.getType(blockposition1); /* 61 */ boolean flag = c(iblockdata.getBlock()); /* */ /* 63 */ return (!flag && enumdirection.k().c() && iblockdata.d(world, blockposition1, enumdirection) == EnumBlockFaceShape.SOLID && !iblockdata.m()); /* */ } /* */ public boolean canPlace(World world, BlockPosition blockposition) { /* */ EnumDirection enumdirection; /* 67 */ Iterator<EnumDirection> iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); /* */ /* */ /* */ /* */ do { /* 72 */ if (!iterator.hasNext()) { /* 73 */ return false; /* */ } /* */ /* 76 */ enumdirection = iterator.next(); /* 77 */ } while (!canPlace(world, blockposition, enumdirection)); /* */ /* 79 */ return true; /* */ } /* */ /* */ public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { /* 83 */ IBlockData iblockdata = getBlockData().<Comparable, Boolean>set(POWERED, Boolean.valueOf(false)).set(ATTACHED, Boolean.valueOf(false)); /* */ /* 85 */ if (enumdirection.k().c()) { /* 86 */ iblockdata = iblockdata.set(FACING, enumdirection); /* */ } /* */ /* 89 */ return iblockdata; /* */ } /* */ /* */ public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { /* 93 */ a(world, blockposition, iblockdata, false, false, -1, (IBlockData)null); /* */ } /* */ /* */ public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1) { /* 97 */ if (block != this && /* 98 */ e(world, blockposition, iblockdata)) { /* 99 */ EnumDirection enumdirection = iblockdata.<EnumDirection>get(FACING); /* */ /* 101 */ if (!canPlace(world, blockposition, enumdirection)) { /* 102 */ b(world, blockposition, iblockdata, 0); /* 103 */ world.setAir(blockposition); /* */ } /* */ } /* */ } /* */ /* */ /* */ public void a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean flag1, int i, @Nullable IBlockData iblockdata1) { /* */ int n; /* 111 */ EnumDirection enumdirection = iblockdata.<EnumDirection>get(FACING); /* 112 */ int flag2 = ((Boolean)iblockdata.<Boolean>get(ATTACHED)).booleanValue(); /* 113 */ boolean flag3 = ((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue(); /* 114 */ boolean flag4 = !flag; /* 115 */ boolean flag5 = false; /* 116 */ int j = 0; /* 117 */ IBlockData[] aiblockdata = new IBlockData[42]; /* */ /* */ /* */ /* 121 */ for (int k = 1; k < 42; k++) { /* 122 */ BlockPosition blockposition1 = blockposition.shift(enumdirection, k); /* 123 */ IBlockData iblockdata2 = world.getType(blockposition1); /* */ /* 125 */ if (iblockdata2.getBlock() == Blocks.TRIPWIRE_HOOK) { /* 126 */ if (iblockdata2.get(FACING) == enumdirection.opposite()) { /* 127 */ j = k; /* */ } /* */ /* */ break; /* */ } /* 132 */ if (iblockdata2.getBlock() != Blocks.TRIPWIRE && k != i) { /* 133 */ aiblockdata[k] = null; /* 134 */ flag4 = false; /* */ } else { /* 136 */ if (k == i) { /* 137 */ iblockdata2 = (IBlockData)MoreObjects.firstNonNull(iblockdata1, iblockdata2); /* */ } /* */ /* 140 */ boolean flag6 = !((Boolean)iblockdata2.<Boolean>get(BlockTripwire.DISARMED)).booleanValue(); /* 141 */ boolean flag7 = ((Boolean)iblockdata2.<Boolean>get(BlockTripwire.POWERED)).booleanValue(); /* */ /* 143 */ n = flag5 | ((flag6 && flag7) ? 1 : 0); /* 144 */ aiblockdata[k] = iblockdata2; /* 145 */ if (k == i) { /* 146 */ world.a(blockposition, this, a(world)); /* 147 */ flag4 &= flag6; /* */ } /* */ } /* */ } /* */ /* 152 */ int m = flag4 & ((j > 1) ? 1 : 0); /* 153 */ n &= m; /* 154 */ IBlockData iblockdata3 = getBlockData().<Comparable, Boolean>set(ATTACHED, Boolean.valueOf(m)).set(POWERED, Boolean.valueOf(n)); /* */ /* 156 */ if (j > 0) { /* 157 */ BlockPosition blockposition1 = blockposition.shift(enumdirection, j); /* 158 */ EnumDirection enumdirection1 = enumdirection.opposite(); /* */ /* 160 */ world.setTypeAndData(blockposition1, iblockdata3.set(FACING, enumdirection1), 3); /* 161 */ a(world, blockposition1, enumdirection1); /* 162 */ a(world, blockposition1, m, n, flag2, flag3); /* */ } /* */ /* */ /* 166 */ Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); /* */ /* 168 */ BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, 15, 0); /* 169 */ world.getServer().getPluginManager().callEvent((Event)eventRedstone); /* */ /* 171 */ if (eventRedstone.getNewCurrent() > 0) { /* */ return; /* */ } /* */ /* */ /* 176 */ a(world, blockposition, m, n, flag2, flag3); /* 177 */ if (!flag) { /* 178 */ world.setTypeAndData(blockposition, iblockdata3.set(FACING, enumdirection), 3); /* 179 */ if (flag1) { /* 180 */ a(world, blockposition, enumdirection); /* */ } /* */ } /* */ /* 184 */ if (flag2 != m) { /* 185 */ for (int l = 1; l < j; l++) { /* 186 */ BlockPosition blockposition2 = blockposition.shift(enumdirection, l); /* 187 */ IBlockData iblockdata4 = aiblockdata[l]; /* */ /* 189 */ if (iblockdata4 != null && world.getType(blockposition2).getMaterial() != Material.AIR) { /* 190 */ world.setTypeAndData(blockposition2, iblockdata4.set(ATTACHED, Boolean.valueOf(m)), 3); /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* */ public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) {} /* */ /* */ public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { /* 200 */ a(world, blockposition, iblockdata, false, true, -1, (IBlockData)null); /* */ } /* */ /* */ private void a(World world, BlockPosition blockposition, boolean flag, boolean flag1, boolean flag2, boolean flag3) { /* 204 */ if (flag1 && !flag3) { /* 205 */ world.a(null, blockposition, SoundEffects.ia, SoundCategory.BLOCKS, 0.4F, 0.6F); /* 206 */ } else if (!flag1 && flag3) { /* 207 */ world.a(null, blockposition, SoundEffects.hZ, SoundCategory.BLOCKS, 0.4F, 0.5F); /* 208 */ } else if (flag && !flag2) { /* 209 */ world.a(null, blockposition, SoundEffects.hY, SoundCategory.BLOCKS, 0.4F, 0.7F); /* 210 */ } else if (!flag && flag2) { /* 211 */ world.a(null, blockposition, SoundEffects.ib, SoundCategory.BLOCKS, 0.4F, 1.2F / (world.random.nextFloat() * 0.2F + 0.9F)); /* */ } /* */ } /* */ /* */ /* */ private void a(World world, BlockPosition blockposition, EnumDirection enumdirection) { /* 217 */ world.applyPhysics(blockposition, this, false); /* 218 */ world.applyPhysics(blockposition.shift(enumdirection.opposite()), this, false); /* */ } /* */ /* */ private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { /* 222 */ if (!canPlace(world, blockposition)) { /* 223 */ b(world, blockposition, iblockdata, 0); /* 224 */ world.setAir(blockposition); /* 225 */ return false; /* */ } /* 227 */ return true; /* */ } /* */ /* */ /* */ public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { /* 232 */ boolean flag = ((Boolean)iblockdata.<Boolean>get(ATTACHED)).booleanValue(); /* 233 */ boolean flag1 = ((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue(); /* */ /* 235 */ if (flag || flag1) { /* 236 */ a(world, blockposition, iblockdata, true, false, -1, (IBlockData)null); /* */ } /* */ /* 239 */ if (flag1) { /* 240 */ world.applyPhysics(blockposition, this, false); /* 241 */ world.applyPhysics(blockposition.shift(((EnumDirection)iblockdata.<EnumDirection>get(FACING)).opposite()), this, false); /* */ } /* */ /* 244 */ super.remove(world, blockposition, iblockdata); /* */ } /* */ /* */ public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { /* 248 */ return ((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue() ? 15 : 0; /* */ } /* */ /* */ public int c(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { /* 252 */ return !((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue() ? 0 : ((iblockdata.get(FACING) == enumdirection) ? 15 : 0); /* */ } /* */ /* */ public boolean isPowerSource(IBlockData iblockdata) { /* 256 */ return true; /* */ } /* */ /* */ public IBlockData fromLegacyData(int i) { /* 260 */ return getBlockData().<Comparable, EnumDirection>set(FACING, EnumDirection.fromType2(i & 0x3)).<Comparable, Boolean>set(POWERED, Boolean.valueOf(((i & 0x8) > 0))).set(ATTACHED, Boolean.valueOf(((i & 0x4) > 0))); /* */ } /* */ /* */ public int toLegacyData(IBlockData iblockdata) { /* 264 */ byte b0 = 0; /* 265 */ int i = b0 | ((EnumDirection)iblockdata.<EnumDirection>get(FACING)).get2DRotationValue(); /* */ /* 267 */ if (((Boolean)iblockdata.<Boolean>get(POWERED)).booleanValue()) { /* 268 */ i |= 0x8; /* */ } /* */ /* 271 */ if (((Boolean)iblockdata.<Boolean>get(ATTACHED)).booleanValue()) { /* 272 */ i |= 0x4; /* */ } /* */ /* 275 */ return i; /* */ } /* */ /* */ public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { /* 279 */ return iblockdata.set(FACING, enumblockrotation.a(iblockdata.<EnumDirection>get(FACING))); /* */ } /* */ /* */ public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { /* 283 */ return iblockdata.a(enumblockmirror.a(iblockdata.<EnumDirection>get(FACING))); /* */ } /* */ /* */ protected BlockStateList getStateList() { /* 287 */ return new BlockStateList(this, (IBlockState<?>[])new IBlockState[] { FACING, POWERED, ATTACHED }); /* */ } /* */ /* */ public EnumBlockFaceShape a(IBlockAccess iblockaccess, IBlockData iblockdata, BlockPosition blockposition, EnumDirection enumdirection) { /* 291 */ return EnumBlockFaceShape.UNDEFINED; /* */ } /* */ } /* Location: C:\Users\Utilisateur\Desktop\spigot-1.12.jar!\net\minecraft\server\v1_12_R1\BlockTripwireHook.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
14,497
0.553908
0.513003
299
46.491638
41.091736
225
false
false
0
0
0
0
0
0
1.060201
false
false
5
e2116c55ae9f8c86c79ee80801e1df49eeb79068
17,420,387,364,562
b110463ee25bc97c520e11ca7fef51b22fd32195
/src/main/java/com/james137137/LimitedWorldEdit/LimitedWorldEdit.java
42e8640874b9069011b3b22cb443aaca16291dae
[]
no_license
James137137/LimitedWorldEdit
https://github.com/James137137/LimitedWorldEdit
a19879e7f9746d76caaf356765548f028cb1fafd
bef7745b2a56ec6b74207973b3e69ed01a615f59
refs/heads/master
2021-01-25T08:28:32.730000
2017-04-19T23:09:43
2017-04-19T23:09:43
9,484,280
2
0
null
false
2014-10-20T19:42:02
2013-04-16T22:38:58
2014-10-20T19:16:29
2014-10-20T19:42:02
200
1
1
0
Java
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.james137137.LimitedWorldEdit; import com.james137137.LimitedWorldEdit.hooks.API; import com.james137137.LimitedWorldEdit.hooks.WorldGaurdAPI; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; /** * * @author James */ public class LimitedWorldEdit extends JavaPlugin { static final Logger log = Logger.getLogger("Minecraft"); public double delay; //in secounds WorldGaurdAPI worldGaurdAPI = null; public static API api; public static WorldEditPlugin worldEdit; @Override public void onEnable() { saveConfig(); Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); if (plugin != null) { api = new WorldGaurdAPI(this); } WorldEdit.getInstance().getEventBus().register(new LimitedWorldEditListener(this)); String version = Bukkit.getServer().getPluginManager().getPlugin(this.getName()).getDescription().getVersion(); log.log(Level.INFO, this.getName() + ":Version {0} enabled", version); } @Override public void onDisable() { log.info("LimitedWorldEdit: disabled"); } }
UTF-8
Java
1,439
java
LimitedWorldEdit.java
Java
[ { "context": " open the template in the editor.\n */\npackage com.james137137.LimitedWorldEdit;\n\nimport com.james137137.Limited", "end": 123, "score": 0.9539467096328735, "start": 112, "tag": "USERNAME", "value": "james137137" }, { "context": "age com.james137137.LimitedWorldEdit;\n\nimport com.james137137.LimitedWorldEdit.hooks.API;\nimport com.james13713", "end": 165, "score": 0.9013731479644775, "start": 154, "tag": "USERNAME", "value": "james137137" }, { "context": "mes137137.LimitedWorldEdit.hooks.API;\nimport com.james137137.LimitedWorldEdit.hooks.WorldGaurdAPI;\nimport com.", "end": 216, "score": 0.8182488679885864, "start": 206, "tag": "USERNAME", "value": "ames137137" }, { "context": ".bukkit.plugin.java.JavaPlugin;\n\n/**\n *\n * @author James\n */\npublic class LimitedWorldEdit extends JavaPlu", "end": 534, "score": 0.9976483583450317, "start": 529, "tag": "NAME", "value": "James" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.james137137.LimitedWorldEdit; import com.james137137.LimitedWorldEdit.hooks.API; import com.james137137.LimitedWorldEdit.hooks.WorldGaurdAPI; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; /** * * @author James */ public class LimitedWorldEdit extends JavaPlugin { static final Logger log = Logger.getLogger("Minecraft"); public double delay; //in secounds WorldGaurdAPI worldGaurdAPI = null; public static API api; public static WorldEditPlugin worldEdit; @Override public void onEnable() { saveConfig(); Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); if (plugin != null) { api = new WorldGaurdAPI(this); } WorldEdit.getInstance().getEventBus().register(new LimitedWorldEditListener(this)); String version = Bukkit.getServer().getPluginManager().getPlugin(this.getName()).getDescription().getVersion(); log.log(Level.INFO, this.getName() + ":Version {0} enabled", version); } @Override public void onDisable() { log.info("LimitedWorldEdit: disabled"); } }
1,439
0.706741
0.690757
50
27.780001
27.094126
119
false
false
0
0
0
0
0
0
0.52
false
false
5
e7410ca95fa62bc14612a305d24f1159fb81c481
8,667,244,039,929
5e384938f407cf09b9f0d7561336dddb5d4599aa
/ProjetosExemplos/ProjetoInterface/src/projetointerface/ProjetoInterface.java
01af465af7ccbafd12060ad7a1fef0bd3aa83378
[]
no_license
Mardoniosc/java_udemy
https://github.com/Mardoniosc/java_udemy
2967d19dac4686ed6f6a421480388c55df2f790f
635d1b4ce3c56571adb19884e205e120f9cc46bd
refs/heads/master
2020-05-25T00:46:30.796000
2019-08-16T13:39:00
2019-08-16T13:39:00
187,537,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package projetointerface; public class ProjetoInterface { public static void main(String[] args) { Caneta caneta = new Caneta("Azul"); Lapis lapis = new Lapis("Preto"); Giz giz = new Giz("Verde"); System.out.println("A caneta tem a cor: " + caneta.cor()); caneta.escrever("Este é o texto escrito pela caneta"); System.out.println("O lapis tem a cor: " + lapis.cor()); lapis.escrever("Este é o texto escrito pelo lapis"); System.out.println("O giz tem a cor: " + giz.cor()); giz.escrever("Este é o texto escrito pelo giz"); } }
WINDOWS-1252
Java
560
java
ProjetoInterface.java
Java
[]
null
[]
package projetointerface; public class ProjetoInterface { public static void main(String[] args) { Caneta caneta = new Caneta("Azul"); Lapis lapis = new Lapis("Preto"); Giz giz = new Giz("Verde"); System.out.println("A caneta tem a cor: " + caneta.cor()); caneta.escrever("Este é o texto escrito pela caneta"); System.out.println("O lapis tem a cor: " + lapis.cor()); lapis.escrever("Este é o texto escrito pelo lapis"); System.out.println("O giz tem a cor: " + giz.cor()); giz.escrever("Este é o texto escrito pelo giz"); } }
560
0.667864
0.667864
20
26.85
23.160904
60
false
false
0
0
0
0
0
0
1.7
false
false
5
cea025624e5285b0b88ca5d005cb0b310164a772
18,992,345,385,960
20a7b28987fdf7b48267b42d146a7eefd63b0048
/webshopbkd/src/test/java/com/abhi/webshopbkd/test/ProductTestCase.java
ec81bc1c467a8d0e500b5d382ea8556091dc7821
[]
no_license
NeoAbhiS/WebShopping
https://github.com/NeoAbhiS/WebShopping
60f109b14ac96ce427e262ce75e3c9d6ecf71d6f
bdbd399fef9ac686c9fca6d737cf135663f8f78a
refs/heads/master
2021-08-23T22:21:00.785000
2017-12-06T21:16:03
2017-12-06T21:16:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package com.abhi.webshopbkd.test; // //import static org.junit.Assert.assertEquals; // //import org.junit.BeforeClass; //import org.junit.Test; //import org.springframework.context.annotation.AnnotationConfigApplicationContext; // //import com.abhi.webshopbkd.dao.ProductDAO; //import com.abhi.webshopbkd.dto.Product; // //public class ProductTestCase { // // private static AnnotationConfigApplicationContext context; // // private static ProductDAO productDAO; // // private Product product; // //// @BeforeClass //// public static void init() { //// //// context = new AnnotationConfigApplicationContext(); //// context.scan("com.abhi.webshopbkd"); //// context.refresh(); //// //// productDAO = (ProductDAO) context.getBean("productDAO"); //// } // // // @Test // // public void testAddProduct() { // // Product = new Product(); // // // // Product.setName("Television"); // // Product.setDescription("Description for Tele from id 1"); // // Product.setImageURL("cat1.png"); // // // // assertEquals("Successfully added a Product inside the // // table!",true,ProductDAO.add(Product)); // // // // } // // /* // * @Test public void testGetProduct() { // * // * Product = ProductDAO.get(2); // * assertEquals("Successfully fetched a single Product from table","Laptop", // * Product.getName()); } // */ // // /* // * @Test public void testUpdateProduct() { // * // * Product = ProductDAO.get(1); Product.setName("TV"); // * assertEquals("Successfully update a single Product in the table",true, // * ProductDAO.update(Product)); } // */ // // /* // * @Test public void testDeleteProduct() { // * // * Product = ProductDAO.get(1); // * assertEquals("Successfully update a single Product in the table",false, // * ProductDAO.delete(Product)); } // */ // // /* // * @Test public void testListProduct() { // * // * assertEquals("Successfully fetched list of categories from the table",2, // * ProductDAO.list().size()); } // */ //// @Test //// public void testCRUDProduct() { //// //// //// //Add the Product //// //// //// product = new Product(); //// //// product.setName("Moto Moto"); //// product.setBrand("MOTO"); //// product.setDescription("Motrola Mobile"); //// product.setUnitPrice(120); //// product.setActive(true); //// product.setCategoryId(3); //// product.setSupplierId(3); //// //// assertEquals("Something went wrong while inserting new product!", true, productDAO.add(product)); //// //// product = new Product(); //// //// product.setName("Samsung Galaxy S4"); //// product.setBrand("Samsung"); //// product.setDescription("Samsung Mobile"); //// product.setUnitPrice(520); //// product.setActive(true); //// product.setCategoryId(3); //// product.setSupplierId(3); //// assertEquals("Something went wrong while inserting new product!", true, productDAO.add(product)); //// //// //Update the Product //// product = productDAO.get(3); //// product.setActive(false); //// assertEquals("Something went wrong while updating the product!", true, productDAO.update(product)); //// //// //Delete the Product //// assertEquals("Something went wrong while deleting the product!", true, productDAO.delete(product)); //// //// //Fetching the Product list //// assertEquals("Something went wrong while fetching the products!", 7, productDAO.list().size()); //// //// //Fetching the active Product list //// assertEquals("Something went wrong while fetching the active products!", 5, productDAO.listActiveProducts().size()); //// //// //Fetching the active Product by Category //// assertEquals("Something went wrong while fetching the active products!", 3, productDAO.listActiveProductsByCategory(3).size()); //// //// //Fetching the active Product by count //// assertEquals("Something went wrong while fetching the products by count!", 4, productDAO.getLatestActiveProducts(4).size()); //// //// } // //}
UTF-8
Java
3,902
java
ProductTestCase.java
Java
[ { "context": "duct = new Product();\n////\n////\t\tproduct.setName(\"Moto Moto\");\n////\t\tproduct.setBrand(\"MOTO\");\n////\t\tproduct.", "end": 2126, "score": 0.7895020246505737, "start": 2117, "tag": "NAME", "value": "Moto Moto" } ]
null
[]
//package com.abhi.webshopbkd.test; // //import static org.junit.Assert.assertEquals; // //import org.junit.BeforeClass; //import org.junit.Test; //import org.springframework.context.annotation.AnnotationConfigApplicationContext; // //import com.abhi.webshopbkd.dao.ProductDAO; //import com.abhi.webshopbkd.dto.Product; // //public class ProductTestCase { // // private static AnnotationConfigApplicationContext context; // // private static ProductDAO productDAO; // // private Product product; // //// @BeforeClass //// public static void init() { //// //// context = new AnnotationConfigApplicationContext(); //// context.scan("com.abhi.webshopbkd"); //// context.refresh(); //// //// productDAO = (ProductDAO) context.getBean("productDAO"); //// } // // // @Test // // public void testAddProduct() { // // Product = new Product(); // // // // Product.setName("Television"); // // Product.setDescription("Description for Tele from id 1"); // // Product.setImageURL("cat1.png"); // // // // assertEquals("Successfully added a Product inside the // // table!",true,ProductDAO.add(Product)); // // // // } // // /* // * @Test public void testGetProduct() { // * // * Product = ProductDAO.get(2); // * assertEquals("Successfully fetched a single Product from table","Laptop", // * Product.getName()); } // */ // // /* // * @Test public void testUpdateProduct() { // * // * Product = ProductDAO.get(1); Product.setName("TV"); // * assertEquals("Successfully update a single Product in the table",true, // * ProductDAO.update(Product)); } // */ // // /* // * @Test public void testDeleteProduct() { // * // * Product = ProductDAO.get(1); // * assertEquals("Successfully update a single Product in the table",false, // * ProductDAO.delete(Product)); } // */ // // /* // * @Test public void testListProduct() { // * // * assertEquals("Successfully fetched list of categories from the table",2, // * ProductDAO.list().size()); } // */ //// @Test //// public void testCRUDProduct() { //// //// //// //Add the Product //// //// //// product = new Product(); //// //// product.setName("<NAME>"); //// product.setBrand("MOTO"); //// product.setDescription("Motrola Mobile"); //// product.setUnitPrice(120); //// product.setActive(true); //// product.setCategoryId(3); //// product.setSupplierId(3); //// //// assertEquals("Something went wrong while inserting new product!", true, productDAO.add(product)); //// //// product = new Product(); //// //// product.setName("Samsung Galaxy S4"); //// product.setBrand("Samsung"); //// product.setDescription("Samsung Mobile"); //// product.setUnitPrice(520); //// product.setActive(true); //// product.setCategoryId(3); //// product.setSupplierId(3); //// assertEquals("Something went wrong while inserting new product!", true, productDAO.add(product)); //// //// //Update the Product //// product = productDAO.get(3); //// product.setActive(false); //// assertEquals("Something went wrong while updating the product!", true, productDAO.update(product)); //// //// //Delete the Product //// assertEquals("Something went wrong while deleting the product!", true, productDAO.delete(product)); //// //// //Fetching the Product list //// assertEquals("Something went wrong while fetching the products!", 7, productDAO.list().size()); //// //// //Fetching the active Product list //// assertEquals("Something went wrong while fetching the active products!", 5, productDAO.listActiveProducts().size()); //// //// //Fetching the active Product by Category //// assertEquals("Something went wrong while fetching the active products!", 3, productDAO.listActiveProductsByCategory(3).size()); //// //// //Fetching the active Product by count //// assertEquals("Something went wrong while fetching the products by count!", 4, productDAO.getLatestActiveProducts(4).size()); //// //// } // //}
3,899
0.654792
0.648642
125
30.216
29.777464
133
false
false
0
0
0
0
0
0
1.736
false
false
5
8e3fb85726961487629af688197925da6b947726
26,225,070,351,659
337eaf4af6734b32e1e7df00cb2ef0f173ba4c97
/src/com/faustas/dbms/scenarios/AddRecipeScenario.java
19a5115cdaa07dc52262c75a8598be5aa8da9e11
[]
no_license
faustuzas/RecipesApp
https://github.com/faustuzas/RecipesApp
99501dc01cee245ff1a1cdb7589fa71a74d6dcb3
650853175c0f473993a6a164fac7e43439fcd880
refs/heads/master
2020-05-20T08:15:05.713000
2019-05-21T09:33:48
2019-05-21T09:33:48
185,470,090
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.faustas.dbms.scenarios; import com.faustas.dbms.framework.annotations.Service; import com.faustas.dbms.interfaces.SecurityContext; import com.faustas.dbms.models.Ingredient; import com.faustas.dbms.models.Recipe; import com.faustas.dbms.services.ConsoleInteractor; import com.faustas.dbms.services.ProductService; import com.faustas.dbms.services.RecipeService; import com.faustas.dbms.utils.NumberReader; import java.util.ArrayList; import java.util.List; @Service public class AddRecipeScenario extends RecipeCRUDScenario { private SecurityContext securityContext; public AddRecipeScenario(ConsoleInteractor interactor, ProductService productService, NumberReader numberReader, RecipeService recipeService, SecurityContext securityContext) { super(interactor, productService, numberReader, recipeService); this.securityContext = securityContext; } @Override public boolean action() { interactor.printHeader("Add new recipe"); Recipe recipe = new Recipe(); interactor.printSectionHeader("Main information"); String title = interactor.ask("Recipe title: "); recipe.setTitle(title); String description = interactor.ask("Recipe description: "); recipe.setDescription(description); interactor.print("Minutes to prepare"); Integer minutesToPrepare = numberReader.readInteger("Minutes > ", "Enter only number of minutes"); recipe.setMinutesToPrepare(minutesToPrepare); List<Ingredient> ingredients = new ArrayList<>(); ingredientsLoop: while (true) { interactor.printSeparator(); interactor.print("1. Add ingredient"); interactor.print("2. Finish adding ingredients"); switch (interactor.getString()) { case "1": Ingredient ingredient = createNewIngredient(); if (ingredient == null) { break ingredientsLoop; } ingredients.add(ingredient); break; case "2": recipe.setIngredients(ingredients); break ingredientsLoop; default: printHelp(); } } try { recipeService.insertForUser(recipe, securityContext.getAuthenticatedUser()); interactor.printSuccess(String.format("Recipe \"%s\" successfully added", recipe.getTitle())); } catch (Exception e) { e.printStackTrace(); interactor.printError("Recipe with this title already exists"); } return true; } }
UTF-8
Java
2,754
java
AddRecipeScenario.java
Java
[]
null
[]
package com.faustas.dbms.scenarios; import com.faustas.dbms.framework.annotations.Service; import com.faustas.dbms.interfaces.SecurityContext; import com.faustas.dbms.models.Ingredient; import com.faustas.dbms.models.Recipe; import com.faustas.dbms.services.ConsoleInteractor; import com.faustas.dbms.services.ProductService; import com.faustas.dbms.services.RecipeService; import com.faustas.dbms.utils.NumberReader; import java.util.ArrayList; import java.util.List; @Service public class AddRecipeScenario extends RecipeCRUDScenario { private SecurityContext securityContext; public AddRecipeScenario(ConsoleInteractor interactor, ProductService productService, NumberReader numberReader, RecipeService recipeService, SecurityContext securityContext) { super(interactor, productService, numberReader, recipeService); this.securityContext = securityContext; } @Override public boolean action() { interactor.printHeader("Add new recipe"); Recipe recipe = new Recipe(); interactor.printSectionHeader("Main information"); String title = interactor.ask("Recipe title: "); recipe.setTitle(title); String description = interactor.ask("Recipe description: "); recipe.setDescription(description); interactor.print("Minutes to prepare"); Integer minutesToPrepare = numberReader.readInteger("Minutes > ", "Enter only number of minutes"); recipe.setMinutesToPrepare(minutesToPrepare); List<Ingredient> ingredients = new ArrayList<>(); ingredientsLoop: while (true) { interactor.printSeparator(); interactor.print("1. Add ingredient"); interactor.print("2. Finish adding ingredients"); switch (interactor.getString()) { case "1": Ingredient ingredient = createNewIngredient(); if (ingredient == null) { break ingredientsLoop; } ingredients.add(ingredient); break; case "2": recipe.setIngredients(ingredients); break ingredientsLoop; default: printHelp(); } } try { recipeService.insertForUser(recipe, securityContext.getAuthenticatedUser()); interactor.printSuccess(String.format("Recipe \"%s\" successfully added", recipe.getTitle())); } catch (Exception e) { e.printStackTrace(); interactor.printError("Recipe with this title already exists"); } return true; } }
2,754
0.631082
0.62963
80
33.424999
27.075254
106
false
false
0
0
0
0
0
0
0.625
false
false
5
03d11149a9f3548aea729c7a0c3b229f04573934
429,496,753,735
f8f11d1a0faa476ed2540934151750b0d809a5c0
/SortAlgorithmVisualizer/src/main/SortAlgorithmVisualizer.java
efdac34c584ff930d4c2caba0d1d6d3e7554bee3
[]
no_license
markekvall/code-projects
https://github.com/markekvall/code-projects
4748c0246678e033ca3712163bf6ab2b6b380e5a
520c297218700f1182a02050784b92befc15e1f0
refs/heads/main
2023-05-06T05:56:07.922000
2021-05-25T11:38:34
2021-05-25T11:38:34
357,164,289
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main; import java.awt.*; import java.awt.image.BufferStrategy; import java.util.Scanner; /*-------------------------------------------------- Created by Mark Ekvall 2021-05 --------------------------------------------------*/ public class SortAlgorithmVisualizer extends Canvas { public static final int WIN_WIDTH = 1280, WIN_HEIGHT = 720; public static final int BAR_WIDTH = 8; public static final int NUM_BARS = WIN_WIDTH / BAR_WIDTH; private String userChoice; private ArraySetUp arraySetUp; public SortAlgorithmVisualizer() { arraySetUp = new ArraySetUp(); arraySetUp.constructArray(NUM_BARS); arraySetUp.shuffleArray(NUM_BARS); new Window(WIN_WIDTH, WIN_HEIGHT, "Sorting visualizer", this); } public void manager() { userChoice = userInput(); arraySetUp.manager(this, userChoice); } public void render() { BufferStrategy bs = this.getBufferStrategy(); if(bs == null) { this.createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, WIN_WIDTH, WIN_HEIGHT); arraySetUp.render(g); g.dispose(); bs.show(); } public String userInput() { Scanner scanner = new Scanner(System.in); // Create a Scanner from scanner class System.out.println("Please choose sorting method: "); System.out.println("1. Type 'bubble' for bubble sort"); System.out.println("2. Type 'insert' for insert sort"); System.out.println("3. Type 'merge' for merge sort"); return scanner.nextLine(); } public static void main (String[] args) { new SortAlgorithmVisualizer(); } }
UTF-8
Java
1,847
java
SortAlgorithmVisualizer.java
Java
[ { "context": "--------------------------------------\r\nCreated by Mark Ekvall\r\n2021-05\r\n --------------------------------------", "end": 179, "score": 0.9998009204864502, "start": 168, "tag": "NAME", "value": "Mark Ekvall" } ]
null
[]
package main; import java.awt.*; import java.awt.image.BufferStrategy; import java.util.Scanner; /*-------------------------------------------------- Created by <NAME> 2021-05 --------------------------------------------------*/ public class SortAlgorithmVisualizer extends Canvas { public static final int WIN_WIDTH = 1280, WIN_HEIGHT = 720; public static final int BAR_WIDTH = 8; public static final int NUM_BARS = WIN_WIDTH / BAR_WIDTH; private String userChoice; private ArraySetUp arraySetUp; public SortAlgorithmVisualizer() { arraySetUp = new ArraySetUp(); arraySetUp.constructArray(NUM_BARS); arraySetUp.shuffleArray(NUM_BARS); new Window(WIN_WIDTH, WIN_HEIGHT, "Sorting visualizer", this); } public void manager() { userChoice = userInput(); arraySetUp.manager(this, userChoice); } public void render() { BufferStrategy bs = this.getBufferStrategy(); if(bs == null) { this.createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, WIN_WIDTH, WIN_HEIGHT); arraySetUp.render(g); g.dispose(); bs.show(); } public String userInput() { Scanner scanner = new Scanner(System.in); // Create a Scanner from scanner class System.out.println("Please choose sorting method: "); System.out.println("1. Type 'bubble' for bubble sort"); System.out.println("2. Type 'insert' for insert sort"); System.out.println("3. Type 'merge' for merge sort"); return scanner.nextLine(); } public static void main (String[] args) { new SortAlgorithmVisualizer(); } }
1,842
0.571738
0.56091
64
26.859375
23.003305
89
false
false
0
0
0
0
0
0
0.609375
false
false
5
325177f205d320e0b866e3b409f2c4182073a4f1
22,565,758,184,824
b6d5b955e58f3aa5af831c03cd010e92bb4b9028
/out/production/HackerRank/src/hackerrank/Regex.java
8e85a852b77ce46039cbc8fb2fd24588a0ce87a0
[]
no_license
Rattlehead931/hackerrankProblems
https://github.com/Rattlehead931/hackerrankProblems
6d4878e13cb4dbf6d8742784670a98714de465fd
1e36c23364f355e80c84e8a17e31833726cd93c4
refs/heads/master
2019-03-16T23:06:07.058000
2018-04-03T12:03:58
2018-04-03T12:03:58
123,023,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hackerrank; import java.util.regex.*; public class Regex { public static void main(String args[]) { String longString = "Blah blah"; } public static void regexChecker(String regex,String toCheck) { Pattern checkRegex = Pattern.compile(regex); Matcher regexMatcher = checkRegex.matcher(toCheck); } }
UTF-8
Java
363
java
Regex.java
Java
[]
null
[]
package hackerrank; import java.util.regex.*; public class Regex { public static void main(String args[]) { String longString = "Blah blah"; } public static void regexChecker(String regex,String toCheck) { Pattern checkRegex = Pattern.compile(regex); Matcher regexMatcher = checkRegex.matcher(toCheck); } }
363
0.652893
0.652893
21
16.285715
21.33886
64
false
false
0
0
0
0
0
0
0.285714
false
false
5
e06ba4c37aa6180e0fbe6ae6ad6bf6a5045bbf9b
34,514,357,240,608
6631a6857a5b6d635b3c8c3537926125f2190102
/app/src/main/java/neo/vn/test365children/Presenter/Iml_init.java
29415df9debaa0c6646be8d29acfd295f01f17c8
[]
no_license
quochuy190/Test365Children
https://github.com/quochuy190/Test365Children
0f9b37f675d52f60d912f6215dd64a26151b0647
d7d068aa6cbc76e8ac4a49d5570af6d5f7103e3c
refs/heads/master
2021-06-04T01:40:37.204000
2020-03-03T03:42:12
2020-03-03T03:42:12
147,315,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package neo.vn.test365children.Presenter; import neo.vn.test365children.Models.ErrorApi; import neo.vn.test365children.Models.respon_api.ResponInitChil; public interface Iml_init { interface Presenter { void api_init(String APP_VERSION, String DEVICE_MODEL, String TOKEN_KEY, String DEVICE_TYPE, String OS_VERSION, String UUID); void api_update_info_chil(String USER_MOTHER, String USER_CHILD, String ID_SCHOOL, String ID_LEVEL, String CLASS, String ID_YEAR, String CHILD_NAME, String CHILD_PASS, String LINK_AVATAR, String MOBILE, String EMAIL); void api_update_info_chil_2(String USER_MOTHER, String USER_CHILD, String ID_SCHOOL, String ID_LEVEL, String CLASS, String ID_YEAR, String CHILD_NAME, String CHILD_PASS, String LINK_AVATAR, String MOBILE, String EMAIL, String ISUPDATE); void api_update_child_device(String USER_MOTHER, String USER_CHILD, String APP_VERSION, String DEVICE_MODEL, String TOKEN_KEY, String DEVICE_TYPE, String OS_VERSION); } interface View { void show_init(ResponInitChil mLis); void show_error_api(ErrorApi mLis); void show_update_infor_child(ErrorApi mLis); void show_update_infor_child_2(ErrorApi mLis); } }
UTF-8
Java
1,427
java
Iml_init.java
Java
[]
null
[]
package neo.vn.test365children.Presenter; import neo.vn.test365children.Models.ErrorApi; import neo.vn.test365children.Models.respon_api.ResponInitChil; public interface Iml_init { interface Presenter { void api_init(String APP_VERSION, String DEVICE_MODEL, String TOKEN_KEY, String DEVICE_TYPE, String OS_VERSION, String UUID); void api_update_info_chil(String USER_MOTHER, String USER_CHILD, String ID_SCHOOL, String ID_LEVEL, String CLASS, String ID_YEAR, String CHILD_NAME, String CHILD_PASS, String LINK_AVATAR, String MOBILE, String EMAIL); void api_update_info_chil_2(String USER_MOTHER, String USER_CHILD, String ID_SCHOOL, String ID_LEVEL, String CLASS, String ID_YEAR, String CHILD_NAME, String CHILD_PASS, String LINK_AVATAR, String MOBILE, String EMAIL, String ISUPDATE); void api_update_child_device(String USER_MOTHER, String USER_CHILD, String APP_VERSION, String DEVICE_MODEL, String TOKEN_KEY, String DEVICE_TYPE, String OS_VERSION); } interface View { void show_init(ResponInitChil mLis); void show_error_api(ErrorApi mLis); void show_update_infor_child(ErrorApi mLis); void show_update_infor_child_2(ErrorApi mLis); } }
1,427
0.633497
0.625788
32
43.59375
41.153568
116
false
false
0
0
0
0
0
0
1.34375
false
false
5
c1d75627c8fe5f1d74d6d1bf78d0bfe3892f05e8
38,843,684,244,412
13cd3d6480346abb4e634432b90ea2125e77d056
/app/src/main/java/com/dragoninst/bluedragon/BlueDragon.java
45c6cfb27e46dec921ab72158e60ee7d69750592
[]
no_license
chrysaor/DragonNest
https://github.com/chrysaor/DragonNest
90aa5ad4cf1f02fac35b7214d94ed85875166fbd
fe9d3fec71dc223bdc5e85c96de669d77685d60e
refs/heads/master
2018-01-08T19:05:47.754000
2016-04-01T02:26:23
2016-04-01T02:26:23
52,540,904
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dragoninst.bluedragon; import com.dragoninst.dragon.AbstractDragon; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.epoll.EpollChannelOption; import io.netty.channel.epoll.EpollDatagramChannel; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; public class BlueDragon extends AbstractDragon { public BlueDragon(ChannelInitializer<?> initializer, int port, int threadNum) { this.channelInitializer = initializer; this.port = port; this.threadCount = threadNum; } // Method from abstractDragon @Override protected boolean initDragon() { System.out.println("initDragon"); rootGroup = new EpollEventLoopGroup(threadCount); bootstrap.group(rootGroup) .channel(EpollDatagramChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(EpollChannelOption.SO_REUSEPORT, true) .handler(new LoggingHandler(LogLevel.INFO)) .handler(channelInitializer); return true; } @Override protected void runDragon() { try { bootstrap.bind(port).sync().channel().closeFuture().await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { shutdownGracefully(); } } @Override protected void shutdownGracefully() { rootGroup.shutdownGracefully(); } }
UTF-8
Java
1,464
java
BlueDragon.java
Java
[]
null
[]
package com.dragoninst.bluedragon; import com.dragoninst.dragon.AbstractDragon; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.epoll.EpollChannelOption; import io.netty.channel.epoll.EpollDatagramChannel; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; public class BlueDragon extends AbstractDragon { public BlueDragon(ChannelInitializer<?> initializer, int port, int threadNum) { this.channelInitializer = initializer; this.port = port; this.threadCount = threadNum; } // Method from abstractDragon @Override protected boolean initDragon() { System.out.println("initDragon"); rootGroup = new EpollEventLoopGroup(threadCount); bootstrap.group(rootGroup) .channel(EpollDatagramChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(EpollChannelOption.SO_REUSEPORT, true) .handler(new LoggingHandler(LogLevel.INFO)) .handler(channelInitializer); return true; } @Override protected void runDragon() { try { bootstrap.bind(port).sync().channel().closeFuture().await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { shutdownGracefully(); } } @Override protected void shutdownGracefully() { rootGroup.shutdownGracefully(); } }
1,464
0.766393
0.766393
58
24.241379
21.210205
80
false
false
0
0
0
0
0
0
1.689655
false
false
5
f5f1363f7473b23908cd74417183376b32a4bbc7
39,024,072,868,730
9d280b50198f56bfb1165003c8cb95f51ae0e367
/app/src/main/java/com/example/hp/iclass/PersonCenter/SettingActivity.java
83476af5d87114fe1ad431486449074589ae7714
[]
no_license
spencercjh/iClass
https://github.com/spencercjh/iClass
608f93e879551980958c740739e47dd8845377a3
e31f514731c5d894d1b36bf70658d97e596c9903
refs/heads/master
2021-09-13T00:23:16.218000
2018-04-23T06:28:27
2018-04-23T06:28:27
113,036,949
4
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hp.iclass.PersonCenter; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.CompoundButton; import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.Toast; import com.example.hp.iclass.CommonActivity.BeginningActivity.Login.LoginActivity; import com.example.hp.iclass.CommonActivity.MainActivity; import com.example.hp.iclass.OBJ.StudentOBJ; import com.example.hp.iclass.OBJ.TeacherOBJ; import com.example.hp.iclass.R; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Properties; public class SettingActivity extends AppCompatActivity { private StudentOBJ studentOBJ = new StudentOBJ(); private TeacherOBJ teacherOBJ = new TeacherOBJ(); private RelativeLayout re_endlogin; private Switch sw_message; private Switch sw_muted; private String user = ""; private int choice_user; private Toolbar tl_head; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); Intent intent = getIntent(); user = (String) intent.getSerializableExtra("user"); if (user.equals("teacher")) { choice_user = 1; teacherOBJ = (TeacherOBJ) intent.getSerializableExtra("teacherOBJ"); } else if (user.equals("student")) { choice_user = 0; studentOBJ = (StudentOBJ) intent.getSerializableExtra("studentOBJ"); } re_endlogin = (RelativeLayout) findViewById(R.id.rl_endlogin); sw_muted = (Switch) findViewById(R.id.sw_muted); sw_message = (Switch) findViewById(R.id.sw_message); tl_head = (Toolbar) findViewById(R.id.tl_head); tl_head.setNavigationIcon(R.drawable.ic_back); tl_head.setTitle(" 设置"); tl_head.setTitleTextColor(Color.WHITE); tl_head.setNavigationIcon(R.drawable.ic_back); setSupportActionBar(tl_head); tl_head.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { gotomain(); } }); set_switch_bar(); sw_muted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (compoundButton.isChecked()) { Properties prop = loadConfig(getApplicationContext(), "/mnt/sdcard/config.properties"); if (prop == null) { // 配置文件不存在的时候创建配置文件 初始化配置信息 prop = new Properties(); prop.put("muted", "true"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } else { prop.put("muted", "true"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } // Toast.makeText(getApplicationContext(), "设置成功 开启", Toast.LENGTH_SHORT).show(); } else { Properties prop = loadConfig(getApplicationContext(), "/mnt/sdcard/config.properties"); if (prop == null) { // 配置文件不存在的时候创建配置文件 初始化配置信息 prop = new Properties(); prop.put("muted", "false"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } else { prop.put("muted", "false"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } // Toast.makeText(getApplicationContext(), "设置成功 关闭", Toast.LENGTH_SHORT).show(); } } }); sw_message.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (compoundButton.isChecked()) { Toast.makeText(getApplicationContext(), "开", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "关", Toast.LENGTH_SHORT).show(); } } }); } public boolean saveConfig(Context context, String file, Properties properties) { try { File fil = new File(file); if (!fil.exists()) fil.createNewFile(); FileOutputStream s = new FileOutputStream(fil); properties.store(s, ""); } catch (Exception e) { e.printStackTrace(); return false; } return true; } private Properties loadConfig(Context context, String file) { Properties properties = new Properties(); try { FileInputStream s = new FileInputStream(file); properties.load(s); } catch (Exception e) { e.printStackTrace(); return null; } return properties; } private void set_switch_bar() { Properties prop = loadConfig(getApplicationContext(), "/mnt/sdcard/config.properties"); if (prop == null) { // 配置文件不存在的时候创建配置文件 初始化配置信息 prop = new Properties(); prop.put("muted", "true"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } if (prop.get("muted") == null) { prop.put("muted", "true"); } String muted = (String) prop.get("muted"); if (muted.equals("true")) { sw_muted.setChecked(true); } else if (muted.equals("false")) { sw_muted.setChecked(false); } } public void exit_login(View view) { Intent intent = new Intent(this, LoginActivity.class); intent.putExtra("exit", "exit"); startActivity(intent); finish(); } public void onBackPressed() { gotomain(); } private void gotomain() { Intent intent = new Intent(SettingActivity.this, MainActivity.class); if (choice_user == 1) { intent.putExtra("teacherOBJ", teacherOBJ); intent.putExtra("user", "teacher"); } else if (choice_user == 0) { intent.putExtra("studentOBJ", studentOBJ); intent.putExtra("user", "student"); } intent.putExtra("to_person_center", "true"); startActivity(intent); finish(); } }
UTF-8
Java
7,292
java
SettingActivity.java
Java
[]
null
[]
package com.example.hp.iclass.PersonCenter; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.CompoundButton; import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.Toast; import com.example.hp.iclass.CommonActivity.BeginningActivity.Login.LoginActivity; import com.example.hp.iclass.CommonActivity.MainActivity; import com.example.hp.iclass.OBJ.StudentOBJ; import com.example.hp.iclass.OBJ.TeacherOBJ; import com.example.hp.iclass.R; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Properties; public class SettingActivity extends AppCompatActivity { private StudentOBJ studentOBJ = new StudentOBJ(); private TeacherOBJ teacherOBJ = new TeacherOBJ(); private RelativeLayout re_endlogin; private Switch sw_message; private Switch sw_muted; private String user = ""; private int choice_user; private Toolbar tl_head; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); Intent intent = getIntent(); user = (String) intent.getSerializableExtra("user"); if (user.equals("teacher")) { choice_user = 1; teacherOBJ = (TeacherOBJ) intent.getSerializableExtra("teacherOBJ"); } else if (user.equals("student")) { choice_user = 0; studentOBJ = (StudentOBJ) intent.getSerializableExtra("studentOBJ"); } re_endlogin = (RelativeLayout) findViewById(R.id.rl_endlogin); sw_muted = (Switch) findViewById(R.id.sw_muted); sw_message = (Switch) findViewById(R.id.sw_message); tl_head = (Toolbar) findViewById(R.id.tl_head); tl_head.setNavigationIcon(R.drawable.ic_back); tl_head.setTitle(" 设置"); tl_head.setTitleTextColor(Color.WHITE); tl_head.setNavigationIcon(R.drawable.ic_back); setSupportActionBar(tl_head); tl_head.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { gotomain(); } }); set_switch_bar(); sw_muted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (compoundButton.isChecked()) { Properties prop = loadConfig(getApplicationContext(), "/mnt/sdcard/config.properties"); if (prop == null) { // 配置文件不存在的时候创建配置文件 初始化配置信息 prop = new Properties(); prop.put("muted", "true"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } else { prop.put("muted", "true"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } // Toast.makeText(getApplicationContext(), "设置成功 开启", Toast.LENGTH_SHORT).show(); } else { Properties prop = loadConfig(getApplicationContext(), "/mnt/sdcard/config.properties"); if (prop == null) { // 配置文件不存在的时候创建配置文件 初始化配置信息 prop = new Properties(); prop.put("muted", "false"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } else { prop.put("muted", "false"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } // Toast.makeText(getApplicationContext(), "设置成功 关闭", Toast.LENGTH_SHORT).show(); } } }); sw_message.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (compoundButton.isChecked()) { Toast.makeText(getApplicationContext(), "开", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "关", Toast.LENGTH_SHORT).show(); } } }); } public boolean saveConfig(Context context, String file, Properties properties) { try { File fil = new File(file); if (!fil.exists()) fil.createNewFile(); FileOutputStream s = new FileOutputStream(fil); properties.store(s, ""); } catch (Exception e) { e.printStackTrace(); return false; } return true; } private Properties loadConfig(Context context, String file) { Properties properties = new Properties(); try { FileInputStream s = new FileInputStream(file); properties.load(s); } catch (Exception e) { e.printStackTrace(); return null; } return properties; } private void set_switch_bar() { Properties prop = loadConfig(getApplicationContext(), "/mnt/sdcard/config.properties"); if (prop == null) { // 配置文件不存在的时候创建配置文件 初始化配置信息 prop = new Properties(); prop.put("muted", "true"); saveConfig(getApplicationContext(), "/mnt/sdcard/config.properties", prop); } if (prop.get("muted") == null) { prop.put("muted", "true"); } String muted = (String) prop.get("muted"); if (muted.equals("true")) { sw_muted.setChecked(true); } else if (muted.equals("false")) { sw_muted.setChecked(false); } } public void exit_login(View view) { Intent intent = new Intent(this, LoginActivity.class); intent.putExtra("exit", "exit"); startActivity(intent); finish(); } public void onBackPressed() { gotomain(); } private void gotomain() { Intent intent = new Intent(SettingActivity.this, MainActivity.class); if (choice_user == 1) { intent.putExtra("teacherOBJ", teacherOBJ); intent.putExtra("user", "teacher"); } else if (choice_user == 0) { intent.putExtra("studentOBJ", studentOBJ); intent.putExtra("user", "student"); } intent.putExtra("to_person_center", "true"); startActivity(intent); finish(); } }
7,292
0.585088
0.584246
185
37.497299
25.216923
107
false
false
0
0
0
0
0
0
0.794595
false
false
5
fc379196d7b06d964ee9168a8824a883ae59c696
38,543,036,540,871
fac4cdb007450ba84b8bc5ebc995854bbbe6c081
/codingInterview/src/chapter8/Question2.java
cc338164c4fd458c8f4002e808bcd439e0184331
[]
no_license
pikachom/carckingTheCodingInterview
https://github.com/pikachom/carckingTheCodingInterview
e2e8d10be7a03704b01c067a6f5f1fa66808eb06
b6363764f71d35594fb5031563a7b01c0bdbd666
refs/heads/master
2021-06-11T16:31:24.151000
2021-05-29T09:20:34
2021-05-29T09:20:34
186,317,778
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter8; import java.util.ArrayList; import java.util.HashSet; public class Question2 { class Board{ int columns; int rows; ArrayList<Bomb> Bombs = new ArrayList<Bomb>(); Board(int columns, int rows){ this.columns = columns; this.rows = rows; } void addBomb(int bombColumn, int bombRow) { if(this.columns<bombColumn || this.rows<bombRow) { System.out.println("보드규격 바깥에 bomb을 추가할 수 없습니다."); return; } Bomb newBomb = new Bomb(bombColumn, bombRow); this.Bombs.add(newBomb); System.out.println(bombColumn + "," + bombRow + "에 폭탄 장착 완료"); } boolean checkBomb(int column, int row) { for(Bomb bomb : this.Bombs) { if(bomb.column == column && bomb.row == row) { return true; } } return false; } void printBoard() { for(int r=1;r<=this.rows;r++) { StringBuilder sb = new StringBuilder(); for(int c=1;c<=this.columns;c++) { if(checkBomb(c,r)) { sb.append("X"); }else { sb.append("O"); } } System.out.println(sb); } } } class Bomb{ int row; int column; Bomb(int column, int row){ this.column = column; this.row = row; } } class Point{ int row; int column; Point(int column, int row){ this.column = column; this.row = row; } } ArrayList<Point> getPath(Board board){ HashSet<Point> failedPoints = new HashSet<Point>(); ArrayList<Point> path = new ArrayList<Point>(); Point goal = new Point(board.columns,board.rows); if(getPath(board, failedPoints, path, goal)){ for(Point point : path) { int col = point.column; int row = point.row; System.out.print("("+col+" "+row+")"+"->"); } return path; } return null; } boolean getPath(Board board, HashSet<Point> failedPoints, ArrayList<Point> path, Point goal){ int col = goal.column; int row = goal.row; if(col<1 || row<1) { return false; } if(col==1 && row == 1) { path.add(goal); return true; } if(failedPoints.contains(goal)) { return false; } if(board.checkBomb(col, row)) { return false; } Point goalLeft = new Point(col-1, row); Point goalUpper = new Point(col, row-1); if(getPath(board, failedPoints, path, goalLeft)||getPath(board, failedPoints, path, goalUpper)) { path.add(goal); return true; } failedPoints.add(goal); return false; } public static void main(String[] args) { Question2 test = new Question2(); Board board = test.new Board(7,7); board.addBomb(3, 3); board.addBomb(7, 1); board.addBomb(11, 4); board.addBomb(4, 3); board.addBomb(1, 4); board.printBoard(); test.getPath(board); } }
UHC
Java
2,683
java
Question2.java
Java
[]
null
[]
package chapter8; import java.util.ArrayList; import java.util.HashSet; public class Question2 { class Board{ int columns; int rows; ArrayList<Bomb> Bombs = new ArrayList<Bomb>(); Board(int columns, int rows){ this.columns = columns; this.rows = rows; } void addBomb(int bombColumn, int bombRow) { if(this.columns<bombColumn || this.rows<bombRow) { System.out.println("보드규격 바깥에 bomb을 추가할 수 없습니다."); return; } Bomb newBomb = new Bomb(bombColumn, bombRow); this.Bombs.add(newBomb); System.out.println(bombColumn + "," + bombRow + "에 폭탄 장착 완료"); } boolean checkBomb(int column, int row) { for(Bomb bomb : this.Bombs) { if(bomb.column == column && bomb.row == row) { return true; } } return false; } void printBoard() { for(int r=1;r<=this.rows;r++) { StringBuilder sb = new StringBuilder(); for(int c=1;c<=this.columns;c++) { if(checkBomb(c,r)) { sb.append("X"); }else { sb.append("O"); } } System.out.println(sb); } } } class Bomb{ int row; int column; Bomb(int column, int row){ this.column = column; this.row = row; } } class Point{ int row; int column; Point(int column, int row){ this.column = column; this.row = row; } } ArrayList<Point> getPath(Board board){ HashSet<Point> failedPoints = new HashSet<Point>(); ArrayList<Point> path = new ArrayList<Point>(); Point goal = new Point(board.columns,board.rows); if(getPath(board, failedPoints, path, goal)){ for(Point point : path) { int col = point.column; int row = point.row; System.out.print("("+col+" "+row+")"+"->"); } return path; } return null; } boolean getPath(Board board, HashSet<Point> failedPoints, ArrayList<Point> path, Point goal){ int col = goal.column; int row = goal.row; if(col<1 || row<1) { return false; } if(col==1 && row == 1) { path.add(goal); return true; } if(failedPoints.contains(goal)) { return false; } if(board.checkBomb(col, row)) { return false; } Point goalLeft = new Point(col-1, row); Point goalUpper = new Point(col, row-1); if(getPath(board, failedPoints, path, goalLeft)||getPath(board, failedPoints, path, goalUpper)) { path.add(goal); return true; } failedPoints.add(goal); return false; } public static void main(String[] args) { Question2 test = new Question2(); Board board = test.new Board(7,7); board.addBomb(3, 3); board.addBomb(7, 1); board.addBomb(11, 4); board.addBomb(4, 3); board.addBomb(1, 4); board.printBoard(); test.getPath(board); } }
2,683
0.618885
0.609405
119
21.159664
18.394821
102
false
false
0
0
0
0
0
0
3.193277
false
false
5
cea392cd63d71def7ca36a4352401702e4a85af4
35,966,056,182,502
1ce3f42c99ecc8214ddf71feba3edb60c6672559
/app/src/main/java/learn2/program/db/tables/CustomServing.java
7e43aacc3c103d245f5bbc3976f0f1359b716f9b
[]
no_license
Svinqvai/ShapeTransform
https://github.com/Svinqvai/ShapeTransform
9a4c031f7d9e09eb361581748398136fb2e82976
534d8f1bd012e9f496be41597ef43da5e5384934
refs/heads/master
2016-09-07T22:14:08.913000
2016-09-06T16:30:53
2016-09-06T16:30:53
49,432,291
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package learn2.program.db.tables; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import learn2.program.pojos.IServing; import learn2.program.pojos.RecycleItem; @DatabaseTable(tableName = "custom_servings") public class CustomServing implements RecycleItem, IServing { public CustomServing(int id, float amount, String name) { this.id = id; this.amount = amount; this.name = name; } public void setName(String name) { this.name = name; } @DatabaseField(generatedId = true, columnName = "_id", index = true) private int id; @DatabaseField(columnName = "serving_amount") private float amount; @DatabaseField private String name; public CustomServing() {/*default constructor used by ORMLite */} public CustomServing(final String name,final float amount){ this.name = name; this.amount = amount; } public String getName() { return name; } public int getId() { return id; } @Override public boolean isSection() { return false; } public void setId(int id) { this.id = id; } public float getAmount() { return amount; } @Override public String toString() { return name; } }
UTF-8
Java
1,332
java
CustomServing.java
Java
[]
null
[]
package learn2.program.db.tables; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import learn2.program.pojos.IServing; import learn2.program.pojos.RecycleItem; @DatabaseTable(tableName = "custom_servings") public class CustomServing implements RecycleItem, IServing { public CustomServing(int id, float amount, String name) { this.id = id; this.amount = amount; this.name = name; } public void setName(String name) { this.name = name; } @DatabaseField(generatedId = true, columnName = "_id", index = true) private int id; @DatabaseField(columnName = "serving_amount") private float amount; @DatabaseField private String name; public CustomServing() {/*default constructor used by ORMLite */} public CustomServing(final String name,final float amount){ this.name = name; this.amount = amount; } public String getName() { return name; } public int getId() { return id; } @Override public boolean isSection() { return false; } public void setId(int id) { this.id = id; } public float getAmount() { return amount; } @Override public String toString() { return name; } }
1,332
0.632883
0.626126
63
20.126984
19.530596
72
false
false
0
0
0
0
0
0
0.412698
false
false
5
c85458e5ff4ec01e7cab1e7c9624604cd1cd46ee
38,405,597,593,023
2eb23895e8f3edbdc9fcb8ce4a55d857c976dc5a
/ tdil-pq --username subcmd@gmail.com/DJMagWeb/JavaSource/com/tdil/djmag/model/Country.java
d3d1ff2501cd4615ab5731a45f58c032ecfa0654
[]
no_license
rraaff/tdil-pq
https://github.com/rraaff/tdil-pq
66e8c1ba13e6bca9dd7ba7d1dea2df0768bfecdf
7a703f5adecb6b8cb149abc361545bcfd3917225
refs/heads/master
2016-09-06T03:54:46.934000
2015-03-07T01:53:22
2015-03-07T01:53:22
38,350,607
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tdil.djmag.model; import com.tdil.ibatis.PersistentObject; public class Country extends PersistentObject { /** * This field was generated by MyBatis Generator. This field corresponds to the database column COUNTRY.name * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ private String name; /** * This field was generated by MyBatis Generator. This field corresponds to the database column COUNTRY.iso_code_2 * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ private String isoCode2; /** * This method was generated by MyBatis Generator. This method returns the value of the database column COUNTRY.name * @return the value of COUNTRY.name * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column COUNTRY.name * @param name the value for COUNTRY.name * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column COUNTRY.iso_code_2 * @return the value of COUNTRY.iso_code_2 * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public String getIsoCode2() { return isoCode2; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column COUNTRY.iso_code_2 * @param isoCode2 the value for COUNTRY.iso_code_2 * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public void setIsoCode2(String isoCode2) { this.isoCode2 = isoCode2 == null ? null : isoCode2.trim(); } /** Methods **/ @Override public String toString() { return this.getName(); } }
UTF-8
Java
1,790
java
Country.java
Java
[]
null
[]
package com.tdil.djmag.model; import com.tdil.ibatis.PersistentObject; public class Country extends PersistentObject { /** * This field was generated by MyBatis Generator. This field corresponds to the database column COUNTRY.name * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ private String name; /** * This field was generated by MyBatis Generator. This field corresponds to the database column COUNTRY.iso_code_2 * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ private String isoCode2; /** * This method was generated by MyBatis Generator. This method returns the value of the database column COUNTRY.name * @return the value of COUNTRY.name * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column COUNTRY.name * @param name the value for COUNTRY.name * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column COUNTRY.iso_code_2 * @return the value of COUNTRY.iso_code_2 * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public String getIsoCode2() { return isoCode2; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column COUNTRY.iso_code_2 * @param isoCode2 the value for COUNTRY.iso_code_2 * @mbggenerated Tue Jun 19 18:08:48 ART 2012 */ public void setIsoCode2(String isoCode2) { this.isoCode2 = isoCode2 == null ? null : isoCode2.trim(); } /** Methods **/ @Override public String toString() { return this.getName(); } }
1,790
0.712849
0.664804
60
28.85
34.481312
123
false
false
0
0
0
0
0
0
1.033333
false
false
5
3da470843177238358455961231aa110043a00c5
17,643,725,686,143
1e755b7b3bb9d84715f3f2919a3683371bf28956
/granmercado/src/main/java/pe/com/granmercado/dao/ProductoDAOImpl.java
fe75d3f5be0effc52dfcb0b3de2a9645860816cb
[]
no_license
djaimes610/APEGA
https://github.com/djaimes610/APEGA
c3fb637d1c07181b3696fa251dadb9d519483274
4994845c3cc1985c424b957846a894b486960041
refs/heads/master
2021-01-13T00:15:51.349000
2015-11-11T09:22:13
2015-11-11T09:22:13
45,328,894
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.com.granmercado.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.springframework.stereotype.Repository; import pe.com.granmercado.model.Producto; @Repository("productoDao") public class ProductoDAOImpl extends AbstractDao implements ProductoDAO { @SuppressWarnings("unchecked") public List<Producto> getAll() { Criteria criteria = getSession().createCriteria(Producto.class); try { return (List<Producto>) criteria.list(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("error "+e.getMessage()); e.printStackTrace(); } return null; } }
UTF-8
Java
716
java
ProductoDAOImpl.java
Java
[]
null
[]
package pe.com.granmercado.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.springframework.stereotype.Repository; import pe.com.granmercado.model.Producto; @Repository("productoDao") public class ProductoDAOImpl extends AbstractDao implements ProductoDAO { @SuppressWarnings("unchecked") public List<Producto> getAll() { Criteria criteria = getSession().createCriteria(Producto.class); try { return (List<Producto>) criteria.list(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("error "+e.getMessage()); e.printStackTrace(); } return null; } }
716
0.706704
0.706704
27
24.518518
20.920256
73
false
false
0
0
0
0
0
0
1.518519
false
false
5
3c485e5638bd0eab487fc3bd65d73f254529f027
4,853,313,078,384
eefbe932119c00d0192e8a465c439f8f75c9bad5
/core/src/com/comp460/screens/tactics/systems/map/MapToScreenSystem.java
8117a2b359a81662b83d2d6b721aa807e8bd7c7e
[]
no_license
mbh95/tactics460
https://github.com/mbh95/tactics460
e68102e0fdfa08502c48c49c1a5834fbbba53922
8e0418a5835007e9ec867e4f7a26bb8299766cd1
refs/heads/master
2021-01-11T21:34:21.820000
2017-04-24T00:22:48
2017-04-24T00:22:48
78,811,105
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.comp460.screens.tactics.systems.map; import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.badlogic.gdx.math.Vector3; import com.comp460.screens.tactics.TacticsScreen; import com.comp460.screens.tactics.components.map.MapPositionComponent; import com.comp460.common.components.ChildComponent; import com.comp460.common.components.TransformComponent; /** * For each entity with both a map position and a transform which is not already tied to a parent entity */ public class MapToScreenSystem extends IteratingSystem { private static final Family trackingToMapFamily = Family.all(MapPositionComponent.class, TransformComponent.class).exclude(ChildComponent.class).get(); private static final ComponentMapper<MapPositionComponent> mapPosM = ComponentMapper.getFor(MapPositionComponent.class); private static final ComponentMapper<TransformComponent> transformM = ComponentMapper.getFor(TransformComponent.class); private TacticsScreen parentScreen; public MapToScreenSystem(TacticsScreen tacticsScreen, int priority) { super(trackingToMapFamily, priority); this.parentScreen = tacticsScreen; } @Override protected void processEntity(Entity entity, float deltaTime) { TransformComponent transform = transformM.get(entity); transform.pos.lerp(goal(entity), 0.3f); } public boolean isDone(Entity entity, float epsilon) { TransformComponent transform = transformM.get(entity); return goal(entity).epsilonEquals(transform.pos, epsilon); } public Vector3 goal(Entity entity) { TransformComponent transform = transformM.get(entity); MapPositionComponent mapPos = mapPosM.get(entity); return new Vector3(mapPos.col * parentScreen.getMap().getTileWidth(), mapPos.row * parentScreen.getMap().getTileHeight(), transform.pos.z); } }
UTF-8
Java
2,005
java
MapToScreenSystem.java
Java
[]
null
[]
package com.comp460.screens.tactics.systems.map; import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.badlogic.gdx.math.Vector3; import com.comp460.screens.tactics.TacticsScreen; import com.comp460.screens.tactics.components.map.MapPositionComponent; import com.comp460.common.components.ChildComponent; import com.comp460.common.components.TransformComponent; /** * For each entity with both a map position and a transform which is not already tied to a parent entity */ public class MapToScreenSystem extends IteratingSystem { private static final Family trackingToMapFamily = Family.all(MapPositionComponent.class, TransformComponent.class).exclude(ChildComponent.class).get(); private static final ComponentMapper<MapPositionComponent> mapPosM = ComponentMapper.getFor(MapPositionComponent.class); private static final ComponentMapper<TransformComponent> transformM = ComponentMapper.getFor(TransformComponent.class); private TacticsScreen parentScreen; public MapToScreenSystem(TacticsScreen tacticsScreen, int priority) { super(trackingToMapFamily, priority); this.parentScreen = tacticsScreen; } @Override protected void processEntity(Entity entity, float deltaTime) { TransformComponent transform = transformM.get(entity); transform.pos.lerp(goal(entity), 0.3f); } public boolean isDone(Entity entity, float epsilon) { TransformComponent transform = transformM.get(entity); return goal(entity).epsilonEquals(transform.pos, epsilon); } public Vector3 goal(Entity entity) { TransformComponent transform = transformM.get(entity); MapPositionComponent mapPos = mapPosM.get(entity); return new Vector3(mapPos.col * parentScreen.getMap().getTileWidth(), mapPos.row * parentScreen.getMap().getTileHeight(), transform.pos.z); } }
2,005
0.772569
0.762594
46
42.586956
39.960075
155
false
false
0
0
0
0
0
0
0.695652
false
false
5
e2660cb3279789d17b3fee0183060e963fc5f41d
4,518,305,627,578
8f696ca4f866557b98337796e7d764b1c2bf9f25
/src/main/java/edu/isi/karma/er/test/old/ConstructPairPropertyMap.java
095d600e4b6ecf1f9fd5765080d5a0a3d9d4052a
[]
no_license
djogopatrao/Web-Karma-Public
https://github.com/djogopatrao/Web-Karma-Public
abfdaf4bd4fe9d3969b3f3d1165f2becd02b780c
f195ac2d71ab2a116155e51769dc39723a8981c4
refs/heads/master
2020-04-08T01:41:20.047000
2013-07-24T13:46:39
2013-07-24T13:46:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.isi.karma.er.test.old; import java.util.Map; import org.json.JSONException; import edu.isi.karma.er.helper.PairPropertyUtil; public class ConstructPairPropertyMap { /** * @param args */ public static void main(String[] args) { //Model srcModel = TDBFactory.createDataset(Constants.PATH_REPOSITORY + "dbpedia/").getDefaultModel(); // Model dstModel = TDBFactory.createDataset(Constants.PATH_REPOSITORY + "dbpedia_a/").getDefaultModel(); //String p1 = "http://americanart.si.edu/saam/birthYear"; //String p2 = "http://americanart.si.edu/saam/deathYear"; PairPropertyUtil util = new PairPropertyUtil(); //Map<String, Map<String, Double>> map = configPairMap(srcModel, p1, p2); Map<String, Map<String, Double>> map = util.loadPairFreqMap(); try { output(map); //output2File(map); } catch (JSONException e) { e.printStackTrace(); } } /* private static Map<String, Map<String, Double>> configPairMap( Model model, String p1, String p2) { Map<String, Map<String, Double>> map = new TreeMap<String, Map<String, Double>>(); List<SaamPerson> list = loadOntologies(model); int len = list.size(); int i = 0; PersonProperty pro1, pro2; for (SaamPerson s : list) { i ++; pro1 = s.getProperty(p1); pro2 = s.getProperty(p2); boolean p1Notnull = (pro1 != null && pro1.getValue() != null); boolean p2Notnull = (pro2 != null && pro2.getValue() != null); Map<String, Double> subMap = null; if (p1Notnull && p2Notnull) { String s1 = pro1.getValue().get(0); String s2 = pro2.getValue().get(0); if (!isParsable(s1) || !isParsable(s2)) continue; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Double>(); } Double count = subMap.get(s2); if (count == null) count = 0d; count += 1.0 / len; subMap.put(s2, count.doubleValue()); map.put(s1, subMap); } else { /* if (p1Notnull) { String s1 = pro1.getValue().get(0); if (!isParsable(s1)) continue; String s2 = "__EMPTY2__"; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Integer>(); } Integer total = subMap.get(s2); if (total == null) { total = 0; } total ++; subMap.put(s2, total); map.put(s1, subMap); } else if (p2Notnull){ String s1 = "__EMPTY1__"; String s2 = pro2.getValue().get(0); if (!isParsable(s2)) continue; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Integer>(); } Integer count = subMap.get(s2); if (count == null) count = 0; count ++; subMap.put(s2, count); map.put(s1, subMap); } else { String s1 = "__EMPTY1__"; String s2 = "__EMPTY2__"; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Integer>(); } Integer count = subMap.get(s2); if (count == null) count = 0; count ++; subMap.put(s2, count); map.put(s1, subMap); }* / } } System.out.println(i + " rows processed."); return map; } */ private static void output(Map<String, Map<String, Double>> map) throws JSONException { int total = 0, subTotal = 0; for (String str : map.keySet()) { System.out.print(str + ":"); subTotal = 0; Map<String, Double>subMap = map.get(str); for (String s2 : subMap.keySet()) { System.out.print("\t" + s2 + ":" + subMap.get(s2)); subTotal += subMap.get(s2); } total += subTotal; System.out.print(subTotal + "\n"); } System.out.println("total:" + total); } /* private static void output2File( Map<String, Map<String, Double>> map) throws JSONException { double total = 0, subTotal = 0; DecimalFormat df = new DecimalFormat("0.0000000"); JSONArray arr = new JSONArray(); for (String str : map.keySet()) { JSONObject obj = new JSONObject(); JSONArray subArr = new JSONArray(); System.out.print(str + ":"); subTotal = 0; Map<String, Double>subMap = map.get(str); for (String s2 : subMap.keySet()) { JSONObject subObj = new JSONObject(); //System.out.print("\t" + s2 + ":" + subMap.get(s2)); subTotal += subMap.get(s2); subObj.put(s2, df.format(subMap.get(s2))); subArr.put(subObj); } obj.put(str, subArr); arr.put(obj); total += subTotal; System.out.print(df.format(subTotal) + "\n"); } System.out.println("total:" + df.format(total)); File file = new File(Constants.PATH_RATIO_FILE + "birthYear_deathYear.json"); if (file.exists()) file.delete(); RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rw"); raf.writeBytes(arr.toString(2)); } catch (IOException e) { e.printStackTrace(); } } */ /* private static List<SaamPerson> loadOntologies(Model model) { String RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; // property to retrieve all the subjects from models. Property RDF = ResourceFactory.createProperty(RDF_TYPE); ResIterator iter = model.listSubjectsWithProperty(RDF); List<SaamPerson> list = new Vector<SaamPerson>(); while (iter.hasNext()) { Resource res = iter.next(); StmtIterator siter = res.listProperties(); SaamPerson per = new SaamPerson(); per.setSubject(res.getURI()); while (siter.hasNext()) { Statement st = siter.next(); String pred = st.getPredicate().getURI(); RDFNode node = st.getObject(); PersonProperty p = new PersonProperty(); p.setPredicate(pred); if (node != null) { if (pred.indexOf("fullName") > -1) { p.setValue(node.asLiteral().getString()); per.setFullName(p); } else if (pred.indexOf("birthYear") > -1) { p.setValue(node.asLiteral().getString()); per.setBirthYear(p); } else if (pred.indexOf("deathYear") > -1) { p.setValue(node.asLiteral().getString()); per.setDeathYear(p); } } } list.add(per); } return list; } */ /* private static boolean isParsable(String str) { if (str == null || "" == str) { return false; } char[] ch = str.toCharArray(); int i; for (i = 0; i < ch.length; i++) { if (ch[i] > '9' || ch[i] < '0') { break; } } if (i >= ch.length) return true; else return false; } */ }
UTF-8
Java
6,332
java
ConstructPairPropertyMap.java
Java
[]
null
[]
package edu.isi.karma.er.test.old; import java.util.Map; import org.json.JSONException; import edu.isi.karma.er.helper.PairPropertyUtil; public class ConstructPairPropertyMap { /** * @param args */ public static void main(String[] args) { //Model srcModel = TDBFactory.createDataset(Constants.PATH_REPOSITORY + "dbpedia/").getDefaultModel(); // Model dstModel = TDBFactory.createDataset(Constants.PATH_REPOSITORY + "dbpedia_a/").getDefaultModel(); //String p1 = "http://americanart.si.edu/saam/birthYear"; //String p2 = "http://americanart.si.edu/saam/deathYear"; PairPropertyUtil util = new PairPropertyUtil(); //Map<String, Map<String, Double>> map = configPairMap(srcModel, p1, p2); Map<String, Map<String, Double>> map = util.loadPairFreqMap(); try { output(map); //output2File(map); } catch (JSONException e) { e.printStackTrace(); } } /* private static Map<String, Map<String, Double>> configPairMap( Model model, String p1, String p2) { Map<String, Map<String, Double>> map = new TreeMap<String, Map<String, Double>>(); List<SaamPerson> list = loadOntologies(model); int len = list.size(); int i = 0; PersonProperty pro1, pro2; for (SaamPerson s : list) { i ++; pro1 = s.getProperty(p1); pro2 = s.getProperty(p2); boolean p1Notnull = (pro1 != null && pro1.getValue() != null); boolean p2Notnull = (pro2 != null && pro2.getValue() != null); Map<String, Double> subMap = null; if (p1Notnull && p2Notnull) { String s1 = pro1.getValue().get(0); String s2 = pro2.getValue().get(0); if (!isParsable(s1) || !isParsable(s2)) continue; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Double>(); } Double count = subMap.get(s2); if (count == null) count = 0d; count += 1.0 / len; subMap.put(s2, count.doubleValue()); map.put(s1, subMap); } else { /* if (p1Notnull) { String s1 = pro1.getValue().get(0); if (!isParsable(s1)) continue; String s2 = "__EMPTY2__"; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Integer>(); } Integer total = subMap.get(s2); if (total == null) { total = 0; } total ++; subMap.put(s2, total); map.put(s1, subMap); } else if (p2Notnull){ String s1 = "__EMPTY1__"; String s2 = pro2.getValue().get(0); if (!isParsable(s2)) continue; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Integer>(); } Integer count = subMap.get(s2); if (count == null) count = 0; count ++; subMap.put(s2, count); map.put(s1, subMap); } else { String s1 = "__EMPTY1__"; String s2 = "__EMPTY2__"; subMap = map.get(s1); if (subMap == null) { subMap = new TreeMap<String, Integer>(); } Integer count = subMap.get(s2); if (count == null) count = 0; count ++; subMap.put(s2, count); map.put(s1, subMap); }* / } } System.out.println(i + " rows processed."); return map; } */ private static void output(Map<String, Map<String, Double>> map) throws JSONException { int total = 0, subTotal = 0; for (String str : map.keySet()) { System.out.print(str + ":"); subTotal = 0; Map<String, Double>subMap = map.get(str); for (String s2 : subMap.keySet()) { System.out.print("\t" + s2 + ":" + subMap.get(s2)); subTotal += subMap.get(s2); } total += subTotal; System.out.print(subTotal + "\n"); } System.out.println("total:" + total); } /* private static void output2File( Map<String, Map<String, Double>> map) throws JSONException { double total = 0, subTotal = 0; DecimalFormat df = new DecimalFormat("0.0000000"); JSONArray arr = new JSONArray(); for (String str : map.keySet()) { JSONObject obj = new JSONObject(); JSONArray subArr = new JSONArray(); System.out.print(str + ":"); subTotal = 0; Map<String, Double>subMap = map.get(str); for (String s2 : subMap.keySet()) { JSONObject subObj = new JSONObject(); //System.out.print("\t" + s2 + ":" + subMap.get(s2)); subTotal += subMap.get(s2); subObj.put(s2, df.format(subMap.get(s2))); subArr.put(subObj); } obj.put(str, subArr); arr.put(obj); total += subTotal; System.out.print(df.format(subTotal) + "\n"); } System.out.println("total:" + df.format(total)); File file = new File(Constants.PATH_RATIO_FILE + "birthYear_deathYear.json"); if (file.exists()) file.delete(); RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rw"); raf.writeBytes(arr.toString(2)); } catch (IOException e) { e.printStackTrace(); } } */ /* private static List<SaamPerson> loadOntologies(Model model) { String RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; // property to retrieve all the subjects from models. Property RDF = ResourceFactory.createProperty(RDF_TYPE); ResIterator iter = model.listSubjectsWithProperty(RDF); List<SaamPerson> list = new Vector<SaamPerson>(); while (iter.hasNext()) { Resource res = iter.next(); StmtIterator siter = res.listProperties(); SaamPerson per = new SaamPerson(); per.setSubject(res.getURI()); while (siter.hasNext()) { Statement st = siter.next(); String pred = st.getPredicate().getURI(); RDFNode node = st.getObject(); PersonProperty p = new PersonProperty(); p.setPredicate(pred); if (node != null) { if (pred.indexOf("fullName") > -1) { p.setValue(node.asLiteral().getString()); per.setFullName(p); } else if (pred.indexOf("birthYear") > -1) { p.setValue(node.asLiteral().getString()); per.setBirthYear(p); } else if (pred.indexOf("deathYear") > -1) { p.setValue(node.asLiteral().getString()); per.setDeathYear(p); } } } list.add(per); } return list; } */ /* private static boolean isParsable(String str) { if (str == null || "" == str) { return false; } char[] ch = str.toCharArray(); int i; for (i = 0; i < ch.length; i++) { if (ch[i] > '9' || ch[i] < '0') { break; } } if (i >= ch.length) return true; else return false; } */ }
6,332
0.601074
0.583544
234
26.05983
20.990755
124
false
false
0
0
0
0
0
0
3.777778
false
false
5
73d47e82c6e85a1eda64d9acd705fa3b1921a281
30,872,224,949,383
14d4d72b2cb877bf43415720c683820d10148681
/src/main/java/com/brothersplant/persistence/LikeGoodDAO.java
0e5be0e16315fd1f5caf278a20d8ab285b1bd22d
[]
no_license
mkChung924/SpringProject
https://github.com/mkChung924/SpringProject
5b8938a7bcf5e31a061cb2fec7a9455d5daeafc1
00eba818101df9d66082c94baed2a75098236f26
refs/heads/master
2020-12-03T00:40:02.461000
2017-07-05T10:37:08
2017-07-05T10:37:08
96,056,369
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.brothersplant.persistence; public interface LikeGoodDAO { public int selectLike(String id, int tbno) throws Exception; public void addLike(String id, int tbno) throws Exception; public int removeLike(String id, int tbno) throws Exception; public int selectTotLike(int tbno) throws Exception; }
UTF-8
Java
325
java
LikeGoodDAO.java
Java
[]
null
[]
package com.brothersplant.persistence; public interface LikeGoodDAO { public int selectLike(String id, int tbno) throws Exception; public void addLike(String id, int tbno) throws Exception; public int removeLike(String id, int tbno) throws Exception; public int selectTotLike(int tbno) throws Exception; }
325
0.766154
0.766154
10
30.5
26.031712
61
false
false
0
0
0
0
0
0
1.4
false
false
5