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
fe66501efffc9c1b69efcc5fbf50ac9355b3ca82
9,225,589,784,078
790e87b5ec44002582f5f349fb612c99355b4e4a
/shop-api-entity-api/shop-service-api-weixin-entity/src/main/java/com/xintao/entity/AppEntity.java
5a38e36ee66da109feabca4419fb71477b82b197
[]
no_license
CocoFresh/shop
https://github.com/CocoFresh/shop
b37a95cddfc76c721007cb302bad3800ca06450c
3bb42eef4abde24609f81302d0578297aa253b7d
refs/heads/master
2022-12-12T07:09:56.647000
2019-11-08T06:28:13
2019-11-08T06:28:13
220,401,326
0
0
null
false
2022-12-06T00:33:23
2019-11-08T06:27:08
2019-11-08T06:29:21
2022-12-06T00:33:22
22
0
0
2
Java
false
false
package com.xintao.entity; import lombok.Data; /** * @Auther: xintao.feng * @Date: 2019/11/8 10:05 * @Description: */ @Data public class AppEntity { private String appId; private String appName; public AppEntity(String appId, String appName) { super(); this.appId = appId; this.appName = appName; } }
UTF-8
Java
350
java
AppEntity.java
Java
[ { "context": "ntao.entity;\n\nimport lombok.Data;\n\n/**\n * @Auther: xintao.feng\n * @Date: 2019/11/8 10:05\n * @Descripti", "end": 66, "score": 0.6399206519126892, "start": 65, "tag": "NAME", "value": "x" }, { "context": "ao.entity;\n\nimport lombok.Data;\n\n/**\n * @Auther: xintao.feng\n * @Date: 2019/11/8 10:05\n * @Description:\n */\n@D", "end": 76, "score": 0.846216082572937, "start": 66, "tag": "USERNAME", "value": "intao.feng" } ]
null
[]
package com.xintao.entity; import lombok.Data; /** * @Auther: xintao.feng * @Date: 2019/11/8 10:05 * @Description: */ @Data public class AppEntity { private String appId; private String appName; public AppEntity(String appId, String appName) { super(); this.appId = appId; this.appName = appName; } }
350
0.622857
0.591429
22
14.909091
13.826552
52
false
false
0
0
0
0
0
0
0.363636
false
false
9
43e622b5afb4e9149fb8d6a44274fd6daac10bc5
38,388,417,719,368
471e753918de61e81061448623401d09d0bbb690
/src/e/commerce/ShowingOptions.java
12bafaf13a5734a531473f4ad73af58bfbc92f9b
[]
no_license
nehadubey20/E-commerce
https://github.com/nehadubey20/E-commerce
fb5e297e46366be0687bab2fa71b185b314ee745
0338a93504aa585a32ce14d494be97062d5262fb
refs/heads/main
2023-05-27T01:12:05.428000
2021-06-23T19:23:12
2021-06-23T19:23:12
364,298,864
0
0
null
false
2021-06-22T06:24:04
2021-05-04T15:17:52
2021-06-22T04:39:40
2021-06-22T06:24:02
63
0
0
0
Java
false
false
/* * 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 e.commerce; import java.sql.SQLException; import java.util.Scanner; /** * * @author NEHA */ public class ShowingOptions { public void showOption() throws SQLException{ int choice; AddToCart atc = new AddToCart(); Browse br = new Browse(); Login login = new Login(); User usr = new User(); UserAccount uac = new UserAccount(); Scanner sc=new Scanner(System.in); System.out.println("-----------Welcome to E-CART----------"); while(true) { System.out.println("1. Login"); System.out.println("2. New user?? Register"); System.out.println("3. Browse"); System.out.println("5. Cart"); System.out.println("4. Quit"); choice=sc.nextInt(); switch(choice) { case 1: usr.login(); if(Login.login()) { System.out.println("User Login Successfully!"); boolean isLoggedIn=true; while(true) { System.out.println("01. Browse"); System.out.println("02. Add to Cart"); System.out.println("03. User Details"); System.out.println("04. Edit User Details"); System.out.println("05. View Cart"); System.out.println("06. Checkout"); System.out.println("07. Exit"); System.out.println("Enter your choice:"); int ch2=sc.nextInt(); switch(ch2) { case 1: br.browse(); System.out.println("Enter your choice:"); int ch3=sc.nextInt(); br.browseProducts(ch3); break; case 2:;break; case 3:uac.viewProfile();break; case 4:uac.editProfile();break; case 5:;break; case 6: ;break; case 7: System.exit(0) ; default: System.out.println("Enter a valid choice!"); } } } else { System.out.println("Invalid Id or Password"); } break; case 2:usr.register(); Register.register() ; break; case 3:br.browse() ; System.out.println("Enter your choice:"); int ch3=sc.nextInt(); br.browseProducts(ch3); break; case 4:System.exit(0) ; case 5: /*System.out.println("1.Show Products\n2.Display Total"); int ch9; ch9=sc.nextInt(); switch(ch9) { case 1: br.show(); break; case 2: br.Total(); }*/ break; default: System.out.println("Enter a valid choice!"); } } } }
UTF-8
Java
4,793
java
ShowingOptions.java
Java
[ { "context": "tion;\nimport java.util.Scanner;\n\n/**\n *\n * @author NEHA\n */\npublic class ShowingOptions {\n \n public", "end": 285, "score": 0.7108452320098877, "start": 281, "tag": "USERNAME", "value": "NEHA" } ]
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 e.commerce; import java.sql.SQLException; import java.util.Scanner; /** * * @author NEHA */ public class ShowingOptions { public void showOption() throws SQLException{ int choice; AddToCart atc = new AddToCart(); Browse br = new Browse(); Login login = new Login(); User usr = new User(); UserAccount uac = new UserAccount(); Scanner sc=new Scanner(System.in); System.out.println("-----------Welcome to E-CART----------"); while(true) { System.out.println("1. Login"); System.out.println("2. New user?? Register"); System.out.println("3. Browse"); System.out.println("5. Cart"); System.out.println("4. Quit"); choice=sc.nextInt(); switch(choice) { case 1: usr.login(); if(Login.login()) { System.out.println("User Login Successfully!"); boolean isLoggedIn=true; while(true) { System.out.println("01. Browse"); System.out.println("02. Add to Cart"); System.out.println("03. User Details"); System.out.println("04. Edit User Details"); System.out.println("05. View Cart"); System.out.println("06. Checkout"); System.out.println("07. Exit"); System.out.println("Enter your choice:"); int ch2=sc.nextInt(); switch(ch2) { case 1: br.browse(); System.out.println("Enter your choice:"); int ch3=sc.nextInt(); br.browseProducts(ch3); break; case 2:;break; case 3:uac.viewProfile();break; case 4:uac.editProfile();break; case 5:;break; case 6: ;break; case 7: System.exit(0) ; default: System.out.println("Enter a valid choice!"); } } } else { System.out.println("Invalid Id or Password"); } break; case 2:usr.register(); Register.register() ; break; case 3:br.browse() ; System.out.println("Enter your choice:"); int ch3=sc.nextInt(); br.browseProducts(ch3); break; case 4:System.exit(0) ; case 5: /*System.out.println("1.Show Products\n2.Display Total"); int ch9; ch9=sc.nextInt(); switch(ch9) { case 1: br.show(); break; case 2: br.Total(); }*/ break; default: System.out.println("Enter a valid choice!"); } } } }
4,793
0.307323
0.297726
119
39.285713
23.19198
94
false
false
0
0
0
0
0
0
0.983193
false
false
15
b304aff04976af86a0aa649ebb97db616c990975
6,777,458,457,396
9d4a597411463455ab0e8b933d663e27828168d8
/src/main/java/de/dhbw/vs/client/ClientTCP.java
21ad3f28378f58d322f4738dd6d343877189fe14
[]
no_license
shembull/verteilte-systeme
https://github.com/shembull/verteilte-systeme
6f1ed8398862d2338c8e3f4dd1bee3a1e1f4db9f
703e0d4b173a7c2afbfba9cee88878de2791027b
refs/heads/master
2020-05-26T14:28:40.546000
2019-06-07T14:35:09
2019-06-07T14:35:09
188,264,357
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.dhbw.vs.client; import java.io.*; import java.net.InetAddress; import java.net.Socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.dhbw.vs.utils.logging.LogLevel; import de.dhbw.vs.utils.logging.Logging; public class ClientTCP { private Socket socket; private Logger log; private int port; private InetAddress inetAddress; static { Logging.setLoggingDefaults(LogLevel.DEBUG, "[%-5p; %c{1}::%M] %m%n"); } public ClientTCP(int port, InetAddress inetAddress) throws IOException { this.log = LoggerFactory.getLogger(ClientTCP.class); this.port = port; this.inetAddress = inetAddress; this.socket = new Socket(this.inetAddress, this.port); } public void send(String data) throws IOException { if (this.socket.isClosed()){ this.socket = new Socket(this.inetAddress, this.port); } //log.debug("Creating writer"); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( this.socket.getOutputStream() ) ); //log.debug("Writer created"); //log.debug("Writing data..."); writer.write(data); //log.debug("Data written"); //log.debug("Flushing writer..."); writer.flush(); //log.debug("Writer flushed"); this.socket.shutdownOutput(); BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); //log.debug("Start reading data"); while (reader.read() > -1){ //log.debug(Integer.toString(reader.read())); log.info(reader.readLine()); } this.socket.close(); } }
UTF-8
Java
1,756
java
ClientTCP.java
Java
[]
null
[]
package de.dhbw.vs.client; import java.io.*; import java.net.InetAddress; import java.net.Socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.dhbw.vs.utils.logging.LogLevel; import de.dhbw.vs.utils.logging.Logging; public class ClientTCP { private Socket socket; private Logger log; private int port; private InetAddress inetAddress; static { Logging.setLoggingDefaults(LogLevel.DEBUG, "[%-5p; %c{1}::%M] %m%n"); } public ClientTCP(int port, InetAddress inetAddress) throws IOException { this.log = LoggerFactory.getLogger(ClientTCP.class); this.port = port; this.inetAddress = inetAddress; this.socket = new Socket(this.inetAddress, this.port); } public void send(String data) throws IOException { if (this.socket.isClosed()){ this.socket = new Socket(this.inetAddress, this.port); } //log.debug("Creating writer"); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( this.socket.getOutputStream() ) ); //log.debug("Writer created"); //log.debug("Writing data..."); writer.write(data); //log.debug("Data written"); //log.debug("Flushing writer..."); writer.flush(); //log.debug("Writer flushed"); this.socket.shutdownOutput(); BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); //log.debug("Start reading data"); while (reader.read() > -1){ //log.debug(Integer.toString(reader.read())); log.info(reader.readLine()); } this.socket.close(); } }
1,756
0.611048
0.6082
60
28.266666
22.837736
104
false
false
0
0
0
0
0
0
0.633333
false
false
15
bce32d356e62835488c8e1d66fa5069e3190ed6f
19,524,921,335,447
13b6664d92b7e0d73224152413db00dfea18e592
/app/src/main/java/project/own/hashratemonitor/WorkService.java
0ff7ce597a33af0b7524530bea4dd1bfa8e254a1
[ "MIT" ]
permissive
zychmarius/hashrate_monitor
https://github.com/zychmarius/hashrate_monitor
fbdbe7bc397c513f7563842816fc2d27bb2ebb85
52492af49fa91f519da382d10655d0a93ac4b8cb
refs/heads/master
2020-03-23T05:04:09.222000
2018-11-11T19:06:12
2018-11-11T19:06:12
141,122,894
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.own.hashratemonitor; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.util.Log; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Timer; import java.util.TimerTask; public class WorkService extends Service { public static final String HASHRATE_SEND = "hashrateValueSend"; public static final String HASHRATE_VALUE = "hashrateValueMessage"; public static final String ETH_ADDRESS = "https://ethereum.miningpoolhub.com/index.php?page=api&action=getuserhashrate"; private final IBinder binder = new MyBinder(); private Timer timer; private TimerTask timerTask; private Integer hashrateAlarmValue; private String adsressHTTP; private class MyTimerTask extends TimerTask { @Override public void run() { webStart(); } } public void testNotification(Integer actualHashrate) { if (actualHashrate != null && actualHashrate < hashrateAlarmValue) { createNotification(); } } public class MyBinder extends Binder { WorkService getworkService() { return WorkService.this; } } @Nullable @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { super.onCreate(); SharedPreferences preferences = getSharedPreferences(Settings.SETTINGS, MODE_PRIVATE); hashrateAlarmValue = Integer.valueOf(preferences.getString(Settings.HASHRATE_ALARM_VALUE, "0")); adsressHTTP = ETH_ADDRESS + "&api_key=" + preferences.getString(Settings.ETHEREUM_APIKEY, "") + "&id=" + preferences.getString(Settings.USER_ID, ""); timer = new Timer(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { clearTimerSchedule(); initTask(); timer.scheduleAtFixedRate(timerTask, 0, 60 * 1000); return super.onStartCommand(intent, flags, startId); } private void clearTimerSchedule() { if (timerTask != null) { timerTask.cancel(); timer.purge(); } } private void initTask() { timerTask = new MyTimerTask(); } @Override public void onDestroy() { clearTimerSchedule(); super.onDestroy(); } public void webStart() { new WebServicesHandler() .execute(adsressHTTP); } private void createNotification() { Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "default") .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("Low Hashrate") .setContentText("Low hasrate") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSound(uri) .setVibrate(new long[]{10, 500}); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); } private void sendHashrateBroadcast(String hashrateValue) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(HASHRATE_SEND); broadcastIntent.putExtra(HASHRATE_VALUE, hashrateValue); sendBroadcast(broadcastIntent); } private class WebServicesHandler extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { } @Override protected String doInBackground(String... urls) { try { URL url = new URL(urls[0]); URLConnection connection = url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); return streamToString(in); } catch (Exception e) { Log.d(MainActivity.class.getSimpleName(), e.toString()); return null; } } @Override protected void onPostExecute(String result) { try { JSONObject json = new JSONObject(result); JSONObject getuserhashrate = json.getJSONObject("getuserhashrate"); String hashrate = getuserhashrate.getString("data"); Double value = Double.valueOf(hashrate); Integer integer = value.intValue() / 1000; sendHashrateBroadcast(String.valueOf(integer)); testNotification(integer); } catch (Exception e) { Log.d(MainActivity.class.getSimpleName(), e.toString()); } } } public static String streamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder stringBuilder = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } reader.close(); } catch (IOException e) { Log.d(MainActivity.class.getSimpleName(), e.toString()); } return stringBuilder.toString(); } }
UTF-8
Java
5,921
java
WorkService.java
Java
[]
null
[]
package project.own.hashratemonitor; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.util.Log; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Timer; import java.util.TimerTask; public class WorkService extends Service { public static final String HASHRATE_SEND = "hashrateValueSend"; public static final String HASHRATE_VALUE = "hashrateValueMessage"; public static final String ETH_ADDRESS = "https://ethereum.miningpoolhub.com/index.php?page=api&action=getuserhashrate"; private final IBinder binder = new MyBinder(); private Timer timer; private TimerTask timerTask; private Integer hashrateAlarmValue; private String adsressHTTP; private class MyTimerTask extends TimerTask { @Override public void run() { webStart(); } } public void testNotification(Integer actualHashrate) { if (actualHashrate != null && actualHashrate < hashrateAlarmValue) { createNotification(); } } public class MyBinder extends Binder { WorkService getworkService() { return WorkService.this; } } @Nullable @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { super.onCreate(); SharedPreferences preferences = getSharedPreferences(Settings.SETTINGS, MODE_PRIVATE); hashrateAlarmValue = Integer.valueOf(preferences.getString(Settings.HASHRATE_ALARM_VALUE, "0")); adsressHTTP = ETH_ADDRESS + "&api_key=" + preferences.getString(Settings.ETHEREUM_APIKEY, "") + "&id=" + preferences.getString(Settings.USER_ID, ""); timer = new Timer(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { clearTimerSchedule(); initTask(); timer.scheduleAtFixedRate(timerTask, 0, 60 * 1000); return super.onStartCommand(intent, flags, startId); } private void clearTimerSchedule() { if (timerTask != null) { timerTask.cancel(); timer.purge(); } } private void initTask() { timerTask = new MyTimerTask(); } @Override public void onDestroy() { clearTimerSchedule(); super.onDestroy(); } public void webStart() { new WebServicesHandler() .execute(adsressHTTP); } private void createNotification() { Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "default") .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("Low Hashrate") .setContentText("Low hasrate") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSound(uri) .setVibrate(new long[]{10, 500}); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); } private void sendHashrateBroadcast(String hashrateValue) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(HASHRATE_SEND); broadcastIntent.putExtra(HASHRATE_VALUE, hashrateValue); sendBroadcast(broadcastIntent); } private class WebServicesHandler extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { } @Override protected String doInBackground(String... urls) { try { URL url = new URL(urls[0]); URLConnection connection = url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); return streamToString(in); } catch (Exception e) { Log.d(MainActivity.class.getSimpleName(), e.toString()); return null; } } @Override protected void onPostExecute(String result) { try { JSONObject json = new JSONObject(result); JSONObject getuserhashrate = json.getJSONObject("getuserhashrate"); String hashrate = getuserhashrate.getString("data"); Double value = Double.valueOf(hashrate); Integer integer = value.intValue() / 1000; sendHashrateBroadcast(String.valueOf(integer)); testNotification(integer); } catch (Exception e) { Log.d(MainActivity.class.getSimpleName(), e.toString()); } } } public static String streamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder stringBuilder = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } reader.close(); } catch (IOException e) { Log.d(MainActivity.class.getSimpleName(), e.toString()); } return stringBuilder.toString(); } }
5,921
0.631988
0.62861
206
27.742718
26.334791
124
false
false
0
0
0
0
0
0
0.480583
false
false
15
bbfa3b3eec7820f2f1224b62dce17e2def9c0afb
14,663,018,356,832
152dcb36b46263f3aaca128bd639e0d1c549b34e
/app/src/main/java/android/uom/gr/airflight/ItemForHistory.java
8625dcb88ab3343ea9613d8d3279bf39c0a38ec8
[]
no_license
GougouVag/AirFlight
https://github.com/GougouVag/AirFlight
d59c68d84b796cc482f56c3f42637a2229be419e
e99931d507e4b3b1e06200b99e945f21f49e6ebc
refs/heads/main
2023-02-26T10:00:01.945000
2021-01-18T17:52:51
2021-01-18T17:52:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.uom.gr.airflight; /** * Created by LamPrOs on 10/1/2017. */ public class ItemForHistory { private int id; private String from; private String to; private String adults_number; private String children_number; private String infants; private String way_is; private String depart_day; private String arrival_day; public ItemForHistory(int id,String from,String to,String adults_number,String children_number,String infants,String way_is,String depart_day,String arrival_day ){ this.id = id; this.from = from; this.to = to; this.adults_number = adults_number; this.children_number = children_number; this.infants = infants; this.way_is = way_is; this.depart_day = depart_day; this.arrival_day = arrival_day; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFrom() { return from; } public String getTo() { return to; } public String getAdults_number() { return adults_number; } public String getArrival_day() { return arrival_day; } public String getChildren_number() { return children_number; } public String getDepart_day() { return depart_day; } public String getInfants() { return infants; } public void setFrom(String from) { this.from = from; } public String getWay_is() { return way_is; } public void setAdults_number(String adults_number) { this.adults_number = adults_number; } public void setChildren_number(String children_number) { this.children_number = children_number; } public void setDepart_day(String depart_day) { this.depart_day = depart_day; } public void setInfants(String infants) { this.infants = infants; } public void setTo(String to) { this.to = to; } public void setArrival_day(String arrival_day) { this.arrival_day = arrival_day; } public void setWay_is(String way_is) { this.way_is = way_is; } }
UTF-8
Java
2,217
java
ItemForHistory.java
Java
[ { "context": "ckage android.uom.gr.airflight;\n\n/**\n * Created by LamPrOs on 10/1/2017.\n */\n\npublic class ItemForHistory {\n", "end": 60, "score": 0.9994939565658569, "start": 53, "tag": "USERNAME", "value": "LamPrOs" } ]
null
[]
package android.uom.gr.airflight; /** * Created by LamPrOs on 10/1/2017. */ public class ItemForHistory { private int id; private String from; private String to; private String adults_number; private String children_number; private String infants; private String way_is; private String depart_day; private String arrival_day; public ItemForHistory(int id,String from,String to,String adults_number,String children_number,String infants,String way_is,String depart_day,String arrival_day ){ this.id = id; this.from = from; this.to = to; this.adults_number = adults_number; this.children_number = children_number; this.infants = infants; this.way_is = way_is; this.depart_day = depart_day; this.arrival_day = arrival_day; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFrom() { return from; } public String getTo() { return to; } public String getAdults_number() { return adults_number; } public String getArrival_day() { return arrival_day; } public String getChildren_number() { return children_number; } public String getDepart_day() { return depart_day; } public String getInfants() { return infants; } public void setFrom(String from) { this.from = from; } public String getWay_is() { return way_is; } public void setAdults_number(String adults_number) { this.adults_number = adults_number; } public void setChildren_number(String children_number) { this.children_number = children_number; } public void setDepart_day(String depart_day) { this.depart_day = depart_day; } public void setInfants(String infants) { this.infants = infants; } public void setTo(String to) { this.to = to; } public void setArrival_day(String arrival_day) { this.arrival_day = arrival_day; } public void setWay_is(String way_is) { this.way_is = way_is; } }
2,217
0.603969
0.600812
105
20.114286
21.981947
167
false
false
0
0
0
0
0
0
0.428571
false
false
15
ba507ceded9df61b12c110acf2884ec9e5d58368
28,458,453,368,529
082e26b011e30dc62a62fae95f375e4f87d9e99c
/docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/mm/plugin/sns/ui/SnsUserUI.java
80c037bd391a56e65922aad1fc7414a5a1e6d57c
[]
no_license
xsren/AndroidReverseNotes
https://github.com/xsren/AndroidReverseNotes
9631a5aabc031006e795a112b7ac756a8edd4385
9202c276fe9f04a978e4e08b08e42645d97ca94b
refs/heads/master
2021-04-07T22:50:51.072000
2019-07-16T02:24:43
2019-07-16T02:24:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.mm.plugin.sns.ui; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Parcel; import android.os.Process; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.tencent.d.f.e; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.R; import com.tencent.mm.g.a.ke; import com.tencent.mm.g.b.a.ah; import com.tencent.mm.hardcoder.WXHardCoderJNI; import com.tencent.mm.kernel.g; import com.tencent.mm.model.r; import com.tencent.mm.plugin.messenger.foundation.a.j; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.sns.data.i; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.plugin.sns.storage.v; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ab; import com.tencent.mm.sdk.platformtools.bo; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ad; import com.tencent.mm.storage.bd; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.MMPullDownView; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n; import com.tencent.mm.ui.base.n.d; import com.tencent.tmassistantsdk.downloadservice.Downloads; import com.tencent.ttpic.util.ActUtil; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class SnsUserUI extends MMActivity implements com.tencent.mm.plugin.sns.b.h.a { private long eEO = 0; private int ehv; private long fAq = 0; private c hAA = new c<ke>() { { AppMethodBeat.i(39793); this.xxI = ke.class.getName().hashCode(); AppMethodBeat.o(39793); } public final /* synthetic */ boolean a(b bVar) { AppMethodBeat.i(39794); ke keVar = (ke) bVar; if (keVar instanceof ke) { switch (keVar.cFH.action) { case 0: case 1: case 2: case 3: case 4: case 7: SnsUserUI.this.rCS.notifyDataSetChanged(); break; } } AppMethodBeat.o(39794); return false; } }; private String igi; private com.tencent.matrix.trace.e.b mnM = new com.tencent.matrix.trace.e.b() { public final void a(String str, long j, int i) { AppMethodBeat.i(39805); super.a(str, j, i); if (i > 0 && !bo.isNullOrNil(str) && str.endsWith(SnsUserUI.this.getClass().getSimpleName())) { SnsUserUI.this.eEO = SnsUserUI.this.eEO + ((long) i); } AppMethodBeat.o(39805); } }; private View plv; private com.tencent.mm.ui.statusbar.c.a plx; private as rCS; private SnsUIAction rCT; private com.tencent.mm.plugin.sns.model.am.a rCU; private com.tencent.mm.plugin.sns.ui.SnsUIAction.a rCV; private RelativeLayout rCW = null; private TextView rCX = null; private int rCY = 0; private Runnable rCZ = new Runnable() { public final void run() { AppMethodBeat.i(39785); SnsUserUI.this.rCS.ctK(); SnsUserUI.this.rCS.crP(); AppMethodBeat.o(39785); } }; private boolean rjn; private String ryC; private boolean ryD; private int ryE; private boolean ryx = false; private OnMenuItemClickListener rzm = new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { AppMethodBeat.i(39790); SnsUserUI.this.finish(); AppMethodBeat.o(39790); return true; } }; class a extends f { private ax rzp = null; a() { } public void fw(int i, int i2) { AppMethodBeat.i(39810); ab.i("MicroMsg.SnsUserUI", "showImg snsinfo snslocalId:%d, pos:%d,mIsSelf:%b ", Integer.valueOf(i), Integer.valueOf(i2), Boolean.valueOf(SnsUserUI.this.rjn)); Intent intent; if (SnsUserUI.this.rjn && i2 == -1) { g.RQ(); String str = (String) g.RP().Ry().get(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_MEDIA_STRING_SYNC, null); if (!bo.isNullOrNil(str)) { g.RQ(); String str2 = (String) g.RP().Ry().get(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_LAST_SESSIONID_STRING, (Object) ""); new ah().Fs().fk(str2).ajK(); byte[] atV = e.atV(str); Parcel obtain = Parcel.obtain(); obtain.unmarshall(atV, 0, atV.length); obtain.setDataPosition(0); try { intent = (Intent) Intent.CREATOR.createFromParcel(obtain); intent.addFlags(268435456); intent.setClass(SnsUserUI.this, SnsUploadUI.class); intent.putExtra("KSessionID", str2); SnsUserUI.this.startActivity(intent); AppMethodBeat.o(39810); return; } catch (Exception e) { g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_MEDIA_STRING_SYNC, (Object) ""); g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_LAST_SESSIONID_STRING, (Object) ""); } } this.rzp = new ax(SnsUserUI.this); this.rzp.rBl = new n.c() { public final void a(l lVar) { AppMethodBeat.i(39808); lVar.e(0, SnsUserUI.this.getString(R.string.q4)); lVar.e(1, SnsUserUI.this.getString(R.string.qa)); AppMethodBeat.o(39808); } }; this.rzp.c(0, SnsUserUI.this.mController.ylL.getString(R.string.q9)); this.rzp.rBm = new d() { public final void onMMMenuItemSelected(MenuItem menuItem, int i) { AppMethodBeat.i(39809); switch (menuItem.getItemId()) { case 0: h.pYm.e(13822, Integer.valueOf(1), Integer.valueOf(2)); SnsUserUI.o(SnsUserUI.this); AppMethodBeat.o(39809); return; case 1: h.pYm.e(13822, Integer.valueOf(2), Integer.valueOf(2)); SnsUserUI.this.rCT.Em(1); break; } AppMethodBeat.o(39809); } }; this.rzp.cuu(); AppMethodBeat.o(39810); return; } intent = new Intent(SnsUserUI.this, SnsGalleryUI.class); intent.putExtra("sns_gallery_userName", SnsUserUI.this.igi); intent.putExtra("sns_gallery_is_self", SnsUserUI.this.rjn); intent.putExtra("sns_gallery_localId", i); intent.putExtra("sns_source", SnsUserUI.this.ryE); intent.putExtra("sns_gallery_st_time", SnsUserUI.this.rCS.rvy); intent.putExtra("sns_gallery_ed_time", SnsUserUI.this.rCS.rvz); if (SnsUserUI.this.rCS != null) { intent.putExtra("sns_gallery_limit_seq", SnsUserUI.this.rCS.lQD); SnsUserUI.this.rCU.j(SnsUserUI.this.igi, SnsUserUI.this.rCS.fv(i, i2)); intent.putExtra("sns_gallery_position", SnsUserUI.this.rCS.rvC); } SnsUserUI.this.startActivityForResult(intent, 8); AppMethodBeat.o(39810); } public final void fx(int i, int i2) { AppMethodBeat.i(39811); com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK == null) { AppMethodBeat.o(39811); } else if (DK.field_type == 15) { Intent intent = new Intent(SnsUserUI.this, SnsGalleryUI.class); intent.putExtra("sns_gallery_userName", SnsUserUI.this.igi); intent.putExtra("sns_gallery_is_self", SnsUserUI.this.rjn); intent.putExtra("sns_gallery_localId", i); intent.putExtra("sns_source", SnsUserUI.this.ryE); intent.putExtra("sns_gallery_st_time", SnsUserUI.this.rCS.rvy); intent.putExtra("sns_gallery_ed_time", SnsUserUI.this.rCS.rvz); if (SnsUserUI.this.rCS != null) { intent.putExtra("sns_gallery_limit_seq", SnsUserUI.this.rCS.lQD); SnsUserUI.this.rCU.j(SnsUserUI.this.igi, SnsUserUI.this.rCS.fv(i, i2)); intent.putExtra("sns_gallery_position", SnsUserUI.this.rCS.rvC); } SnsUserUI.this.startActivityForResult(intent, 8); AppMethodBeat.o(39811); } else { Intent intent2 = new Intent(); intent2.setClass(SnsUserUI.this, SnsCommentDetailUI.class); intent2.putExtra("INTENT_TALKER", DK.field_userName); intent2.putExtra("INTENT_SNS_LOCAL_ID", v.ap("sns_table_", (long) i)); SnsUserUI.this.startActivityForResult(intent2, 12); AppMethodBeat.o(39811); } } public final void Ed(int i) { AppMethodBeat.i(39812); com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK == null) { AppMethodBeat.o(39812); return; } Intent intent = new Intent(); intent.setClass(SnsUserUI.this, SnsCommentDetailUI.class); intent.putExtra("INTENT_TALKER", DK.field_userName); intent.putExtra("INTENT_SNS_LOCAL_ID", v.ap("sns_table_", (long) i)); SnsUserUI.this.startActivityForResult(intent, 12); AppMethodBeat.o(39812); } public final void fy(int i, int i2) { AppMethodBeat.i(39813); ab.d("MicroMsg.SnsUserUI", "onFailLongClick localId:%s position:%s", Integer.valueOf(i), Integer.valueOf(i2)); com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK != null && DK.cnn() && DK.cqW()) { SnsUserUI.b(SnsUserUI.this, i); } AppMethodBeat.o(39813); } } public void onWindowFocusChanged(boolean z) { super.onWindowFocusChanged(z); AppMethodBeat.at(this, z); } public SnsUserUI() { AppMethodBeat.i(39814); AppMethodBeat.o(39814); } static /* synthetic */ void o(SnsUserUI snsUserUI) { AppMethodBeat.i(39831); snsUserUI.cuG(); AppMethodBeat.o(39831); } public void onCreate(Bundle bundle) { AppMethodBeat.i(39815); if (this.mController != null) { this.mController.aC(2, false); } this.ylm = true; super.onCreate(bundle); if (g.RN().QY()) { com.tencent.mm.n.a aoO; this.plv = findViewById(R.id.k0); if (this.plv != null && com.tencent.mm.ui.statusbar.c.zzP) { com.tencent.mm.ui.statusbar.c az = com.tencent.mm.ui.statusbar.c.az(this); AnonymousClass4 anonymousClass4 = new com.tencent.mm.ui.statusbar.c.a() { public final void pO(int i) { AppMethodBeat.i(39788); SnsUserUI.this.plv.setPadding(0, i, 0, 0); com.tencent.mm.ui.statusbar.d.a(SnsUserUI.this.getWindow()); AppMethodBeat.o(39788); } }; this.plx = anonymousClass4; az.a(anonymousClass4); getWindow().getDecorView().requestApplyInsets(); com.tencent.mm.ui.statusbar.d.a(getWindow()); } getWindow().getDecorView().setSystemUiVisibility(ActUtil.HEIGHT); xE(this.mController.ylL.getResources().getColor(R.color.a3p)); b(new Runnable() { public final void run() { } }, new Runnable() { public final void run() { } }); this.rCU = af.cnv(); this.ryE = getIntent().getIntExtra("sns_source", 0); this.igi = getIntent().getStringExtra("sns_userName"); if (this.igi == null) { this.igi = ""; } g.RQ(); this.ryD = ((j) g.K(j.class)).XM().aoJ(this.igi); this.ryC = r.Yz(); this.rjn = this.ryC.equals(this.igi); bd cnt = af.cnt(); String bc = bo.bc(getIntent().getStringExtra("sns_signature"), ""); String bc2 = bo.bc(getIntent().getStringExtra("sns_nickName"), ""); if (this.igi == null || this.igi.equals("")) { aoO = cnt.aoO(this.ryC); } else { aoO = cnt.aoO(this.igi); } if (aoO != null && ((int) aoO.ewQ) > 0) { bc = aoO.signature; bc2 = aoO.Oi(); ab.i("MicroMsg.SnsUserUI", "contact:user[%s] id[%d] nickname[%s]", aoO.field_username, Integer.valueOf((int) aoO.ewQ), bc2); } this.rCT = new SnsUIAction(this); this.rCT.a(this.ryC, this.igi, bc2, bc, this.ryD, this.rjn, this.ryE); SnsUIAction snsUIAction = this.rCT; AnonymousClass13 anonymousClass13 = new com.tencent.mm.plugin.sns.ui.SnsUIAction.a() { public final void cuh() { AppMethodBeat.i(39795); if (SnsUserUI.this.rCU == null) { SnsUserUI.this.rCU = af.cnv(); } com.tencent.mm.plugin.sns.model.am.a b = SnsUserUI.this.rCU; String c = SnsUserUI.this.igi; SnsUserUI.this.ryD; b.b(2, c, SnsUserUI.this.rjn, SnsUserUI.this.ryE); af.bCo().postDelayed(SnsUserUI.this.rCZ, 3000); AppMethodBeat.o(39795); } public final ListView getSnsListView() { AppMethodBeat.i(39796); ListView listView = (ListView) SnsUserUI.this.findViewById(R.id.eii); AppMethodBeat.o(39796); return listView; } public final View cui() { AppMethodBeat.i(39797); View findViewById = SnsUserUI.this.findViewById(R.id.um); AppMethodBeat.o(39797); return findViewById; } public final View getMaskView() { AppMethodBeat.i(39798); View findViewById = SnsUserUI.this.findViewById(R.id.el6); AppMethodBeat.o(39798); return findViewById; } public final MMPullDownView cuj() { AppMethodBeat.i(39799); MMPullDownView mMPullDownView = (MMPullDownView) SnsUserUI.this.findViewById(R.id.avx); AppMethodBeat.o(39799); return mMPullDownView; } public final int getType() { return 2; } public final void b(int i, List<Integer> list, List<Integer> list2) { as a; AppMethodBeat.i(39800); if (!(i == -1 || SnsUserUI.this.rCS == null)) { a = SnsUserUI.this.rCS; if (a.rvw != null) { at atVar = a.rvw; com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (!(DK == null || DK.cqu().xfI == null || atVar.list.size() <= 0)) { atVar.list.add(1, DK); atVar.ctM(); atVar.ctN(); } } } if (!(SnsUserUI.this.rCS == null || list == null || list2 == null)) { a = SnsUserUI.this.rCS; if (a.rvw != null) { if (list == null || list2 == null || list.size() + list2.size() == 0) { AppMethodBeat.o(39800); return; } int i2; com.tencent.mm.plugin.sns.storage.n nVar; at atVar2 = a.rvw; if (!(list == null || list.size() == 0)) { ab.d("MicroMsg.SnsSelfHelper", "remove Items"); for (Integer intValue : list) { int intValue2 = intValue.intValue(); int size = atVar2.list.size(); for (i2 = 1; i2 < size; i2++) { nVar = (com.tencent.mm.plugin.sns.storage.n) atVar2.list.get(i2); if (nVar != null && nVar.reX == intValue2) { atVar2.list.remove(i2); break; } } } } if (!(list2 == null || list2.size() == 0)) { ab.d("MicroMsg.SnsSelfHelper", "change Items"); LinkedList linkedList = new LinkedList(); i2 = 1; while (i2 < atVar2.list.size()) { nVar = (com.tencent.mm.plugin.sns.storage.n) atVar2.list.get(i2); if (nVar != null) { for (Integer intValue3 : list2) { int intValue4 = intValue3.intValue(); if (nVar.reX == intValue4) { ab.d("MicroMsg.SnsSelfHelper", "update list localId ".concat(String.valueOf(intValue4))); atVar2.list.remove(i2); linkedList.add(af.cnF().DK(intValue4)); i2--; break; } } } i2++; } Iterator it = linkedList.iterator(); while (it.hasNext()) { atVar2.list.add((com.tencent.mm.plugin.sns.storage.n) it.next()); } } atVar2.ctM(); atVar2.ctN(); } } AppMethodBeat.o(39800); } public final boolean cuk() { return false; } public final void cul() { AppMethodBeat.i(39801); com.tencent.mm.plugin.sns.model.am.a b = SnsUserUI.this.rCU; String c = SnsUserUI.this.igi; SnsUserUI.this.ryD; b.a(2, c, SnsUserUI.this.rjn, SnsUserUI.this.ryE); AppMethodBeat.o(39801); } public final void cum() { } public final void Eh(int i) { AppMethodBeat.i(39802); ab.i("MicroMsg.SnsUserUI", "onListViewScoll %s", Integer.valueOf(i)); if (i == 2) { WXHardCoderJNI.stopPerformance(WXHardCoderJNI.hcSNSUserScrollEnable, SnsUserUI.this.ehv); SnsUserUI.this.ehv = WXHardCoderJNI.startPerformance(WXHardCoderJNI.hcSNSUserScrollEnable, WXHardCoderJNI.hcSNSUserScrollDelay, WXHardCoderJNI.hcSNSUserScrollCPU, WXHardCoderJNI.hcSNSUserScrollIO, WXHardCoderJNI.hcSNSUserScrollThr ? Process.myTid() : 0, WXHardCoderJNI.hcSNSUserScrollTimeout, 704, WXHardCoderJNI.hcSNSUserScrollAction, "MicroMsg.SnsUserUI"); ab.i("MicroMsg.SnsUserUI", "summer hardcoder sns startPerformance [%s]", Integer.valueOf(SnsUserUI.this.ehv)); } AppMethodBeat.o(39802); } public final void ad(int i, boolean z) { Object obj = null; AppMethodBeat.i(39803); if (SnsUserUI.this.rCS != null) { as a = SnsUserUI.this.rCS; if (a.rvw != null) { at atVar = a.rvw; com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK == null || DK.cqu().xfI == null || atVar.list.size() <= 0) { AppMethodBeat.o(39803); return; } for (int i2 = 0; i2 < atVar.list.size(); i2++) { if (((com.tencent.mm.plugin.sns.storage.n) atVar.list.get(i2)).cqU() == DK.cqU()) { obj = 1; atVar.list.remove(i2); break; } } if (obj != null) { atVar.list.add(DK); atVar.ctM(); atVar.ctN(); } } } AppMethodBeat.o(39803); } public final void ln(boolean z) { } public final void fA(int i, int i2) { AppMethodBeat.i(39804); if (i2 <= 0) { SnsUserUI.i(SnsUserUI.this); AppMethodBeat.o(39804); return; } SnsUserUI.a(SnsUserUI.this, i, i2); AppMethodBeat.o(39804); } }; this.rCV = anonymousClass13; snsUIAction.rBP = anonymousClass13; this.rCT.onCreate(); getIntent().setExtrasClassLoader(getClass().getClassLoader()); initView(); com.tencent.mm.sdk.b.a.xxA.c(this.hAA); AppMethodBeat.o(39815); return; } finish(); AppMethodBeat.o(39815); } public void onDestroy() { AppMethodBeat.i(39816); af.bCo().removeCallbacks(this.rCZ); this.ryx = true; com.tencent.mm.sdk.b.a.xxA.d(this.hAA); com.tencent.mm.modelsns.b u = com.tencent.mm.modelsns.b.u(getIntent()); if (u != null) { u.update(); u.ajK(); } if (!(this.rCT == null || this.rCT.tipDialog == null)) { this.rCT.tipDialog.dismiss(); this.rCT.tipDialog = null; } g.RQ(); if (g.RN().QY() && this.rCU != null) { this.rCU.a(this, this.rCV.getType()); } if (this.rCT != null) { this.rCT.onDestroy(); } super.onDestroy(); AppMethodBeat.o(39816); } public void onDrag() { AppMethodBeat.i(39817); super.onDrag(); AppMethodBeat.o(39817); } public final int getLayoutId() { return R.layout.aw6; } public void onResume() { AppMethodBeat.i(39818); this.fAq = bo.anT(); if (com.tencent.matrix.a.isInstalled() && com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class) != null) { com.tencent.matrix.trace.f.c cVar = ((com.tencent.matrix.trace.a) com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class)).bYx; if (cVar != null) { cVar.a(this.mnM); } } if (this.rCS != null) { this.rCS.notifyDataSetChanged(); } setRequestedOrientation(-1); if (this.rjn) { b(getString(R.string.emv), (int) R.raw.actionbar_list_icon, (OnMenuItemClickListener) new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { AppMethodBeat.i(39787); Intent intent = new Intent(); intent.setClass(SnsUserUI.this, SnsMsgUI.class); intent.putExtra("sns_msg_force_show_all", true); SnsUserUI.this.startActivityForResult(intent, 8); AppMethodBeat.o(39787); return true; } }); } else { enableOptionMenu(false); } setBackBtn(this.rzm, R.raw.actionbar_icon_dark_back); if (this.rjn) { setMMTitle((int) R.string.enj); } else { CharSequence Oj; ab.d("MicroMsg.SnsUserUI", "SnsUserUI, userName:%s, title:%s", this.igi, this.rCT.title); ad aoO = af.cnt().aoO(this.igi); if (aoO != null) { ab.d("MicroMsg.SnsUserUI", "SnsUserUI, contact is not null"); Oj = aoO.Oj(); } else { ab.d("MicroMsg.SnsUserUI", "SnsUserUI, contact is null, title:%s", this.rCT.title); Oj = this.rCT.title; } setMMTitle(i.K(Oj)); } this.rCT.onResume(); super.onResume(); AppMethodBeat.o(39818); } public void onPause() { AppMethodBeat.i(39819); WXHardCoderJNI.stopPerformance(WXHardCoderJNI.hcSNSUserScrollEnable, this.ehv); this.ehv = 0; this.rCT.onPause(); super.onPause(); if (com.tencent.matrix.a.isInstalled() && com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class) != null) { com.tencent.matrix.trace.f.c cVar = ((com.tencent.matrix.trace.a) com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class)).bYx; if (cVar != null) { cVar.b(this.mnM); } } this.fAq = bo.anT() > this.fAq ? bo.anT() - this.fAq : 1; WXHardCoderJNI.reportFPS(704, WXHardCoderJNI.hcSNSUserScrollAction, 1, this.eEO, this.fAq); this.eEO = 0; this.fAq = 0; AppMethodBeat.o(39819); } public final void initView() { AppMethodBeat.i(39820); this.rCW = (RelativeLayout) findViewById(R.id.el7); this.rCX = (TextView) findViewById(R.id.el8); this.rCW.post(new Runnable() { public final void run() { AppMethodBeat.i(39806); LayoutParams layoutParams = new LayoutParams(-1, -2); layoutParams.topMargin = x.al(SnsUserUI.this) + SnsUserUI.this.getResources().getDimensionPixelSize(R.dimen.di); SnsUserUI.this.rCW.setLayoutParams(layoutParams); AppMethodBeat.o(39806); } }); this.rCS = new as(this, new a() { public final void fw(int i, int i2) { AppMethodBeat.i(39807); super.fw(i, i2); AppMethodBeat.o(39807); } }, this.igi, new as.c() { }); this.rCT.nDp.setAdapter(this.rCS); this.rCT.nDp.setOnItemClickListener(new OnItemClickListener() { public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { } }); this.rCT.nDp.postDelayed(new Runnable() { public final void run() { AppMethodBeat.i(39786); if (SnsUserUI.this.ryx) { ab.w("MicroMsg.SnsUserUI", "too fast that it finish"); AppMethodBeat.o(39786); return; } SnsUserUI.this.rCU.a(SnsUserUI.this.rCV.getType(), SnsUserUI.this.igi, SnsUserUI.this); if (SnsUserUI.this.rCV.getType() == 1 && SnsUserUI.this.rCV.cuk()) { af.cnv().B(af.cnM().qMB, -1); } if (!SnsUserUI.this.rCV.cuk()) { com.tencent.mm.plugin.sns.model.am.a b = SnsUserUI.this.rCU; int type = SnsUserUI.this.rCV.getType(); String c = SnsUserUI.this.igi; SnsUserUI.this.ryD; b.a(type, c, SnsUserUI.this.rjn, SnsUserUI.this.ryE); } AppMethodBeat.o(39786); } }, 500); setBackBtn(this.rzm, R.raw.actionbar_icon_dark_back); AppMethodBeat.o(39820); } public final void a(boolean z, boolean z2, String str, boolean z3, boolean z4, int i, long j, String str2) { AppMethodBeat.i(39821); if (this.rCS != null) { this.rCS.rmL = str; if (str.compareTo(this.rCS.lQD) < 0) { ab.i("MicroMsg.SnsUserUI", "onFpSetSize addsize %s %s isNeedNP %s", str, this.rCS.lQD, Boolean.valueOf(z)); this.rCS.ctK(); } else { ab.i("MicroMsg.SnsUserUI", "onFpSetSize addsize passed %s %s isNeedNP %s", str, this.rCS.lQD, Boolean.valueOf(z)); } this.rCS.crP(); } if ((z4 || !bo.isNullOrNil(str2)) && !this.ryC.equals(this.igi)) { this.rCT.koC = true; this.rCT.bf(i, str2); } else { if (this.ryC.equals(this.igi) && j != 0) { g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_RECENT_LIMITED_ID_LONG_SYNC, Long.valueOf(j)); this.rCS.kI(j); } this.rCT.koC = z2; if (z2) { this.rCT.lc(false); } else if (z) { this.rCU.b(this.rCV.getType(), this.igi, this.rjn, this.ryE); } } if (z3) { this.rCT.qQt.cti(); } AppMethodBeat.o(39821); } public final void a(boolean z, String str, boolean z2, boolean z3, int i, long j, String str2) { AppMethodBeat.i(39822); af.bCo().removeCallbacks(this.rCZ); if (this.rCS != null) { this.rCS.rvv = z2; this.rCS.rmL = str; if (str.compareTo(this.rCS.lQD) < 0) { ab.i("MicroMsg.SnsUserUI", "onNpAddSize addsize %s %s", str, this.rCS.lQD); this.rCS.ctK(); } else { ab.i("MicroMsg.SnsUserUI", "onNpAddSize addsize passed %s %s", str, this.rCS.lQD); } this.rCS.crP(); } if (!z3 || this.ryC.equals(this.igi)) { if (this.ryC.equals(this.igi) && j != 0) { g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_RECENT_LIMITED_ID_LONG_SYNC, Long.valueOf(j)); this.rCS.kI(j); } this.rCT.koC = z; if (z) { this.rCT.lc(false); } AppMethodBeat.o(39822); return; } this.rCT.koC = true; this.rCT.bf(i, str2); AppMethodBeat.o(39822); } public final void xE(int i) { AppMethodBeat.i(39823); super.xE(i); if (VERSION.SDK_INT >= 21 && this.plv != null) { this.plv.setBackgroundColor(getWindow().getStatusBarColor()); com.tencent.mm.ui.statusbar.d.a(getWindow()); } AppMethodBeat.o(39823); } private void cuG() { AppMethodBeat.i(39824); if (com.tencent.mm.r.a.bH(this)) { AppMethodBeat.o(39824); return; } ab.d("MicroMsg.SnsUserUI", "summerper checkPermission checkCamera[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.CAMERA", 18, "", "")), bo.dpG(), this); if (com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.CAMERA", 18, "", "")) { ab.d("MicroMsg.SnsUserUI", "summerper checkPermission checkmicrophone[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.RECORD_AUDIO", 18, "", "")), bo.dpG(), this); if (com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.RECORD_AUDIO", 18, "", "")) { com.tencent.mm.pluginsdk.ui.tools.n.G(this.mController.ylL, new Intent()); AppMethodBeat.o(39824); return; } AppMethodBeat.o(39824); return; } AppMethodBeat.o(39824); } public void onBackPressed() { AppMethodBeat.i(39825); finish(); AppMethodBeat.o(39825); } public boolean supportNavigationSwipeBack() { AppMethodBeat.i(39826); boolean supportNavigationSwipeBack = super.supportNavigationSwipeBack(); AppMethodBeat.o(39826); return supportNavigationSwipeBack; } public void onActivityResult(int i, int i2, Intent intent) { AppMethodBeat.i(39827); ab.i("MicroMsg.SnsUserUI", "on activity result, %d %d", Integer.valueOf(i), Integer.valueOf(i2)); if (5985 == i && i2 == -1) { finish(); AppMethodBeat.o(39827); return; } super.onActivityResult(i, i2, intent); this.rCT.onActivityResult(i, i2, intent); AppMethodBeat.o(39827); } public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) { AppMethodBeat.i(39828); if (iArr == null || iArr.length <= 0) { ab.i("MicroMsg.SnsUserUI", "onRequestPermissionsResult grantResults length 0. requestCode[%d], tid[%d]", Integer.valueOf(i), Long.valueOf(Thread.currentThread().getId())); AppMethodBeat.o(39828); return; } ab.i("MicroMsg.SnsUserUI", "onRequestPermissionsResult requestCode[%d],grantResults[%d] tid[%d]", Integer.valueOf(i), Integer.valueOf(iArr[0]), Long.valueOf(Thread.currentThread().getId())); switch (i) { case 18: if (iArr[0] != 0) { int i2 = "android.permission.CAMERA".equals(strArr[0]) ? R.string.dbs : R.string.dc0; if (iArr[0] != 0) { com.tencent.mm.ui.base.h.a((Context) this, getString(i2), getString(R.string.dc8), getString(R.string.ckr), getString(R.string.or), false, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { AppMethodBeat.i(39791); dialogInterface.dismiss(); SnsUserUI.this.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS")); AppMethodBeat.o(39791); } }, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { AppMethodBeat.i(39792); dialogInterface.dismiss(); AppMethodBeat.o(39792); } }); break; } } cuG(); AppMethodBeat.o(39828); return; break; } AppMethodBeat.o(39828); } static /* synthetic */ void i(SnsUserUI snsUserUI) { AppMethodBeat.i(39829); snsUserUI.rCW.setVisibility(8); AppMethodBeat.o(39829); } static /* synthetic */ void a(SnsUserUI snsUserUI, int i, int i2) { int i3; AppMethodBeat.i(39830); as asVar = snsUserUI.rCS; if (asVar.rgf.get(Integer.valueOf(i)) == null) { i3 = -1; } else { i3 = ((Integer) asVar.rgf.get(Integer.valueOf(i))).intValue(); } ab.d("MicroMsg.SnsUserUI", "displayYearTip position:%d alpha:%d realPos:%d", Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3)); if (i3 != -1) { Object item = snsUserUI.rCS.getItem(i3); if (item != null && (item instanceof com.tencent.mm.plugin.sns.storage.n)) { float f = ((float) i2) / 100.0f; if (f != snsUserUI.rCW.getAlpha()) { snsUserUI.rCW.setAlpha(f); } snsUserUI.rCW.setVisibility(0); com.tencent.mm.plugin.sns.storage.n nVar = (com.tencent.mm.plugin.sns.storage.n) item; if (snsUserUI.rCY != nVar.field_head / Downloads.MIN_WAIT_FOR_NETWORK) { snsUserUI.rCY = nVar.field_head / Downloads.MIN_WAIT_FOR_NETWORK; snsUserUI.rCX.setText(String.format(snsUserUI.getResources().getString(R.string.eqj), new Object[]{Integer.valueOf(snsUserUI.rCY)})); } } } AppMethodBeat.o(39830); } static /* synthetic */ void b(SnsUserUI snsUserUI, final int i) { AppMethodBeat.i(39832); com.tencent.mm.ui.base.h.a((Context) snsUserUI, (int) R.string.p5, (int) R.string.tz, (int) R.string.s6, (int) R.string.or, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { AppMethodBeat.i(39789); af.cnF().DL(i); SnsUserUI.this.rCS.crP(); AppMethodBeat.o(39789); } }, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { } }); AppMethodBeat.o(39832); } }
UTF-8
Java
39,193
java
SnsUserUI.java
Java
[]
null
[]
package com.tencent.mm.plugin.sns.ui; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Parcel; import android.os.Process; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.tencent.d.f.e; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.R; import com.tencent.mm.g.a.ke; import com.tencent.mm.g.b.a.ah; import com.tencent.mm.hardcoder.WXHardCoderJNI; import com.tencent.mm.kernel.g; import com.tencent.mm.model.r; import com.tencent.mm.plugin.messenger.foundation.a.j; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.sns.data.i; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.plugin.sns.storage.v; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ab; import com.tencent.mm.sdk.platformtools.bo; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ad; import com.tencent.mm.storage.bd; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.MMPullDownView; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n; import com.tencent.mm.ui.base.n.d; import com.tencent.tmassistantsdk.downloadservice.Downloads; import com.tencent.ttpic.util.ActUtil; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class SnsUserUI extends MMActivity implements com.tencent.mm.plugin.sns.b.h.a { private long eEO = 0; private int ehv; private long fAq = 0; private c hAA = new c<ke>() { { AppMethodBeat.i(39793); this.xxI = ke.class.getName().hashCode(); AppMethodBeat.o(39793); } public final /* synthetic */ boolean a(b bVar) { AppMethodBeat.i(39794); ke keVar = (ke) bVar; if (keVar instanceof ke) { switch (keVar.cFH.action) { case 0: case 1: case 2: case 3: case 4: case 7: SnsUserUI.this.rCS.notifyDataSetChanged(); break; } } AppMethodBeat.o(39794); return false; } }; private String igi; private com.tencent.matrix.trace.e.b mnM = new com.tencent.matrix.trace.e.b() { public final void a(String str, long j, int i) { AppMethodBeat.i(39805); super.a(str, j, i); if (i > 0 && !bo.isNullOrNil(str) && str.endsWith(SnsUserUI.this.getClass().getSimpleName())) { SnsUserUI.this.eEO = SnsUserUI.this.eEO + ((long) i); } AppMethodBeat.o(39805); } }; private View plv; private com.tencent.mm.ui.statusbar.c.a plx; private as rCS; private SnsUIAction rCT; private com.tencent.mm.plugin.sns.model.am.a rCU; private com.tencent.mm.plugin.sns.ui.SnsUIAction.a rCV; private RelativeLayout rCW = null; private TextView rCX = null; private int rCY = 0; private Runnable rCZ = new Runnable() { public final void run() { AppMethodBeat.i(39785); SnsUserUI.this.rCS.ctK(); SnsUserUI.this.rCS.crP(); AppMethodBeat.o(39785); } }; private boolean rjn; private String ryC; private boolean ryD; private int ryE; private boolean ryx = false; private OnMenuItemClickListener rzm = new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { AppMethodBeat.i(39790); SnsUserUI.this.finish(); AppMethodBeat.o(39790); return true; } }; class a extends f { private ax rzp = null; a() { } public void fw(int i, int i2) { AppMethodBeat.i(39810); ab.i("MicroMsg.SnsUserUI", "showImg snsinfo snslocalId:%d, pos:%d,mIsSelf:%b ", Integer.valueOf(i), Integer.valueOf(i2), Boolean.valueOf(SnsUserUI.this.rjn)); Intent intent; if (SnsUserUI.this.rjn && i2 == -1) { g.RQ(); String str = (String) g.RP().Ry().get(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_MEDIA_STRING_SYNC, null); if (!bo.isNullOrNil(str)) { g.RQ(); String str2 = (String) g.RP().Ry().get(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_LAST_SESSIONID_STRING, (Object) ""); new ah().Fs().fk(str2).ajK(); byte[] atV = e.atV(str); Parcel obtain = Parcel.obtain(); obtain.unmarshall(atV, 0, atV.length); obtain.setDataPosition(0); try { intent = (Intent) Intent.CREATOR.createFromParcel(obtain); intent.addFlags(268435456); intent.setClass(SnsUserUI.this, SnsUploadUI.class); intent.putExtra("KSessionID", str2); SnsUserUI.this.startActivity(intent); AppMethodBeat.o(39810); return; } catch (Exception e) { g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_MEDIA_STRING_SYNC, (Object) ""); g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_OPEN_UPLOAD_DRAFT_LAST_SESSIONID_STRING, (Object) ""); } } this.rzp = new ax(SnsUserUI.this); this.rzp.rBl = new n.c() { public final void a(l lVar) { AppMethodBeat.i(39808); lVar.e(0, SnsUserUI.this.getString(R.string.q4)); lVar.e(1, SnsUserUI.this.getString(R.string.qa)); AppMethodBeat.o(39808); } }; this.rzp.c(0, SnsUserUI.this.mController.ylL.getString(R.string.q9)); this.rzp.rBm = new d() { public final void onMMMenuItemSelected(MenuItem menuItem, int i) { AppMethodBeat.i(39809); switch (menuItem.getItemId()) { case 0: h.pYm.e(13822, Integer.valueOf(1), Integer.valueOf(2)); SnsUserUI.o(SnsUserUI.this); AppMethodBeat.o(39809); return; case 1: h.pYm.e(13822, Integer.valueOf(2), Integer.valueOf(2)); SnsUserUI.this.rCT.Em(1); break; } AppMethodBeat.o(39809); } }; this.rzp.cuu(); AppMethodBeat.o(39810); return; } intent = new Intent(SnsUserUI.this, SnsGalleryUI.class); intent.putExtra("sns_gallery_userName", SnsUserUI.this.igi); intent.putExtra("sns_gallery_is_self", SnsUserUI.this.rjn); intent.putExtra("sns_gallery_localId", i); intent.putExtra("sns_source", SnsUserUI.this.ryE); intent.putExtra("sns_gallery_st_time", SnsUserUI.this.rCS.rvy); intent.putExtra("sns_gallery_ed_time", SnsUserUI.this.rCS.rvz); if (SnsUserUI.this.rCS != null) { intent.putExtra("sns_gallery_limit_seq", SnsUserUI.this.rCS.lQD); SnsUserUI.this.rCU.j(SnsUserUI.this.igi, SnsUserUI.this.rCS.fv(i, i2)); intent.putExtra("sns_gallery_position", SnsUserUI.this.rCS.rvC); } SnsUserUI.this.startActivityForResult(intent, 8); AppMethodBeat.o(39810); } public final void fx(int i, int i2) { AppMethodBeat.i(39811); com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK == null) { AppMethodBeat.o(39811); } else if (DK.field_type == 15) { Intent intent = new Intent(SnsUserUI.this, SnsGalleryUI.class); intent.putExtra("sns_gallery_userName", SnsUserUI.this.igi); intent.putExtra("sns_gallery_is_self", SnsUserUI.this.rjn); intent.putExtra("sns_gallery_localId", i); intent.putExtra("sns_source", SnsUserUI.this.ryE); intent.putExtra("sns_gallery_st_time", SnsUserUI.this.rCS.rvy); intent.putExtra("sns_gallery_ed_time", SnsUserUI.this.rCS.rvz); if (SnsUserUI.this.rCS != null) { intent.putExtra("sns_gallery_limit_seq", SnsUserUI.this.rCS.lQD); SnsUserUI.this.rCU.j(SnsUserUI.this.igi, SnsUserUI.this.rCS.fv(i, i2)); intent.putExtra("sns_gallery_position", SnsUserUI.this.rCS.rvC); } SnsUserUI.this.startActivityForResult(intent, 8); AppMethodBeat.o(39811); } else { Intent intent2 = new Intent(); intent2.setClass(SnsUserUI.this, SnsCommentDetailUI.class); intent2.putExtra("INTENT_TALKER", DK.field_userName); intent2.putExtra("INTENT_SNS_LOCAL_ID", v.ap("sns_table_", (long) i)); SnsUserUI.this.startActivityForResult(intent2, 12); AppMethodBeat.o(39811); } } public final void Ed(int i) { AppMethodBeat.i(39812); com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK == null) { AppMethodBeat.o(39812); return; } Intent intent = new Intent(); intent.setClass(SnsUserUI.this, SnsCommentDetailUI.class); intent.putExtra("INTENT_TALKER", DK.field_userName); intent.putExtra("INTENT_SNS_LOCAL_ID", v.ap("sns_table_", (long) i)); SnsUserUI.this.startActivityForResult(intent, 12); AppMethodBeat.o(39812); } public final void fy(int i, int i2) { AppMethodBeat.i(39813); ab.d("MicroMsg.SnsUserUI", "onFailLongClick localId:%s position:%s", Integer.valueOf(i), Integer.valueOf(i2)); com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK != null && DK.cnn() && DK.cqW()) { SnsUserUI.b(SnsUserUI.this, i); } AppMethodBeat.o(39813); } } public void onWindowFocusChanged(boolean z) { super.onWindowFocusChanged(z); AppMethodBeat.at(this, z); } public SnsUserUI() { AppMethodBeat.i(39814); AppMethodBeat.o(39814); } static /* synthetic */ void o(SnsUserUI snsUserUI) { AppMethodBeat.i(39831); snsUserUI.cuG(); AppMethodBeat.o(39831); } public void onCreate(Bundle bundle) { AppMethodBeat.i(39815); if (this.mController != null) { this.mController.aC(2, false); } this.ylm = true; super.onCreate(bundle); if (g.RN().QY()) { com.tencent.mm.n.a aoO; this.plv = findViewById(R.id.k0); if (this.plv != null && com.tencent.mm.ui.statusbar.c.zzP) { com.tencent.mm.ui.statusbar.c az = com.tencent.mm.ui.statusbar.c.az(this); AnonymousClass4 anonymousClass4 = new com.tencent.mm.ui.statusbar.c.a() { public final void pO(int i) { AppMethodBeat.i(39788); SnsUserUI.this.plv.setPadding(0, i, 0, 0); com.tencent.mm.ui.statusbar.d.a(SnsUserUI.this.getWindow()); AppMethodBeat.o(39788); } }; this.plx = anonymousClass4; az.a(anonymousClass4); getWindow().getDecorView().requestApplyInsets(); com.tencent.mm.ui.statusbar.d.a(getWindow()); } getWindow().getDecorView().setSystemUiVisibility(ActUtil.HEIGHT); xE(this.mController.ylL.getResources().getColor(R.color.a3p)); b(new Runnable() { public final void run() { } }, new Runnable() { public final void run() { } }); this.rCU = af.cnv(); this.ryE = getIntent().getIntExtra("sns_source", 0); this.igi = getIntent().getStringExtra("sns_userName"); if (this.igi == null) { this.igi = ""; } g.RQ(); this.ryD = ((j) g.K(j.class)).XM().aoJ(this.igi); this.ryC = r.Yz(); this.rjn = this.ryC.equals(this.igi); bd cnt = af.cnt(); String bc = bo.bc(getIntent().getStringExtra("sns_signature"), ""); String bc2 = bo.bc(getIntent().getStringExtra("sns_nickName"), ""); if (this.igi == null || this.igi.equals("")) { aoO = cnt.aoO(this.ryC); } else { aoO = cnt.aoO(this.igi); } if (aoO != null && ((int) aoO.ewQ) > 0) { bc = aoO.signature; bc2 = aoO.Oi(); ab.i("MicroMsg.SnsUserUI", "contact:user[%s] id[%d] nickname[%s]", aoO.field_username, Integer.valueOf((int) aoO.ewQ), bc2); } this.rCT = new SnsUIAction(this); this.rCT.a(this.ryC, this.igi, bc2, bc, this.ryD, this.rjn, this.ryE); SnsUIAction snsUIAction = this.rCT; AnonymousClass13 anonymousClass13 = new com.tencent.mm.plugin.sns.ui.SnsUIAction.a() { public final void cuh() { AppMethodBeat.i(39795); if (SnsUserUI.this.rCU == null) { SnsUserUI.this.rCU = af.cnv(); } com.tencent.mm.plugin.sns.model.am.a b = SnsUserUI.this.rCU; String c = SnsUserUI.this.igi; SnsUserUI.this.ryD; b.b(2, c, SnsUserUI.this.rjn, SnsUserUI.this.ryE); af.bCo().postDelayed(SnsUserUI.this.rCZ, 3000); AppMethodBeat.o(39795); } public final ListView getSnsListView() { AppMethodBeat.i(39796); ListView listView = (ListView) SnsUserUI.this.findViewById(R.id.eii); AppMethodBeat.o(39796); return listView; } public final View cui() { AppMethodBeat.i(39797); View findViewById = SnsUserUI.this.findViewById(R.id.um); AppMethodBeat.o(39797); return findViewById; } public final View getMaskView() { AppMethodBeat.i(39798); View findViewById = SnsUserUI.this.findViewById(R.id.el6); AppMethodBeat.o(39798); return findViewById; } public final MMPullDownView cuj() { AppMethodBeat.i(39799); MMPullDownView mMPullDownView = (MMPullDownView) SnsUserUI.this.findViewById(R.id.avx); AppMethodBeat.o(39799); return mMPullDownView; } public final int getType() { return 2; } public final void b(int i, List<Integer> list, List<Integer> list2) { as a; AppMethodBeat.i(39800); if (!(i == -1 || SnsUserUI.this.rCS == null)) { a = SnsUserUI.this.rCS; if (a.rvw != null) { at atVar = a.rvw; com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (!(DK == null || DK.cqu().xfI == null || atVar.list.size() <= 0)) { atVar.list.add(1, DK); atVar.ctM(); atVar.ctN(); } } } if (!(SnsUserUI.this.rCS == null || list == null || list2 == null)) { a = SnsUserUI.this.rCS; if (a.rvw != null) { if (list == null || list2 == null || list.size() + list2.size() == 0) { AppMethodBeat.o(39800); return; } int i2; com.tencent.mm.plugin.sns.storage.n nVar; at atVar2 = a.rvw; if (!(list == null || list.size() == 0)) { ab.d("MicroMsg.SnsSelfHelper", "remove Items"); for (Integer intValue : list) { int intValue2 = intValue.intValue(); int size = atVar2.list.size(); for (i2 = 1; i2 < size; i2++) { nVar = (com.tencent.mm.plugin.sns.storage.n) atVar2.list.get(i2); if (nVar != null && nVar.reX == intValue2) { atVar2.list.remove(i2); break; } } } } if (!(list2 == null || list2.size() == 0)) { ab.d("MicroMsg.SnsSelfHelper", "change Items"); LinkedList linkedList = new LinkedList(); i2 = 1; while (i2 < atVar2.list.size()) { nVar = (com.tencent.mm.plugin.sns.storage.n) atVar2.list.get(i2); if (nVar != null) { for (Integer intValue3 : list2) { int intValue4 = intValue3.intValue(); if (nVar.reX == intValue4) { ab.d("MicroMsg.SnsSelfHelper", "update list localId ".concat(String.valueOf(intValue4))); atVar2.list.remove(i2); linkedList.add(af.cnF().DK(intValue4)); i2--; break; } } } i2++; } Iterator it = linkedList.iterator(); while (it.hasNext()) { atVar2.list.add((com.tencent.mm.plugin.sns.storage.n) it.next()); } } atVar2.ctM(); atVar2.ctN(); } } AppMethodBeat.o(39800); } public final boolean cuk() { return false; } public final void cul() { AppMethodBeat.i(39801); com.tencent.mm.plugin.sns.model.am.a b = SnsUserUI.this.rCU; String c = SnsUserUI.this.igi; SnsUserUI.this.ryD; b.a(2, c, SnsUserUI.this.rjn, SnsUserUI.this.ryE); AppMethodBeat.o(39801); } public final void cum() { } public final void Eh(int i) { AppMethodBeat.i(39802); ab.i("MicroMsg.SnsUserUI", "onListViewScoll %s", Integer.valueOf(i)); if (i == 2) { WXHardCoderJNI.stopPerformance(WXHardCoderJNI.hcSNSUserScrollEnable, SnsUserUI.this.ehv); SnsUserUI.this.ehv = WXHardCoderJNI.startPerformance(WXHardCoderJNI.hcSNSUserScrollEnable, WXHardCoderJNI.hcSNSUserScrollDelay, WXHardCoderJNI.hcSNSUserScrollCPU, WXHardCoderJNI.hcSNSUserScrollIO, WXHardCoderJNI.hcSNSUserScrollThr ? Process.myTid() : 0, WXHardCoderJNI.hcSNSUserScrollTimeout, 704, WXHardCoderJNI.hcSNSUserScrollAction, "MicroMsg.SnsUserUI"); ab.i("MicroMsg.SnsUserUI", "summer hardcoder sns startPerformance [%s]", Integer.valueOf(SnsUserUI.this.ehv)); } AppMethodBeat.o(39802); } public final void ad(int i, boolean z) { Object obj = null; AppMethodBeat.i(39803); if (SnsUserUI.this.rCS != null) { as a = SnsUserUI.this.rCS; if (a.rvw != null) { at atVar = a.rvw; com.tencent.mm.plugin.sns.storage.n DK = af.cnF().DK(i); if (DK == null || DK.cqu().xfI == null || atVar.list.size() <= 0) { AppMethodBeat.o(39803); return; } for (int i2 = 0; i2 < atVar.list.size(); i2++) { if (((com.tencent.mm.plugin.sns.storage.n) atVar.list.get(i2)).cqU() == DK.cqU()) { obj = 1; atVar.list.remove(i2); break; } } if (obj != null) { atVar.list.add(DK); atVar.ctM(); atVar.ctN(); } } } AppMethodBeat.o(39803); } public final void ln(boolean z) { } public final void fA(int i, int i2) { AppMethodBeat.i(39804); if (i2 <= 0) { SnsUserUI.i(SnsUserUI.this); AppMethodBeat.o(39804); return; } SnsUserUI.a(SnsUserUI.this, i, i2); AppMethodBeat.o(39804); } }; this.rCV = anonymousClass13; snsUIAction.rBP = anonymousClass13; this.rCT.onCreate(); getIntent().setExtrasClassLoader(getClass().getClassLoader()); initView(); com.tencent.mm.sdk.b.a.xxA.c(this.hAA); AppMethodBeat.o(39815); return; } finish(); AppMethodBeat.o(39815); } public void onDestroy() { AppMethodBeat.i(39816); af.bCo().removeCallbacks(this.rCZ); this.ryx = true; com.tencent.mm.sdk.b.a.xxA.d(this.hAA); com.tencent.mm.modelsns.b u = com.tencent.mm.modelsns.b.u(getIntent()); if (u != null) { u.update(); u.ajK(); } if (!(this.rCT == null || this.rCT.tipDialog == null)) { this.rCT.tipDialog.dismiss(); this.rCT.tipDialog = null; } g.RQ(); if (g.RN().QY() && this.rCU != null) { this.rCU.a(this, this.rCV.getType()); } if (this.rCT != null) { this.rCT.onDestroy(); } super.onDestroy(); AppMethodBeat.o(39816); } public void onDrag() { AppMethodBeat.i(39817); super.onDrag(); AppMethodBeat.o(39817); } public final int getLayoutId() { return R.layout.aw6; } public void onResume() { AppMethodBeat.i(39818); this.fAq = bo.anT(); if (com.tencent.matrix.a.isInstalled() && com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class) != null) { com.tencent.matrix.trace.f.c cVar = ((com.tencent.matrix.trace.a) com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class)).bYx; if (cVar != null) { cVar.a(this.mnM); } } if (this.rCS != null) { this.rCS.notifyDataSetChanged(); } setRequestedOrientation(-1); if (this.rjn) { b(getString(R.string.emv), (int) R.raw.actionbar_list_icon, (OnMenuItemClickListener) new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { AppMethodBeat.i(39787); Intent intent = new Intent(); intent.setClass(SnsUserUI.this, SnsMsgUI.class); intent.putExtra("sns_msg_force_show_all", true); SnsUserUI.this.startActivityForResult(intent, 8); AppMethodBeat.o(39787); return true; } }); } else { enableOptionMenu(false); } setBackBtn(this.rzm, R.raw.actionbar_icon_dark_back); if (this.rjn) { setMMTitle((int) R.string.enj); } else { CharSequence Oj; ab.d("MicroMsg.SnsUserUI", "SnsUserUI, userName:%s, title:%s", this.igi, this.rCT.title); ad aoO = af.cnt().aoO(this.igi); if (aoO != null) { ab.d("MicroMsg.SnsUserUI", "SnsUserUI, contact is not null"); Oj = aoO.Oj(); } else { ab.d("MicroMsg.SnsUserUI", "SnsUserUI, contact is null, title:%s", this.rCT.title); Oj = this.rCT.title; } setMMTitle(i.K(Oj)); } this.rCT.onResume(); super.onResume(); AppMethodBeat.o(39818); } public void onPause() { AppMethodBeat.i(39819); WXHardCoderJNI.stopPerformance(WXHardCoderJNI.hcSNSUserScrollEnable, this.ehv); this.ehv = 0; this.rCT.onPause(); super.onPause(); if (com.tencent.matrix.a.isInstalled() && com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class) != null) { com.tencent.matrix.trace.f.c cVar = ((com.tencent.matrix.trace.a) com.tencent.matrix.a.yK().F(com.tencent.matrix.trace.a.class)).bYx; if (cVar != null) { cVar.b(this.mnM); } } this.fAq = bo.anT() > this.fAq ? bo.anT() - this.fAq : 1; WXHardCoderJNI.reportFPS(704, WXHardCoderJNI.hcSNSUserScrollAction, 1, this.eEO, this.fAq); this.eEO = 0; this.fAq = 0; AppMethodBeat.o(39819); } public final void initView() { AppMethodBeat.i(39820); this.rCW = (RelativeLayout) findViewById(R.id.el7); this.rCX = (TextView) findViewById(R.id.el8); this.rCW.post(new Runnable() { public final void run() { AppMethodBeat.i(39806); LayoutParams layoutParams = new LayoutParams(-1, -2); layoutParams.topMargin = x.al(SnsUserUI.this) + SnsUserUI.this.getResources().getDimensionPixelSize(R.dimen.di); SnsUserUI.this.rCW.setLayoutParams(layoutParams); AppMethodBeat.o(39806); } }); this.rCS = new as(this, new a() { public final void fw(int i, int i2) { AppMethodBeat.i(39807); super.fw(i, i2); AppMethodBeat.o(39807); } }, this.igi, new as.c() { }); this.rCT.nDp.setAdapter(this.rCS); this.rCT.nDp.setOnItemClickListener(new OnItemClickListener() { public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { } }); this.rCT.nDp.postDelayed(new Runnable() { public final void run() { AppMethodBeat.i(39786); if (SnsUserUI.this.ryx) { ab.w("MicroMsg.SnsUserUI", "too fast that it finish"); AppMethodBeat.o(39786); return; } SnsUserUI.this.rCU.a(SnsUserUI.this.rCV.getType(), SnsUserUI.this.igi, SnsUserUI.this); if (SnsUserUI.this.rCV.getType() == 1 && SnsUserUI.this.rCV.cuk()) { af.cnv().B(af.cnM().qMB, -1); } if (!SnsUserUI.this.rCV.cuk()) { com.tencent.mm.plugin.sns.model.am.a b = SnsUserUI.this.rCU; int type = SnsUserUI.this.rCV.getType(); String c = SnsUserUI.this.igi; SnsUserUI.this.ryD; b.a(type, c, SnsUserUI.this.rjn, SnsUserUI.this.ryE); } AppMethodBeat.o(39786); } }, 500); setBackBtn(this.rzm, R.raw.actionbar_icon_dark_back); AppMethodBeat.o(39820); } public final void a(boolean z, boolean z2, String str, boolean z3, boolean z4, int i, long j, String str2) { AppMethodBeat.i(39821); if (this.rCS != null) { this.rCS.rmL = str; if (str.compareTo(this.rCS.lQD) < 0) { ab.i("MicroMsg.SnsUserUI", "onFpSetSize addsize %s %s isNeedNP %s", str, this.rCS.lQD, Boolean.valueOf(z)); this.rCS.ctK(); } else { ab.i("MicroMsg.SnsUserUI", "onFpSetSize addsize passed %s %s isNeedNP %s", str, this.rCS.lQD, Boolean.valueOf(z)); } this.rCS.crP(); } if ((z4 || !bo.isNullOrNil(str2)) && !this.ryC.equals(this.igi)) { this.rCT.koC = true; this.rCT.bf(i, str2); } else { if (this.ryC.equals(this.igi) && j != 0) { g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_RECENT_LIMITED_ID_LONG_SYNC, Long.valueOf(j)); this.rCS.kI(j); } this.rCT.koC = z2; if (z2) { this.rCT.lc(false); } else if (z) { this.rCU.b(this.rCV.getType(), this.igi, this.rjn, this.ryE); } } if (z3) { this.rCT.qQt.cti(); } AppMethodBeat.o(39821); } public final void a(boolean z, String str, boolean z2, boolean z3, int i, long j, String str2) { AppMethodBeat.i(39822); af.bCo().removeCallbacks(this.rCZ); if (this.rCS != null) { this.rCS.rvv = z2; this.rCS.rmL = str; if (str.compareTo(this.rCS.lQD) < 0) { ab.i("MicroMsg.SnsUserUI", "onNpAddSize addsize %s %s", str, this.rCS.lQD); this.rCS.ctK(); } else { ab.i("MicroMsg.SnsUserUI", "onNpAddSize addsize passed %s %s", str, this.rCS.lQD); } this.rCS.crP(); } if (!z3 || this.ryC.equals(this.igi)) { if (this.ryC.equals(this.igi) && j != 0) { g.RQ(); g.RP().Ry().set(com.tencent.mm.storage.ac.a.USERINFO_SNS_RECENT_LIMITED_ID_LONG_SYNC, Long.valueOf(j)); this.rCS.kI(j); } this.rCT.koC = z; if (z) { this.rCT.lc(false); } AppMethodBeat.o(39822); return; } this.rCT.koC = true; this.rCT.bf(i, str2); AppMethodBeat.o(39822); } public final void xE(int i) { AppMethodBeat.i(39823); super.xE(i); if (VERSION.SDK_INT >= 21 && this.plv != null) { this.plv.setBackgroundColor(getWindow().getStatusBarColor()); com.tencent.mm.ui.statusbar.d.a(getWindow()); } AppMethodBeat.o(39823); } private void cuG() { AppMethodBeat.i(39824); if (com.tencent.mm.r.a.bH(this)) { AppMethodBeat.o(39824); return; } ab.d("MicroMsg.SnsUserUI", "summerper checkPermission checkCamera[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.CAMERA", 18, "", "")), bo.dpG(), this); if (com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.CAMERA", 18, "", "")) { ab.d("MicroMsg.SnsUserUI", "summerper checkPermission checkmicrophone[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.RECORD_AUDIO", 18, "", "")), bo.dpG(), this); if (com.tencent.mm.pluginsdk.permission.b.a(this, "android.permission.RECORD_AUDIO", 18, "", "")) { com.tencent.mm.pluginsdk.ui.tools.n.G(this.mController.ylL, new Intent()); AppMethodBeat.o(39824); return; } AppMethodBeat.o(39824); return; } AppMethodBeat.o(39824); } public void onBackPressed() { AppMethodBeat.i(39825); finish(); AppMethodBeat.o(39825); } public boolean supportNavigationSwipeBack() { AppMethodBeat.i(39826); boolean supportNavigationSwipeBack = super.supportNavigationSwipeBack(); AppMethodBeat.o(39826); return supportNavigationSwipeBack; } public void onActivityResult(int i, int i2, Intent intent) { AppMethodBeat.i(39827); ab.i("MicroMsg.SnsUserUI", "on activity result, %d %d", Integer.valueOf(i), Integer.valueOf(i2)); if (5985 == i && i2 == -1) { finish(); AppMethodBeat.o(39827); return; } super.onActivityResult(i, i2, intent); this.rCT.onActivityResult(i, i2, intent); AppMethodBeat.o(39827); } public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) { AppMethodBeat.i(39828); if (iArr == null || iArr.length <= 0) { ab.i("MicroMsg.SnsUserUI", "onRequestPermissionsResult grantResults length 0. requestCode[%d], tid[%d]", Integer.valueOf(i), Long.valueOf(Thread.currentThread().getId())); AppMethodBeat.o(39828); return; } ab.i("MicroMsg.SnsUserUI", "onRequestPermissionsResult requestCode[%d],grantResults[%d] tid[%d]", Integer.valueOf(i), Integer.valueOf(iArr[0]), Long.valueOf(Thread.currentThread().getId())); switch (i) { case 18: if (iArr[0] != 0) { int i2 = "android.permission.CAMERA".equals(strArr[0]) ? R.string.dbs : R.string.dc0; if (iArr[0] != 0) { com.tencent.mm.ui.base.h.a((Context) this, getString(i2), getString(R.string.dc8), getString(R.string.ckr), getString(R.string.or), false, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { AppMethodBeat.i(39791); dialogInterface.dismiss(); SnsUserUI.this.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS")); AppMethodBeat.o(39791); } }, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { AppMethodBeat.i(39792); dialogInterface.dismiss(); AppMethodBeat.o(39792); } }); break; } } cuG(); AppMethodBeat.o(39828); return; break; } AppMethodBeat.o(39828); } static /* synthetic */ void i(SnsUserUI snsUserUI) { AppMethodBeat.i(39829); snsUserUI.rCW.setVisibility(8); AppMethodBeat.o(39829); } static /* synthetic */ void a(SnsUserUI snsUserUI, int i, int i2) { int i3; AppMethodBeat.i(39830); as asVar = snsUserUI.rCS; if (asVar.rgf.get(Integer.valueOf(i)) == null) { i3 = -1; } else { i3 = ((Integer) asVar.rgf.get(Integer.valueOf(i))).intValue(); } ab.d("MicroMsg.SnsUserUI", "displayYearTip position:%d alpha:%d realPos:%d", Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3)); if (i3 != -1) { Object item = snsUserUI.rCS.getItem(i3); if (item != null && (item instanceof com.tencent.mm.plugin.sns.storage.n)) { float f = ((float) i2) / 100.0f; if (f != snsUserUI.rCW.getAlpha()) { snsUserUI.rCW.setAlpha(f); } snsUserUI.rCW.setVisibility(0); com.tencent.mm.plugin.sns.storage.n nVar = (com.tencent.mm.plugin.sns.storage.n) item; if (snsUserUI.rCY != nVar.field_head / Downloads.MIN_WAIT_FOR_NETWORK) { snsUserUI.rCY = nVar.field_head / Downloads.MIN_WAIT_FOR_NETWORK; snsUserUI.rCX.setText(String.format(snsUserUI.getResources().getString(R.string.eqj), new Object[]{Integer.valueOf(snsUserUI.rCY)})); } } } AppMethodBeat.o(39830); } static /* synthetic */ void b(SnsUserUI snsUserUI, final int i) { AppMethodBeat.i(39832); com.tencent.mm.ui.base.h.a((Context) snsUserUI, (int) R.string.p5, (int) R.string.tz, (int) R.string.s6, (int) R.string.or, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { AppMethodBeat.i(39789); af.cnF().DL(i); SnsUserUI.this.rCS.crP(); AppMethodBeat.o(39789); } }, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { } }); AppMethodBeat.o(39832); } }
39,193
0.492613
0.471511
902
42.449001
32.981636
382
false
false
0
0
0
0
0
0
0.921286
false
false
15
5add39a36ba1a84b6f265d98452baee6de1f3251
25,486,335,983,472
86c6870d54d045a5d7e37c2e0ba19079672de211
/app/src/main/java/com/example/xiaolitongxue/wieying/view/fragment/BaseFragment.java
d4ccaf1680e694c095f94521163864b2f4bb32b0
[]
no_license
MyWeiYing/MyWeiYing
https://github.com/MyWeiYing/MyWeiYing
9998e08559772db294fcb8a67984a0a5380cdde2
a6840a209df61c537a657543c2923339fca3e88c
refs/heads/master
2020-03-17T16:59:29.028000
2018-05-25T08:32:03
2018-05-25T08:32:03
133,770,493
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.xiaolitongxue.wieying.view.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.xiaolitongxue.wieying.presenter.BasePresenter; import com.example.xiaolitongxue.wieying.view.interfaces.BaseIView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by xiaolitongxue on 2018/5/16. */ //bbb public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseIView{ public P p; Unbinder unbinder; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = initView(inflater,container); unbinder = ButterKnife.bind(this, view); p = newPresenter(); Log.e("myMessage",""+p); Log.e("myMessage",""+p); if (p!=null){ p.attachView(this); } findViewByIdView(view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(savedInstanceState); } protected abstract View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container); abstract void initData( @Nullable Bundle savedInstanceState); protected abstract void findViewByIdView(View view); abstract P newPresenter(); public P getPresenter(){ return p; } @Override public void onDestroy() { super.onDestroy(); p.detachView(); unbinder.unbind(); } }
UTF-8
Java
1,826
java
BaseFragment.java
Java
[ { "context": "e;\nimport butterknife.Unbinder;\n\n/**\n * Created by xiaolitongxue on 2018/5/16.\n */\n//bbb\npublic abstract class Bas", "end": 558, "score": 0.999423623085022, "start": 545, "tag": "USERNAME", "value": "xiaolitongxue" } ]
null
[]
package com.example.xiaolitongxue.wieying.view.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.xiaolitongxue.wieying.presenter.BasePresenter; import com.example.xiaolitongxue.wieying.view.interfaces.BaseIView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by xiaolitongxue on 2018/5/16. */ //bbb public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseIView{ public P p; Unbinder unbinder; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = initView(inflater,container); unbinder = ButterKnife.bind(this, view); p = newPresenter(); Log.e("myMessage",""+p); Log.e("myMessage",""+p); if (p!=null){ p.attachView(this); } findViewByIdView(view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(savedInstanceState); } protected abstract View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container); abstract void initData( @Nullable Bundle savedInstanceState); protected abstract void findViewByIdView(View view); abstract P newPresenter(); public P getPresenter(){ return p; } @Override public void onDestroy() { super.onDestroy(); p.detachView(); unbinder.unbind(); } }
1,826
0.711391
0.70701
61
28.934425
26.824181
132
false
false
0
0
0
0
0
0
0.655738
false
false
15
dfc4ac2be92bc36f555ac333d76c79c304034812
28,303,834,543,524
1d8d9341d5a2184dad75defe239c73d727e050d8
/src/main/java/cl/servel/gasto/model/Configuracion.java
5285f7bd514fec19f9b76291dfd24a39b4408511
[]
no_license
carboy35/model
https://github.com/carboy35/model
e9f4edd8ab7d6f346704fa5eefa174e2a1baaaf4
cd30834e6306e059e410b9c1386e3f5de0f45fdd
refs/heads/master
2020-12-10T00:08:49.060000
2020-01-12T20:31:34
2020-01-12T20:31:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cl.servel.gasto.model; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @AllArgsConstructor @NoArgsConstructor @ToString @Builder public class Configuracion implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private Integer conId; private Integer idEveEventoEleccionario; private Integer idTpoEleccion; private Date created; private Date modified; private Boolean conEliminado; private String estado; private Integer idTpoEvento; private Boolean activo; private boolean estadoCarga; private String nombreTipoEvento; private String nombreTipoEleccion; private Integer dexId; }
UTF-8
Java
764
java
Configuracion.java
Java
[]
null
[]
package cl.servel.gasto.model; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @AllArgsConstructor @NoArgsConstructor @ToString @Builder public class Configuracion implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private Integer conId; private Integer idEveEventoEleccionario; private Integer idTpoEleccion; private Date created; private Date modified; private Boolean conEliminado; private String estado; private Integer idTpoEvento; private Boolean activo; private boolean estadoCarga; private String nombreTipoEvento; private String nombreTipoEleccion; private Integer dexId; }
764
0.807592
0.806283
36
20.222221
14.689587
60
false
false
0
0
0
0
0
0
1.055556
false
false
15
f714534bfa7de2b4287dfeb708bb851c3d1f2994
18,554,258,776,821
0cb56e3f4bb4f19653e1ec27e7e9e1a712f4d5ea
/src/main/java/tech/units/tck/tests/spi/ServicesTest.java
a566335a3bcca667f6edf357e8ad166dff4a1524
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
unitsofmeasurement/unit-tck
https://github.com/unitsofmeasurement/unit-tck
1d193685ea7ef62283b543d2b8b1e58eb0232d81
8a04d1e23c926311c3704fcf2294e72c0d67ad64
refs/heads/master
2023-08-26T10:00:13.414000
2023-07-07T20:05:56
2023-07-07T20:05:56
18,568,544
6
6
NOASSERTION
false
2023-02-25T13:28:51
2014-04-08T17:46:05
2022-02-22T12:59:24
2023-02-25T13:12:32
592
5
5
3
Java
false
false
/* * Units of Measurement TCK * Copyright © 2005-2023, Jean-Marie Dautelle, Werner Keil, Otavio Santana. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package tech.units.tck.tests.spi; import static org.testng.AssertJUnit.assertNotNull; import static tech.units.tck.TCKRunner.SECTION_PREFIX; import static tech.units.tck.TCKRunner.SPEC_ID; import static tech.units.tck.TCKRunner.SPEC_VERSION; import static tech.units.tck.util.TestGroups.SPI; import static tech.units.tck.util.TestUtils.NUM_OF_BINARY_PREFIXES; import static tech.units.tck.util.TestUtils.NUM_OF_METRIC_PREFIXES; import static javax.measure.spi.FormatService.FormatType.UNIT_FORMAT; import static javax.measure.spi.FormatService.FormatType.QUANTITY_FORMAT; import java.util.Set; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertFalse; import javax.measure.BinaryPrefix; import javax.measure.MetricPrefix; import javax.measure.spi.FormatService; import javax.measure.spi.ServiceProvider; import javax.measure.spi.SystemOfUnitsService; import org.jboss.test.audit.annotations.SpecAssertion; import org.jboss.test.audit.annotations.SpecVersion; import org.testng.annotations.Test; /** * Test class for Services. * * @author Werner Keil * @version 2.2, July 7, 2023 * @since 1.0 */ @SpecVersion(spec = SPEC_ID, version = SPEC_VERSION) public class ServicesTest { private static final String SECTION_NUM = "5.4"; private static final String DESCRIPTION = SECTION_NUM + " Services"; // ************************ 5.4 Services // ************************ /** * Access available FormatServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A01") public void testFormatService() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); } } // ************************ 5.4 Services // ************************ /** * Access available QuantityFormats in FormatServices. * @since 2.1 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A02") public void testFormatServiceQuantityFormatsAvailable() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available QuantityFormat names are null", service.getAvailableFormatNames(QUANTITY_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available QuantityFormat names found", service.getAvailableFormatNames(QUANTITY_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access default QuantityFormat in FormatServices. * @since 2.1 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A03") public void testFormatServiceQuantityFormatsDefault() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Default QuantityFormat is null", service.getUnitFormat()); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available QuantityFormat names are null", service.getAvailableFormatNames(QUANTITY_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available QuantityFormat names found", service.getAvailableFormatNames(QUANTITY_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access available UnitFormats in FormatServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A04") public void testFormatServiceUnitFormatsAvailable() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available UnitFormat names are null", service.getAvailableFormatNames(UNIT_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available UnitFormat names found", service.getAvailableFormatNames(UNIT_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access default UnitFormats in FormatServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A05") public void testFormatServiceUnitFormatsDefault() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Default UnitFormat is null", service.getUnitFormat()); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available UnitFormat names are null", service.getAvailableFormatNames(UNIT_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available UnitFormat names found", service.getAvailableFormatNames(UNIT_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access available SystemOfUnitsServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A06") public void testSystemOfUnitsService() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); } } // ************************ 5.4 Services // ************************ /** * Access default SystemOfUnits in SystemOfUnitsService. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A07") public void testSystemOfUnitsServiceDefaultSystem() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Default SystemOfUnits is null", service.getSystemOfUnits()); } } // ************************ 5.4 Services // ************************ /** * Access available Systems OfUnits in SystemOfUnitsService. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A08") public void testSystemOfUnitsServiceAvailableSystems() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available SystemOfUnits are null", service.getAvailableSystemsOfUnits()); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available SystemOfUnits found", service.getAvailableSystemsOfUnits().isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access Binary Prefixes in SystemOfUnitsService. * @since 2.0 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A09") public void testSystemOfUnitsServicePrefixBinary() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); final SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); Set<BinaryPrefix> prefixes = service.getPrefixes(BinaryPrefix.class); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Binary Prefixes are null", prefixes); assertFalse(SECTION_PREFIX + SECTION_NUM + " No Binary Prefixes found", prefixes.isEmpty()); assertEquals(prefixes.size(), NUM_OF_BINARY_PREFIXES, SECTION_PREFIX + SECTION_NUM + " Wrong Number of Binary Prefixes"); } } // ************************ 5.4 Services // ************************ /** * Access Metric Prefixes in SystemOfUnitsService. * @since 2.0 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A10") public void testSystemOfUnitsServicePrefixMetric() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); final SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); Set<MetricPrefix> prefixes = service.getPrefixes(MetricPrefix.class); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Metric Prefixes are null", prefixes); assertFalse(SECTION_PREFIX + SECTION_NUM + " No Metric Prefixes found", prefixes.isEmpty()); assertEquals(prefixes.size(), NUM_OF_METRIC_PREFIXES, SECTION_PREFIX + SECTION_NUM + " Wrong Number of Metric Prefixes"); } } }
UTF-8
Java
11,633
java
ServicesTest.java
Java
[ { "context": "Units of Measurement TCK\n * Copyright © 2005-2023, Jean-Marie Dautelle, Werner Keil, Otavio Santana.\n *\n * All rights re", "end": 76, "score": 0.9997642636299133, "start": 57, "tag": "NAME", "value": "Jean-Marie Dautelle" }, { "context": "TCK\n * Copyright © 2005-2023, Jean-Marie Dautelle, Werner Keil, Otavio Santana.\n *\n * All rights reserved.\n *\n *", "end": 89, "score": 0.9998306035995483, "start": 78, "tag": "NAME", "value": "Werner Keil" }, { "context": "ght © 2005-2023, Jean-Marie Dautelle, Werner Keil, Otavio Santana.\n *\n * All rights reserved.\n *\n * Redistribution ", "end": 105, "score": 0.9998448491096497, "start": 91, "tag": "NAME", "value": "Otavio Santana" }, { "context": "t;\n\n/**\n * Test class for Services.\n * \n * @author Werner Keil\n * @version 2.2, July 7, 2023\n * @since 1.0\n */\n@", "end": 2723, "score": 0.999808669090271, "start": 2712, "tag": "NAME", "value": "Werner Keil" } ]
null
[]
/* * Units of Measurement TCK * Copyright © 2005-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package tech.units.tck.tests.spi; import static org.testng.AssertJUnit.assertNotNull; import static tech.units.tck.TCKRunner.SECTION_PREFIX; import static tech.units.tck.TCKRunner.SPEC_ID; import static tech.units.tck.TCKRunner.SPEC_VERSION; import static tech.units.tck.util.TestGroups.SPI; import static tech.units.tck.util.TestUtils.NUM_OF_BINARY_PREFIXES; import static tech.units.tck.util.TestUtils.NUM_OF_METRIC_PREFIXES; import static javax.measure.spi.FormatService.FormatType.UNIT_FORMAT; import static javax.measure.spi.FormatService.FormatType.QUANTITY_FORMAT; import java.util.Set; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertFalse; import javax.measure.BinaryPrefix; import javax.measure.MetricPrefix; import javax.measure.spi.FormatService; import javax.measure.spi.ServiceProvider; import javax.measure.spi.SystemOfUnitsService; import org.jboss.test.audit.annotations.SpecAssertion; import org.jboss.test.audit.annotations.SpecVersion; import org.testng.annotations.Test; /** * Test class for Services. * * @author <NAME> * @version 2.2, July 7, 2023 * @since 1.0 */ @SpecVersion(spec = SPEC_ID, version = SPEC_VERSION) public class ServicesTest { private static final String SECTION_NUM = "5.4"; private static final String DESCRIPTION = SECTION_NUM + " Services"; // ************************ 5.4 Services // ************************ /** * Access available FormatServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A01") public void testFormatService() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); } } // ************************ 5.4 Services // ************************ /** * Access available QuantityFormats in FormatServices. * @since 2.1 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A02") public void testFormatServiceQuantityFormatsAvailable() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available QuantityFormat names are null", service.getAvailableFormatNames(QUANTITY_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available QuantityFormat names found", service.getAvailableFormatNames(QUANTITY_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access default QuantityFormat in FormatServices. * @since 2.1 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A03") public void testFormatServiceQuantityFormatsDefault() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Default QuantityFormat is null", service.getUnitFormat()); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available QuantityFormat names are null", service.getAvailableFormatNames(QUANTITY_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available QuantityFormat names found", service.getAvailableFormatNames(QUANTITY_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access available UnitFormats in FormatServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A04") public void testFormatServiceUnitFormatsAvailable() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available UnitFormat names are null", service.getAvailableFormatNames(UNIT_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available UnitFormat names found", service.getAvailableFormatNames(UNIT_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access default UnitFormats in FormatServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A05") public void testFormatServiceUnitFormatsDefault() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); FormatService service = provider.getFormatService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": FormatService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Default UnitFormat is null", service.getUnitFormat()); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available UnitFormat names are null", service.getAvailableFormatNames(UNIT_FORMAT)); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available UnitFormat names found", service.getAvailableFormatNames(UNIT_FORMAT).isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access available SystemOfUnitsServices. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A06") public void testSystemOfUnitsService() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); } } // ************************ 5.4 Services // ************************ /** * Access default SystemOfUnits in SystemOfUnitsService. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A07") public void testSystemOfUnitsServiceDefaultSystem() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Default SystemOfUnits is null", service.getSystemOfUnits()); } } // ************************ 5.4 Services // ************************ /** * Access available Systems OfUnits in SystemOfUnitsService. */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A08") public void testSystemOfUnitsServiceAvailableSystems() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Available SystemOfUnits are null", service.getAvailableSystemsOfUnits()); assertFalse(SECTION_PREFIX + SECTION_NUM + " No available SystemOfUnits found", service.getAvailableSystemsOfUnits().isEmpty()); } } // ************************ 5.4 Services // ************************ /** * Access Binary Prefixes in SystemOfUnitsService. * @since 2.0 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A09") public void testSystemOfUnitsServicePrefixBinary() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); final SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); Set<BinaryPrefix> prefixes = service.getPrefixes(BinaryPrefix.class); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Binary Prefixes are null", prefixes); assertFalse(SECTION_PREFIX + SECTION_NUM + " No Binary Prefixes found", prefixes.isEmpty()); assertEquals(prefixes.size(), NUM_OF_BINARY_PREFIXES, SECTION_PREFIX + SECTION_NUM + " Wrong Number of Binary Prefixes"); } } // ************************ 5.4 Services // ************************ /** * Access Metric Prefixes in SystemOfUnitsService. * @since 2.0 */ @Test(groups = { SPI }, description = DESCRIPTION) @SpecAssertion(section = SECTION_NUM, id = "54-A10") public void testSystemOfUnitsServicePrefixMetric() { for (ServiceProvider provider : ServiceProvider.available()) { assertNotNull(SECTION_PREFIX + SECTION_NUM + ": ServiceProvider is null", provider); final SystemOfUnitsService service = provider.getSystemOfUnitsService(); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": SystemOfUnitsService is null", service); Set<MetricPrefix> prefixes = service.getPrefixes(MetricPrefix.class); assertNotNull(SECTION_PREFIX + SECTION_NUM + ": Metric Prefixes are null", prefixes); assertFalse(SECTION_PREFIX + SECTION_NUM + " No Metric Prefixes found", prefixes.isEmpty()); assertEquals(prefixes.size(), NUM_OF_METRIC_PREFIXES, SECTION_PREFIX + SECTION_NUM + " Wrong Number of Metric Prefixes"); } } }
11,602
0.713291
0.705296
252
45.15873
32.434772
124
false
false
0
0
0
0
0
0
2.003968
false
false
15
9522a078056aa05960c50c7105dd04ae3a364b5d
7,224,135,059,246
2e58e812c18eb47bd97fb7cd4063efc8309d0156
/src/eapli.base/base.core/src/main/java/eapli/base/ticket/application/GetTicketTaskInfoController.java
915a054cd6721a9438f0a72e2ff16de300947cfd
[ "MIT" ]
permissive
Joao-PP-Alves/isep-lapr4
https://github.com/Joao-PP-Alves/isep-lapr4
5d0d31df206fbdf599ddcf0aa6fac6d5251e3447
bff732dccb114a07f7f537dc4edd74fa579af78b
refs/heads/master
2023-07-14T09:55:51.507000
2021-06-20T22:35:32
2021-06-20T22:35:32
399,133,407
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eapli.base.ticket.application; import eapli.base.infrastructure.persistence.PersistenceContext; import eapli.base.ticket.repositories.TicketRepository; import eapli.base.usermanagement.domain.BaseRoles; import eapli.framework.infrastructure.authz.application.AuthorizationService; import eapli.framework.infrastructure.authz.application.AuthzRegistry; import java.util.Calendar; public class GetTicketTaskInfoController { private final AuthorizationService authz = AuthzRegistry.authorizationService(); private final TicketRepository ticketsRepo = PersistenceContext.repositories().tickets(); public void getTicketTaskInfo(int[] taskTypeAmount) { authz.ensureAuthenticatedUserHasAnyOf(BaseRoles.HRR, BaseRoles.ADMIN, BaseRoles.POWER_USER, BaseRoles.COLLABORATOR); Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); endDate.add(Calendar.HOUR_OF_DAY, 1); taskTypeAmount[0] = Long.valueOf(ticketsRepo.findPendingAmount()).intValue(); taskTypeAmount[1] = Long.valueOf(ticketsRepo.findExpiredAmount()).intValue(); taskTypeAmount[2] = Long.valueOf(ticketsRepo.findSoonToBeExpiredAmount(startDate, endDate)).intValue(); } }
UTF-8
Java
1,242
java
GetTicketTaskInfoController.java
Java
[]
null
[]
package eapli.base.ticket.application; import eapli.base.infrastructure.persistence.PersistenceContext; import eapli.base.ticket.repositories.TicketRepository; import eapli.base.usermanagement.domain.BaseRoles; import eapli.framework.infrastructure.authz.application.AuthorizationService; import eapli.framework.infrastructure.authz.application.AuthzRegistry; import java.util.Calendar; public class GetTicketTaskInfoController { private final AuthorizationService authz = AuthzRegistry.authorizationService(); private final TicketRepository ticketsRepo = PersistenceContext.repositories().tickets(); public void getTicketTaskInfo(int[] taskTypeAmount) { authz.ensureAuthenticatedUserHasAnyOf(BaseRoles.HRR, BaseRoles.ADMIN, BaseRoles.POWER_USER, BaseRoles.COLLABORATOR); Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); endDate.add(Calendar.HOUR_OF_DAY, 1); taskTypeAmount[0] = Long.valueOf(ticketsRepo.findPendingAmount()).intValue(); taskTypeAmount[1] = Long.valueOf(ticketsRepo.findExpiredAmount()).intValue(); taskTypeAmount[2] = Long.valueOf(ticketsRepo.findSoonToBeExpiredAmount(startDate, endDate)).intValue(); } }
1,242
0.785829
0.782609
28
43.357143
37.822155
124
false
false
0
0
0
0
0
0
0.75
false
false
15
9771ad8d690a43ff1de0ba4491513055b2820288
33,947,421,553,161
14cb5bc44b8f1fec92fd7d6cd7eb4b8ba7ad9d42
/src/main/java/org/folio/search/model/SystemUser.java
9188b277318fae3745e0e359de8f7e4360cffeed
[ "Apache-2.0" ]
permissive
craigmcnally/mod-search
https://github.com/craigmcnally/mod-search
896f8853ea751939ccd5d61c4238e13f71a476e4
cf80aab4cb579260105ba1e0659aa2d127d7e478
refs/heads/master
2023-08-22T19:53:32.101000
2021-10-19T11:48:21
2021-10-19T11:48:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.folio.search.model; import lombok.Builder; import lombok.Getter; import lombok.With; @Getter @Builder public class SystemUser { private final String username; @With private final String token; private final String okapiUrl; private final String tenantId; }
UTF-8
Java
281
java
SystemUser.java
Java
[]
null
[]
package org.folio.search.model; import lombok.Builder; import lombok.Getter; import lombok.With; @Getter @Builder public class SystemUser { private final String username; @With private final String token; private final String okapiUrl; private final String tenantId; }
281
0.775801
0.775801
15
17.733334
12.195445
32
false
false
0
0
0
0
0
0
0.533333
false
false
15
52db3a1ba2899bcc630b48b846a4c5311ad04975
35,124,242,587,024
d6fc6eb6fbdff2051f12359fe0faffae260d955d
/src/main/java/gluttonmod/cards/ShedFat.java
f4e01c1f69091d76ef80d046f4140d6628fb3dc5
[]
no_license
HypoSoc/GluttonMod
https://github.com/HypoSoc/GluttonMod
073fadab791826fa5fb99dc069e120b66b9fc779
89056a494f2a720f89ceeaf5fcb15d65ae80d145
refs/heads/master
2020-04-05T14:56:28.577000
2018-12-14T03:53:37
2018-12-14T03:53:37
156,947,382
1
1
null
false
2018-11-10T12:52:13
2018-11-10T04:28:45
2018-11-10T05:09:50
2018-11-10T05:09:49
3,758
0
1
1
Java
false
null
package gluttonmod.cards; import com.evacipated.cardcrawl.mod.stslib.fields.cards.AbstractCard.AlwaysRetainField; import com.megacrit.cardcrawl.actions.common.DrawCardAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInDiscardAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import gluttonmod.actions.ShedFatAction; public class ShedFat extends AbstractGluttonCard { public static final String ID = "ShedFat"; public static final String NAME = "Shed Fat"; public static final String DESCRIPTION = "Exhaust your hand. Draw that many cards plus !M!. NL Exhaust."; public static final String UPGRADE_DESCRIPTION = "Retain. Exhaust your hand. Draw that many cards plus !M!. NL Exhaust."; public static final String IMG_PATH = "cards/shedfat.png"; private static final CardType TYPE = CardType.SKILL; private static final CardRarity RARITY = CardRarity.UNCOMMON; private static final CardTarget TARGET = CardTarget.SELF; private static final int COST = 0; private static final int MAGIC = 1; public ShedFat() { super(ID, NAME, IMG_PATH, COST, DESCRIPTION, TYPE, RARITY, TARGET); this.baseMagicNumber = MAGIC; this.magicNumber = this.baseMagicNumber; this.exhaust = true; } public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new ShedFatAction(this.magicNumber)); } public AbstractCard makeCopy() { return new ShedFat(); } public void upgrade() { if (!this.upgraded) { upgradeName(); AlwaysRetainField.alwaysRetain.set(this, true); this.retain = true; this.rawDescription = UPGRADE_DESCRIPTION; initializeDescription(); } } }
UTF-8
Java
1,986
java
ShedFat.java
Java
[]
null
[]
package gluttonmod.cards; import com.evacipated.cardcrawl.mod.stslib.fields.cards.AbstractCard.AlwaysRetainField; import com.megacrit.cardcrawl.actions.common.DrawCardAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInDiscardAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import gluttonmod.actions.ShedFatAction; public class ShedFat extends AbstractGluttonCard { public static final String ID = "ShedFat"; public static final String NAME = "Shed Fat"; public static final String DESCRIPTION = "Exhaust your hand. Draw that many cards plus !M!. NL Exhaust."; public static final String UPGRADE_DESCRIPTION = "Retain. Exhaust your hand. Draw that many cards plus !M!. NL Exhaust."; public static final String IMG_PATH = "cards/shedfat.png"; private static final CardType TYPE = CardType.SKILL; private static final CardRarity RARITY = CardRarity.UNCOMMON; private static final CardTarget TARGET = CardTarget.SELF; private static final int COST = 0; private static final int MAGIC = 1; public ShedFat() { super(ID, NAME, IMG_PATH, COST, DESCRIPTION, TYPE, RARITY, TARGET); this.baseMagicNumber = MAGIC; this.magicNumber = this.baseMagicNumber; this.exhaust = true; } public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new ShedFatAction(this.magicNumber)); } public AbstractCard makeCopy() { return new ShedFat(); } public void upgrade() { if (!this.upgraded) { upgradeName(); AlwaysRetainField.alwaysRetain.set(this, true); this.retain = true; this.rawDescription = UPGRADE_DESCRIPTION; initializeDescription(); } } }
1,986
0.71148
0.710473
56
34.482143
29.991064
125
false
false
0
0
0
0
0
0
0.696429
false
false
15
01fe4423b47258ea9496551c36c21da66e97aa62
27,230,092,712,023
634de49aeb49dc4fcfc4c1dae7ab3b71110a6971
/app/src/main/java/com/pthomasdesigns/myhealth/MainActivity.java
b807c41e35bb1ddd8db96592d407f03ef37e83da
[]
no_license
pthomasdesigns/myHealth
https://github.com/pthomasdesigns/myHealth
f62a780d13de769893f111d9331c4aaaf0e24b8d
7a042cca7d3ee27ea86754b7b4a55cb0c6313a1a
refs/heads/master
2020-03-12T18:38:34.361000
2018-04-27T07:57:10
2018-04-27T07:57:10
130,765,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pthomasdesigns.myhealth; /** * Created by tthomas on 4/14/2018. */ import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.pthomasdesigns.myhealth.rest.model.UserInfo; import com.pthomasdesigns.myhealth.rest.service.RestClient; import org.parceler.Parcels; public class MainActivity extends AppCompatActivity { private static final String TAG = "MyHealth:MainActivity"; public static String PACKAGE_NAME = BuildConfig.APPLICATION_ID; public static final String FRAGMENT_ID = PACKAGE_NAME + ".FragmentId"; private DrawerLayout mDrawerLayout; private TextView mNavigationViewUserId; private NavigationView mNavigationView; private ActionBar mActionBar; private static UserInfo mUserInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setHomeAsUpIndicator(R.drawable.ic_menu); mActionBar.setTitle(R.string.app_name); mDrawerLayout = findViewById(R.id.drawer_layout); mNavigationView = findViewById(R.id.nav_view); mNavigationViewUserId = mNavigationView.getHeaderView(0).findViewById(R.id.nav_view_userid); mNavigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { startFragment(item.getItemId()); item.setChecked(true); mDrawerLayout.closeDrawers(); return true; } } ); if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); Parcelable pExtras = getIntent().getParcelableExtra(UserInfo.TAG); if (pExtras != null) { mUserInfo = Parcels.unwrap(pExtras); mNavigationViewUserId.setText(mUserInfo.getName()); } if (extras != null && extras.getInt(FRAGMENT_ID) != 0) { startFragment(extras.getInt(FRAGMENT_ID)); } else { startMainFragment(); } } else { mUserInfo = Parcels.unwrap(savedInstanceState.getParcelable(UserInfo.TAG)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } private void startFragment(int itemId) { switch(itemId) { case R.id.nav_visits: startVisitsFragment(); break; case R.id.nav_bills: startBillsFragment(); break; case R.id.nav_messages: startMessagesFragment(); break; case R.id.logout: finish(); break; default: startMainFragment(); break; } } @Override public void onBackPressed () { Fragment fragment = getSupportFragmentManager().findFragmentByTag(MainFragment.TAG); if (fragment != null && fragment.isVisible()) { finish(); } else { startMainFragmentAnimation(); } } private void startMainFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MainFragment fragment = new MainFragment(); fragment.setUserInfo(mUserInfo); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } private void startMainFragmentAnimation() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MainFragment fragment = new MainFragment(); fragment.setUserInfo(mUserInfo); transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right ); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); mActionBar.setTitle(R.string.app_name); } private void startVisitsFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); VisitsFragment fragment = new VisitsFragment(); fragment.setUserId(mUserInfo.getId()); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } private void startBillsFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); BillsFragment fragment = new BillsFragment(); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } private void startMessagesFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MessagesFragment fragment = new MessagesFragment(); fragment.setUserInfo(mUserInfo); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } @Override public void onSaveInstanceState(Bundle outState) { outState.putParcelable(UserInfo.TAG, Parcels.wrap(mUserInfo)); // call superclass to save any view hierarchy super.onSaveInstanceState(outState); } }
UTF-8
Java
6,523
java
MainActivity.java
Java
[ { "context": "ge com.pthomasdesigns.myhealth;\n\n/**\n * Created by tthomas on 4/14/2018.\n */\n\nimport android.content.Intent;", "end": 63, "score": 0.9996373057365417, "start": 56, "tag": "USERNAME", "value": "tthomas" } ]
null
[]
package com.pthomasdesigns.myhealth; /** * Created by tthomas on 4/14/2018. */ import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.pthomasdesigns.myhealth.rest.model.UserInfo; import com.pthomasdesigns.myhealth.rest.service.RestClient; import org.parceler.Parcels; public class MainActivity extends AppCompatActivity { private static final String TAG = "MyHealth:MainActivity"; public static String PACKAGE_NAME = BuildConfig.APPLICATION_ID; public static final String FRAGMENT_ID = PACKAGE_NAME + ".FragmentId"; private DrawerLayout mDrawerLayout; private TextView mNavigationViewUserId; private NavigationView mNavigationView; private ActionBar mActionBar; private static UserInfo mUserInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setHomeAsUpIndicator(R.drawable.ic_menu); mActionBar.setTitle(R.string.app_name); mDrawerLayout = findViewById(R.id.drawer_layout); mNavigationView = findViewById(R.id.nav_view); mNavigationViewUserId = mNavigationView.getHeaderView(0).findViewById(R.id.nav_view_userid); mNavigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { startFragment(item.getItemId()); item.setChecked(true); mDrawerLayout.closeDrawers(); return true; } } ); if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); Parcelable pExtras = getIntent().getParcelableExtra(UserInfo.TAG); if (pExtras != null) { mUserInfo = Parcels.unwrap(pExtras); mNavigationViewUserId.setText(mUserInfo.getName()); } if (extras != null && extras.getInt(FRAGMENT_ID) != 0) { startFragment(extras.getInt(FRAGMENT_ID)); } else { startMainFragment(); } } else { mUserInfo = Parcels.unwrap(savedInstanceState.getParcelable(UserInfo.TAG)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } private void startFragment(int itemId) { switch(itemId) { case R.id.nav_visits: startVisitsFragment(); break; case R.id.nav_bills: startBillsFragment(); break; case R.id.nav_messages: startMessagesFragment(); break; case R.id.logout: finish(); break; default: startMainFragment(); break; } } @Override public void onBackPressed () { Fragment fragment = getSupportFragmentManager().findFragmentByTag(MainFragment.TAG); if (fragment != null && fragment.isVisible()) { finish(); } else { startMainFragmentAnimation(); } } private void startMainFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MainFragment fragment = new MainFragment(); fragment.setUserInfo(mUserInfo); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } private void startMainFragmentAnimation() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MainFragment fragment = new MainFragment(); fragment.setUserInfo(mUserInfo); transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right ); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); mActionBar.setTitle(R.string.app_name); } private void startVisitsFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); VisitsFragment fragment = new VisitsFragment(); fragment.setUserId(mUserInfo.getId()); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } private void startBillsFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); BillsFragment fragment = new BillsFragment(); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } private void startMessagesFragment() { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MessagesFragment fragment = new MessagesFragment(); fragment.setUserInfo(mUserInfo); transaction.replace(R.id.fragment_container, fragment, fragment.TAG); transaction.commit(); } @Override public void onSaveInstanceState(Bundle outState) { outState.putParcelable(UserInfo.TAG, Parcels.wrap(mUserInfo)); // call superclass to save any view hierarchy super.onSaveInstanceState(outState); } }
6,523
0.659206
0.6566
181
35.038673
25.613222
103
false
false
0
0
0
0
0
0
0.607735
false
false
15
3c5d4cc916162cf23b4759c5e42fe0ae4b8bc1c5
5,798,205,850,688
d21de86375354f1ef0614b73a8f39dc48ed92fcd
/src/main/java/com/wangzhixuan/mapper/task/TaskItemMapper.java
e43bb5a1489962f10b4f9c8bf0ac01ab5a0f9459
[]
no_license
EsionMa/SFT
https://github.com/EsionMa/SFT
22173c5846efc2e687a6911651b646b15ab472be
00c6eb15351c802a0860cfbe90e358a57fa5f771
refs/heads/master
2020-05-17T19:36:23.019000
2019-04-28T14:54:34
2019-04-28T14:54:34
183,918,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wangzhixuan.mapper.task; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.wangzhixuan.model.task.TaskItem; public interface TaskItemMapper extends BaseMapper<TaskItem> { }
UTF-8
Java
199
java
TaskItemMapper.java
Java
[]
null
[]
package com.wangzhixuan.mapper.task; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.wangzhixuan.model.task.TaskItem; public interface TaskItemMapper extends BaseMapper<TaskItem> { }
199
0.834171
0.834171
7
27.428572
24.563951
62
false
false
0
0
0
0
0
0
0.428571
false
false
15
3bcbfe3dea312d633d2a25b7600ca95df7e11bfe
755,914,290,308
36f35b444a2772054eba900814a3e174be4c9e1a
/org.moxieapps.gwt.highcharts.showcase/src/main/java/org/moxieapps/gwt/highcharts/showcase/client/dynamic/ColumnPieDrilldownExample.java
da8d859600d9a9fab6e7fcc524baafbdce4d1dc8
[ "Apache-2.0" ]
permissive
Healthometry/gwt-highcharts
https://github.com/Healthometry/gwt-highcharts
eae06a936ca5bcf83f0a71806ec76cc8dfca8531
8c2d9ea8790b2671e4fb718aa886fcfb058ace86
refs/heads/main
2023-02-27T20:37:12.018000
2021-02-05T16:24:58
2021-02-05T16:24:58
341,611,410
0
1
Apache-2.0
true
2021-02-23T16:08:10
2021-02-23T16:08:09
2021-02-09T01:19:41
2021-02-05T16:25:04
1,239
0
0
0
null
false
false
package org.moxieapps.gwt.highcharts.showcase.client.dynamic; import com.google.gwt.user.client.Window; import com.smartgwt.client.widgets.Canvas; import org.moxieapps.gwt.highcharts.client.*; import org.moxieapps.gwt.highcharts.client.labels.DataLabels; import org.moxieapps.gwt.highcharts.client.plotOptions.SeriesPlotOptions; import org.moxieapps.gwt.highcharts.showcase.client.BaseChartExample; import org.moxieapps.gwt.highcharts.showcase.client.ExampleFactory; import org.moxieapps.gwt.highcharts.showcase.client.threeD.Column3DExample; public class ColumnPieDrilldownExample extends BaseChartExample { public ColumnPieDrilldownExample(String title, String icon) { super(title, icon); } @Override public String getSourcePath() { return "dynamic/ColumnPieDrilldownExample.java.html"; } public static ExampleFactory getExampleFactory() { return new ExampleFactory() { @Override public Canvas createChartCanvas() { return new ColumnPieDrilldownExample(getTitle(), getIcon()); } @Override public String getTitle() { return "Drilldown Across Series Types"; } @Override public String getIcon() { return "icons/16/column_chart.png"; } }; } @Override public BaseChart createChart() { Chart chart = new Chart() .setType(Series.Type.COLUMN) .setChartTitleText("Drilldown from Column to Pie") .setBorderWidth(0); chart.getXAxis() .setType(Axis.Type.CATEGORY) .setShowEmpty(false); chart.getYAxis() .setShowEmpty(false); chart.setLegend(new Legend() .setEnabled(true) ); chart.setSeriesPlotOptions(new SeriesPlotOptions() .setDataLabels(new DataLabels() .setEnabled(true) ) ); final Series animalSeries = chart.createSeries() .setType(Series.Type.PIE) .setPoints( new Point[]{ new Point("Cats", 4), new Point("Dogs", 2), new Point("Cows", 2), new Point("Sheep", 2), new Point("Pigs", 1) }); final Series fruitSeries = chart.createSeries() .setType(Series.Type.PIE) .setPoints(new Point[]{ new Point("Apples", 4), new Point("Oranges", 2) }); final Series carSeries = chart.createSeries() .setType(Series.Type.PIE) .setPoints(new Point[]{ new Point("Toyota", 4), new Point("Opel", 2), new Point("Volkswagen", 2) }); chart.setDrilldown(new Drilldown() .setSeries(animalSeries, fruitSeries, carSeries) ); chart.addSeries(chart.createSeries() .setName("Things") .setColorByPoint(true) .setPoints(new Point[]{ new Point("Animals", 5) .setDrilldownSeries(animalSeries), new Point("Fruits", 2) .setDrilldownSeries(fruitSeries), new Point("Cars", 3) .setDrilldownSeries(carSeries) }) ); Highcharts.setOptions( new Highcharts.Options().setLang( new Lang() .setOption("drillUpText", "Back to Things") ) ); return chart; } }
UTF-8
Java
3,676
java
ColumnPieDrilldownExample.java
Java
[]
null
[]
package org.moxieapps.gwt.highcharts.showcase.client.dynamic; import com.google.gwt.user.client.Window; import com.smartgwt.client.widgets.Canvas; import org.moxieapps.gwt.highcharts.client.*; import org.moxieapps.gwt.highcharts.client.labels.DataLabels; import org.moxieapps.gwt.highcharts.client.plotOptions.SeriesPlotOptions; import org.moxieapps.gwt.highcharts.showcase.client.BaseChartExample; import org.moxieapps.gwt.highcharts.showcase.client.ExampleFactory; import org.moxieapps.gwt.highcharts.showcase.client.threeD.Column3DExample; public class ColumnPieDrilldownExample extends BaseChartExample { public ColumnPieDrilldownExample(String title, String icon) { super(title, icon); } @Override public String getSourcePath() { return "dynamic/ColumnPieDrilldownExample.java.html"; } public static ExampleFactory getExampleFactory() { return new ExampleFactory() { @Override public Canvas createChartCanvas() { return new ColumnPieDrilldownExample(getTitle(), getIcon()); } @Override public String getTitle() { return "Drilldown Across Series Types"; } @Override public String getIcon() { return "icons/16/column_chart.png"; } }; } @Override public BaseChart createChart() { Chart chart = new Chart() .setType(Series.Type.COLUMN) .setChartTitleText("Drilldown from Column to Pie") .setBorderWidth(0); chart.getXAxis() .setType(Axis.Type.CATEGORY) .setShowEmpty(false); chart.getYAxis() .setShowEmpty(false); chart.setLegend(new Legend() .setEnabled(true) ); chart.setSeriesPlotOptions(new SeriesPlotOptions() .setDataLabels(new DataLabels() .setEnabled(true) ) ); final Series animalSeries = chart.createSeries() .setType(Series.Type.PIE) .setPoints( new Point[]{ new Point("Cats", 4), new Point("Dogs", 2), new Point("Cows", 2), new Point("Sheep", 2), new Point("Pigs", 1) }); final Series fruitSeries = chart.createSeries() .setType(Series.Type.PIE) .setPoints(new Point[]{ new Point("Apples", 4), new Point("Oranges", 2) }); final Series carSeries = chart.createSeries() .setType(Series.Type.PIE) .setPoints(new Point[]{ new Point("Toyota", 4), new Point("Opel", 2), new Point("Volkswagen", 2) }); chart.setDrilldown(new Drilldown() .setSeries(animalSeries, fruitSeries, carSeries) ); chart.addSeries(chart.createSeries() .setName("Things") .setColorByPoint(true) .setPoints(new Point[]{ new Point("Animals", 5) .setDrilldownSeries(animalSeries), new Point("Fruits", 2) .setDrilldownSeries(fruitSeries), new Point("Cars", 3) .setDrilldownSeries(carSeries) }) ); Highcharts.setOptions( new Highcharts.Options().setLang( new Lang() .setOption("drillUpText", "Back to Things") ) ); return chart; } }
3,676
0.548966
0.544342
120
29.633333
21.385326
76
false
false
0
0
0
0
0
0
0.458333
false
false
15
406a9fd4bd3c961fa2ecd59438157427383f8cd3
7,894,149,932,162
3ef07146e3702dd10816349d3549831a0312d032
/src/model/Model.java
685d3d84e8fed52d271a37c8c98e71cd4f567355
[]
no_license
yashwanthgowda2433/Java-web-application
https://github.com/yashwanthgowda2433/Java-web-application
69b78214643eca827a5753230c67d9abddd29ffa
2b509efc6a5e827e0e8452f2f24eb9d1ae083aa1
refs/heads/main
2023-04-04T23:49:23.256000
2021-04-15T12:07:37
2021-04-15T12:07:37
358,243,217
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import oracle.jdbc.driver.OracleDriver; public class Model { float balance = 100.0f; // Initial Balance = 100.0 float principal; // Principal Loan Amount float tempBalance = -1.0f; float toBalance; float amount; String name; String password; String branch; String email; int accNumber; // Current Account Number int accNumber2; // Updated / Next Account Number int toAccNumber; String ifsc; int result, result2, a; String p; Connection con = null; ResultSet resultSet = null; PreparedStatement pstmt = null; Statement stmt = null; // Model() Constructor will load the OJDBC driver & establish the connection to the database. public Model() { try { DriverManager.registerDriver(new OracleDriver()); System.out.println("Driver Loaded Successfully!"); con = DriverManager.getConnection("jdbc:oracle:thin:@SurajAcer:1522:xe", "system", "system"); System.out.println("Connection Established Successfully!"); } catch(Exception e) { e.printStackTrace(); } } // Generate account number by retrieving value of ACC_NO from ACC_TABLE. public void generateAccNumber() { try { stmt = con.createStatement(); resultSet = stmt.executeQuery("SELECT ACC_NO FROM ACC_TABLE"); while(resultSet.next() == true) { accNumber = resultSet.getInt(1); accNumber2 = accNumber + 1; updateAccNumber(); } } catch (SQLException e) { e.printStackTrace(); } } // Store the next account number by updating value of ACC_NO in ACC_TABLE. public void updateAccNumber() { try { pstmt = con.prepareStatement("UPDATE ACC_TABLE SET ACC_NO = ? WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber2); pstmt.setInt(2, accNumber); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // Generate IFSC code from the Bank's branch location. public void generateIFSC() { if(branch.equals("VIJ")) { ifsc = "UNBKVIJ001"; } else if (branch.equals("YPR")) { ifsc = "UNBKYPR002"; } else { ifsc = "Invalid"; } } /** * Registers a new account into the database table of BANK_DATA. * @return true, if the registration was successful. * @return false, if the registration was not successful. */ public boolean register() { generateIFSC(); if(ifsc.equals("Invalid")) // IFSC code is Invalid, Hence registration must fail. { return false; // So directly return false. } generateAccNumber(); try { pstmt = con.prepareStatement("INSERT INTO BANK_DATA VALUES(?,?,?,?,?,?,?)"); pstmt.setFloat(1, balance); pstmt.setString(2, name); pstmt.setString(3, password); pstmt.setString(4, branch); pstmt.setString(5, email); pstmt.setInt(6, accNumber); pstmt.setString(7, ifsc); result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } if(result == 1) { return true; } else { return false; } } /** * Login for an existing account by taking it's accNumber & matching the password from the database. * @return true, if the login was successful. * @return false, if the login was not successful. */ public boolean login() { try { pstmt = con.prepareStatement("SELECT * FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Setting the accNumber given from Login servlet. resultSet = pstmt.executeQuery(); // Executing the query while(resultSet.next() == true) { a = resultSet.getInt("ACC_NO"); // Getting the accNumber from the Database p = resultSet.getString("PASSWORD"); // Getting the password from the Database } } catch (SQLException e) { e.printStackTrace(); } if(accNumber == a && password.equals(p)) // Matching the credentials { return true; } else { return false; } } /** * Check Balance for an already logged-in account. * @return true, if the balance check was successful. * @return false, if the balance check was not successful. */ public boolean checkBalance() { try { tempBalance = -1.0f; // First set a Negative, Invalid Balance value. pstmt = con.prepareStatement("SELECT BALANCE FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Setting the accNumber from Balance servlet. resultSet = pstmt.executeQuery(); // Executing the query while(resultSet.next() == true) { tempBalance = resultSet.getFloat("BALANCE"); // Getting balance from the Database } } catch (SQLException e) { e.printStackTrace(); } if(tempBalance > 0.0f) // If valid Balance { balance = tempBalance; // Store the valid Balance value. return true; } else // If invalid Balance { return false; } } /** * Change Password for an already logged-in account. * @return true, if the password change was successful. * @return false, if the password change was not successful. */ public boolean changePassword() { try { pstmt = con.prepareStatement("UPDATE BANK_DATA SET PASSWORD = ? WHERE ACC_NO = ?"); pstmt.setString(1, password); // Setting password from Password servlet. pstmt.setInt(2, accNumber); // Setting accNumber from Password servlet. result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } if(result == 1) { return true; } else { return false; } } /** * Transfer amount from an already logged-in account to another account. * @return true, if the transfer was successful. * @return false, if the transfer was not successful. */ public boolean transfer() { try { // First, get the current balance of the toAccNumber account. pstmt = con.prepareStatement("SELECT * FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, toAccNumber); resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { toBalance = resultSet.getFloat("BALANCE"); } // Then, Credit (Add) the amount into the toAccNumber account. toBalance = toBalance + amount; // New, Updated Balance of toAccNumber Account pstmt = con.prepareStatement("UPDATE BANK_DATA SET BALANCE = ? WHERE ACC_NO = ?"); pstmt.setFloat(1, toBalance); pstmt.setInt(2, toAccNumber); result = pstmt.executeUpdate(); updateHistory(); // Update Transaction History in TRANSACTION Table of DB. } catch(Exception e) { e.printStackTrace(); } if(result == 1) { try { // Now, Debit (Deduct) the same amount from logged-in account. balance = balance - amount; // New, Updated Balance of Logged-in Account pstmt = con.prepareStatement("UPDATE BANK_DATA SET BALANCE = ? WHERE ACC_NO = ?"); pstmt.setFloat(1, balance); pstmt.setInt(2, accNumber); result2 = pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } return true; } else { return false; } } // Update Transaction History in TRANSACTION Table of DB. public void updateHistory() { try { pstmt = con.prepareStatement("INSERT INTO TRANSACTIONS VALUES(?,?)"); pstmt.setInt(1, accNumber); // Logged-in Account Number pstmt.setFloat(2, amount); // Transaction Amount pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } /** * @return ArrayList containing Transaction History of logged-in account. */ public ArrayList<Float> history() { ArrayList<Float> al = new ArrayList<Float>(); try { pstmt = con.prepareStatement("SELECT AMOUNT FROM TRANSACTIONS WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Logged-in Account Number resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { al.add(resultSet.getFloat("AMOUNT")); // Add all transaction amounts into the ArrayList. } } catch(Exception e) { e.printStackTrace(); } return al; } // Retrieve name of logged-in account holder, based on their accNumber. public void retrieveName() { try { pstmt = con.prepareStatement("SELECT NAME FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Logged-in Account Number resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { name = resultSet.getString("NAME"); // Store name of logged-in account holder. } } catch(Exception e) { e.printStackTrace(); } } // Approve Loan & add principal loan amount into the logged-in account's balance. public void updateLoan() { try { // First, get the current balance of the logged-in accNumber account. pstmt = con.prepareStatement("SELECT BALANCE FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { balance = resultSet.getFloat("BALANCE"); balance = balance + principal; // Add principal loan amount into the balance. } // Then, update the new balance into the toAccNumber account. pstmt = con.prepareStatement("UPDATE BANK_DATA SET BALANCE = ? WHERE ACC_NO = ?"); pstmt.setFloat(1, balance); pstmt.setInt(2, accNumber); pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } // Getters public float getBalance() { return balance; } public String getName() { return name; } public String getPassword() { return password; } public String getBranch() { return branch; } public String getEmail() { return email; } public int getAccNumber() { return accNumber; } public int getAccNumber2() { return accNumber2; } public String getIfsc() { return ifsc; } public int getToAccNumber() { return toAccNumber; } // Setters public void setBalance(float balance) { this.balance = balance; } public void setPrincipal(float principal) { this.principal = principal; } public void setAmount(float amount) { this.amount = amount; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = password; } public void setBranch(String branch) { this.branch = branch; } public void setEmail(String email) { this.email = email; } public void setAccNumber(int accNumber) { this.accNumber = accNumber; } public void setToAccNumber(int toAccNumber) { this.toAccNumber = toAccNumber; } }
UTF-8
Java
10,980
java
Model.java
Java
[]
null
[]
package model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import oracle.jdbc.driver.OracleDriver; public class Model { float balance = 100.0f; // Initial Balance = 100.0 float principal; // Principal Loan Amount float tempBalance = -1.0f; float toBalance; float amount; String name; String password; String branch; String email; int accNumber; // Current Account Number int accNumber2; // Updated / Next Account Number int toAccNumber; String ifsc; int result, result2, a; String p; Connection con = null; ResultSet resultSet = null; PreparedStatement pstmt = null; Statement stmt = null; // Model() Constructor will load the OJDBC driver & establish the connection to the database. public Model() { try { DriverManager.registerDriver(new OracleDriver()); System.out.println("Driver Loaded Successfully!"); con = DriverManager.getConnection("jdbc:oracle:thin:@SurajAcer:1522:xe", "system", "system"); System.out.println("Connection Established Successfully!"); } catch(Exception e) { e.printStackTrace(); } } // Generate account number by retrieving value of ACC_NO from ACC_TABLE. public void generateAccNumber() { try { stmt = con.createStatement(); resultSet = stmt.executeQuery("SELECT ACC_NO FROM ACC_TABLE"); while(resultSet.next() == true) { accNumber = resultSet.getInt(1); accNumber2 = accNumber + 1; updateAccNumber(); } } catch (SQLException e) { e.printStackTrace(); } } // Store the next account number by updating value of ACC_NO in ACC_TABLE. public void updateAccNumber() { try { pstmt = con.prepareStatement("UPDATE ACC_TABLE SET ACC_NO = ? WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber2); pstmt.setInt(2, accNumber); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // Generate IFSC code from the Bank's branch location. public void generateIFSC() { if(branch.equals("VIJ")) { ifsc = "UNBKVIJ001"; } else if (branch.equals("YPR")) { ifsc = "UNBKYPR002"; } else { ifsc = "Invalid"; } } /** * Registers a new account into the database table of BANK_DATA. * @return true, if the registration was successful. * @return false, if the registration was not successful. */ public boolean register() { generateIFSC(); if(ifsc.equals("Invalid")) // IFSC code is Invalid, Hence registration must fail. { return false; // So directly return false. } generateAccNumber(); try { pstmt = con.prepareStatement("INSERT INTO BANK_DATA VALUES(?,?,?,?,?,?,?)"); pstmt.setFloat(1, balance); pstmt.setString(2, name); pstmt.setString(3, password); pstmt.setString(4, branch); pstmt.setString(5, email); pstmt.setInt(6, accNumber); pstmt.setString(7, ifsc); result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } if(result == 1) { return true; } else { return false; } } /** * Login for an existing account by taking it's accNumber & matching the password from the database. * @return true, if the login was successful. * @return false, if the login was not successful. */ public boolean login() { try { pstmt = con.prepareStatement("SELECT * FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Setting the accNumber given from Login servlet. resultSet = pstmt.executeQuery(); // Executing the query while(resultSet.next() == true) { a = resultSet.getInt("ACC_NO"); // Getting the accNumber from the Database p = resultSet.getString("PASSWORD"); // Getting the password from the Database } } catch (SQLException e) { e.printStackTrace(); } if(accNumber == a && password.equals(p)) // Matching the credentials { return true; } else { return false; } } /** * Check Balance for an already logged-in account. * @return true, if the balance check was successful. * @return false, if the balance check was not successful. */ public boolean checkBalance() { try { tempBalance = -1.0f; // First set a Negative, Invalid Balance value. pstmt = con.prepareStatement("SELECT BALANCE FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Setting the accNumber from Balance servlet. resultSet = pstmt.executeQuery(); // Executing the query while(resultSet.next() == true) { tempBalance = resultSet.getFloat("BALANCE"); // Getting balance from the Database } } catch (SQLException e) { e.printStackTrace(); } if(tempBalance > 0.0f) // If valid Balance { balance = tempBalance; // Store the valid Balance value. return true; } else // If invalid Balance { return false; } } /** * Change Password for an already logged-in account. * @return true, if the password change was successful. * @return false, if the password change was not successful. */ public boolean changePassword() { try { pstmt = con.prepareStatement("UPDATE BANK_DATA SET PASSWORD = ? WHERE ACC_NO = ?"); pstmt.setString(1, password); // Setting password from Password servlet. pstmt.setInt(2, accNumber); // Setting accNumber from Password servlet. result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } if(result == 1) { return true; } else { return false; } } /** * Transfer amount from an already logged-in account to another account. * @return true, if the transfer was successful. * @return false, if the transfer was not successful. */ public boolean transfer() { try { // First, get the current balance of the toAccNumber account. pstmt = con.prepareStatement("SELECT * FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, toAccNumber); resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { toBalance = resultSet.getFloat("BALANCE"); } // Then, Credit (Add) the amount into the toAccNumber account. toBalance = toBalance + amount; // New, Updated Balance of toAccNumber Account pstmt = con.prepareStatement("UPDATE BANK_DATA SET BALANCE = ? WHERE ACC_NO = ?"); pstmt.setFloat(1, toBalance); pstmt.setInt(2, toAccNumber); result = pstmt.executeUpdate(); updateHistory(); // Update Transaction History in TRANSACTION Table of DB. } catch(Exception e) { e.printStackTrace(); } if(result == 1) { try { // Now, Debit (Deduct) the same amount from logged-in account. balance = balance - amount; // New, Updated Balance of Logged-in Account pstmt = con.prepareStatement("UPDATE BANK_DATA SET BALANCE = ? WHERE ACC_NO = ?"); pstmt.setFloat(1, balance); pstmt.setInt(2, accNumber); result2 = pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } return true; } else { return false; } } // Update Transaction History in TRANSACTION Table of DB. public void updateHistory() { try { pstmt = con.prepareStatement("INSERT INTO TRANSACTIONS VALUES(?,?)"); pstmt.setInt(1, accNumber); // Logged-in Account Number pstmt.setFloat(2, amount); // Transaction Amount pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } /** * @return ArrayList containing Transaction History of logged-in account. */ public ArrayList<Float> history() { ArrayList<Float> al = new ArrayList<Float>(); try { pstmt = con.prepareStatement("SELECT AMOUNT FROM TRANSACTIONS WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Logged-in Account Number resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { al.add(resultSet.getFloat("AMOUNT")); // Add all transaction amounts into the ArrayList. } } catch(Exception e) { e.printStackTrace(); } return al; } // Retrieve name of logged-in account holder, based on their accNumber. public void retrieveName() { try { pstmt = con.prepareStatement("SELECT NAME FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); // Logged-in Account Number resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { name = resultSet.getString("NAME"); // Store name of logged-in account holder. } } catch(Exception e) { e.printStackTrace(); } } // Approve Loan & add principal loan amount into the logged-in account's balance. public void updateLoan() { try { // First, get the current balance of the logged-in accNumber account. pstmt = con.prepareStatement("SELECT BALANCE FROM BANK_DATA WHERE ACC_NO = ?"); pstmt.setInt(1, accNumber); resultSet = pstmt.executeQuery(); while(resultSet.next() == true) { balance = resultSet.getFloat("BALANCE"); balance = balance + principal; // Add principal loan amount into the balance. } // Then, update the new balance into the toAccNumber account. pstmt = con.prepareStatement("UPDATE BANK_DATA SET BALANCE = ? WHERE ACC_NO = ?"); pstmt.setFloat(1, balance); pstmt.setInt(2, accNumber); pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } // Getters public float getBalance() { return balance; } public String getName() { return name; } public String getPassword() { return password; } public String getBranch() { return branch; } public String getEmail() { return email; } public int getAccNumber() { return accNumber; } public int getAccNumber2() { return accNumber2; } public String getIfsc() { return ifsc; } public int getToAccNumber() { return toAccNumber; } // Setters public void setBalance(float balance) { this.balance = balance; } public void setPrincipal(float principal) { this.principal = principal; } public void setAmount(float amount) { this.amount = amount; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = password; } public void setBranch(String branch) { this.branch = branch; } public void setEmail(String email) { this.email = email; } public void setAccNumber(int accNumber) { this.accNumber = accNumber; } public void setToAccNumber(int toAccNumber) { this.toAccNumber = toAccNumber; } }
10,980
0.635883
0.630328
466
21.566525
24.394224
101
false
false
0
0
0
0
0
0
2.414163
false
false
15
2710419e84f6a25b08569179c6677ebe4c34ca37
14,010,183,335,099
7f3503a7916377ba5d5912ccfdb489dea571f9c1
/src/main/java/com/softserve/edu/servicecenter/entity/Address.java
18d9cc9ee28f4f3e4dbb77f5bc53b2d335e5180d
[]
no_license
khdimon/ServiceCenter
https://github.com/khdimon/ServiceCenter
dbdbcf1a1e1b7176fd4cee097918e2f3bc7a04af
3598dc5ef098fc7213d9c9790180254f9928ee52
refs/heads/master
2020-09-06T14:21:53.980000
2017-07-04T17:32:05
2017-07-04T17:32:05
94,419,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.softserve.edu.servicecenter.entity; import javax.persistence.*; import java.util.Collection; @Entity @Table(name = "addresses") public class Address { private long id; private String city; private String street; private String house; private Integer flat; private String entrance; private Integer floor; private Collection<Client> clientsById; private Collection<Master> mastersById; @Id @Column(name = "id", nullable = false) public long getId() { return id; } public void setId(long id) { this.id = id; } @Basic @Column(name = "city", nullable = false, length = 45) public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Basic @Column(name = "street", nullable = false, length = 45) public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } @Basic @Column(name = "house", nullable = false, length = 8) public String getHouse() { return house; } public void setHouse(String house) { this.house = house; } @Basic @Column(name = "flat", nullable = true) public Integer getFlat() { return flat; } public void setFlat(Integer flat) { this.flat = flat; } @Basic @Column(name = "entrance", nullable = true, length = 8) public String getEntrance() { return entrance; } public void setEntrance(String entrance) { this.entrance = entrance; } @Basic @Column(name = "floor", nullable = true) public Integer getFloor() { return floor; } public void setFloor(Integer floor) { this.floor = floor; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address that = (Address) o; if (id != that.id) return false; if (city != null ? !city.equals(that.city) : that.city != null) return false; if (street != null ? !street.equals(that.street) : that.street != null) return false; if (house != null ? !house.equals(that.house) : that.house != null) return false; if (flat != null ? !flat.equals(that.flat) : that.flat != null) return false; if (entrance != null ? !entrance.equals(that.entrance) : that.entrance != null) return false; if (floor != null ? !floor.equals(that.floor) : that.floor != null) return false; return true; } @Override public int hashCode() { int result = (int) id; result = 31 * result + (city != null ? city.hashCode() : 0); result = 31 * result + (street != null ? street.hashCode() : 0); result = 31 * result + (house != null ? house.hashCode() : 0); result = 31 * result + (flat != null ? flat.hashCode() : 0); result = 31 * result + (entrance != null ? entrance.hashCode() : 0); result = 31 * result + (floor != null ? floor.hashCode() : 0); return result; } @OneToMany(mappedBy = "addressByAddressId") public Collection<Client> getClientsById() { return clientsById; } public void setClientsById(Collection<Client> clientsById) { this.clientsById = clientsById; } @OneToMany(mappedBy = "addressByAddressId") public Collection<Master> getMastersById() { return mastersById; } public void setMastersById(Collection<Master> mastersById) { this.mastersById = mastersById; } @Override public String toString() { String flatStr = (flat != null) ? ", кв. " + flat : ""; String entranceStr = (entrance != null) ? ", подъезд " + entrance : ""; String floorStr = (floor != null) ? ", этаж " + floor : ""; return city + ", " + street + ", " + house + flatStr + entranceStr + floorStr; } }
UTF-8
Java
4,020
java
Address.java
Java
[]
null
[]
package com.softserve.edu.servicecenter.entity; import javax.persistence.*; import java.util.Collection; @Entity @Table(name = "addresses") public class Address { private long id; private String city; private String street; private String house; private Integer flat; private String entrance; private Integer floor; private Collection<Client> clientsById; private Collection<Master> mastersById; @Id @Column(name = "id", nullable = false) public long getId() { return id; } public void setId(long id) { this.id = id; } @Basic @Column(name = "city", nullable = false, length = 45) public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Basic @Column(name = "street", nullable = false, length = 45) public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } @Basic @Column(name = "house", nullable = false, length = 8) public String getHouse() { return house; } public void setHouse(String house) { this.house = house; } @Basic @Column(name = "flat", nullable = true) public Integer getFlat() { return flat; } public void setFlat(Integer flat) { this.flat = flat; } @Basic @Column(name = "entrance", nullable = true, length = 8) public String getEntrance() { return entrance; } public void setEntrance(String entrance) { this.entrance = entrance; } @Basic @Column(name = "floor", nullable = true) public Integer getFloor() { return floor; } public void setFloor(Integer floor) { this.floor = floor; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address that = (Address) o; if (id != that.id) return false; if (city != null ? !city.equals(that.city) : that.city != null) return false; if (street != null ? !street.equals(that.street) : that.street != null) return false; if (house != null ? !house.equals(that.house) : that.house != null) return false; if (flat != null ? !flat.equals(that.flat) : that.flat != null) return false; if (entrance != null ? !entrance.equals(that.entrance) : that.entrance != null) return false; if (floor != null ? !floor.equals(that.floor) : that.floor != null) return false; return true; } @Override public int hashCode() { int result = (int) id; result = 31 * result + (city != null ? city.hashCode() : 0); result = 31 * result + (street != null ? street.hashCode() : 0); result = 31 * result + (house != null ? house.hashCode() : 0); result = 31 * result + (flat != null ? flat.hashCode() : 0); result = 31 * result + (entrance != null ? entrance.hashCode() : 0); result = 31 * result + (floor != null ? floor.hashCode() : 0); return result; } @OneToMany(mappedBy = "addressByAddressId") public Collection<Client> getClientsById() { return clientsById; } public void setClientsById(Collection<Client> clientsById) { this.clientsById = clientsById; } @OneToMany(mappedBy = "addressByAddressId") public Collection<Master> getMastersById() { return mastersById; } public void setMastersById(Collection<Master> mastersById) { this.mastersById = mastersById; } @Override public String toString() { String flatStr = (flat != null) ? ", кв. " + flat : ""; String entranceStr = (entrance != null) ? ", подъезд " + entrance : ""; String floorStr = (floor != null) ? ", этаж " + floor : ""; return city + ", " + street + ", " + house + flatStr + entranceStr + floorStr; } }
4,020
0.585725
0.579735
144
26.826389
25.245277
101
false
false
0
0
0
0
0
0
0.493056
false
false
15
5653614da7a8563b3394945b7011a8be9e016292
14,010,183,335,957
e7db7379b17f9f345139bc549571d741dfaabfa4
/src/main/java/pl/martyna/converter/service/IngredientsToJSONExportService.java
ec3a8d6cf64017fa9fa73efff1c96398f8567a35
[]
no_license
martyna8821/JSON-converter
https://github.com/martyna8821/JSON-converter
e5e2a7283339b78dad928e30722788d82dc62fd3
84a60d8c5b913ef82fa019fe0a99060858043aac
refs/heads/master
2021-07-19T19:22:04.312000
2019-11-14T19:54:23
2019-11-14T19:54:23
221,082,670
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.martyna.converter.service; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import pl.martyna.converter.Nutrition; import pl.martyna.converter.builder.Ingredient; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.Set; public class IngredientsToJSONExportService { public boolean writeIngredientsToJSONFile(Set<Ingredient> ingredients, String fileName){ JSONArray jsonIngredients = new JSONArray(); ingredients.forEach( ingredient -> { JSONObject jsonIngredient = new JSONObject(); jsonIngredient.put("name", ingredient.getName()); jsonIngredient.put("quantity", ingredient.getQuantity()); jsonIngredient.put("unit", ingredient.getUnit()); JSONArray jsonTypes = new JSONArray(); ingredient.getIngredientTypes().forEach(jsonTypes::add); jsonIngredient.put("ingredientTypes", jsonTypes); JSONArray jsonLabels = new JSONArray(); ingredient.getLabels().forEach(jsonLabels::add); jsonIngredient.put("labels", jsonLabels); JSONArray jsonBrands = new JSONArray(); ingredient.getBrands().forEach(jsonBrands::add); jsonIngredient.put("brands", jsonBrands); JSONArray jsonAllergens = new JSONArray(); ingredient.getAllergens().forEach(jsonAllergens::add); jsonIngredient.put("allergens", jsonAllergens); JSONArray jsonNutrition = new JSONArray(); for (Map.Entry<String, Nutrition> entry : ingredient.getNutrition().entrySet()) { JSONObject nutritionObj = new JSONObject(); nutritionObj.put("englishName", entry.getKey()); nutritionObj.put("polishName", entry.getValue().getPolishName()); nutritionObj.put("value", entry.getValue().getValue()); nutritionObj.put("unit", entry.getValue().getUnit()); jsonNutrition.add(nutritionObj); } jsonIngredient.put("nutrition", jsonNutrition); jsonIngredients.add(jsonIngredient); System.out.println(String.format("Added %s", ingredient.getName())); }); try(FileWriter file = new FileWriter(fileName)){ file.write(jsonIngredients.toJSONString()); } catch (IOException e) { e.printStackTrace(); return false; } return true; } }
UTF-8
Java
2,751
java
IngredientsToJSONExportService.java
Java
[]
null
[]
package pl.martyna.converter.service; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import pl.martyna.converter.Nutrition; import pl.martyna.converter.builder.Ingredient; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.Set; public class IngredientsToJSONExportService { public boolean writeIngredientsToJSONFile(Set<Ingredient> ingredients, String fileName){ JSONArray jsonIngredients = new JSONArray(); ingredients.forEach( ingredient -> { JSONObject jsonIngredient = new JSONObject(); jsonIngredient.put("name", ingredient.getName()); jsonIngredient.put("quantity", ingredient.getQuantity()); jsonIngredient.put("unit", ingredient.getUnit()); JSONArray jsonTypes = new JSONArray(); ingredient.getIngredientTypes().forEach(jsonTypes::add); jsonIngredient.put("ingredientTypes", jsonTypes); JSONArray jsonLabels = new JSONArray(); ingredient.getLabels().forEach(jsonLabels::add); jsonIngredient.put("labels", jsonLabels); JSONArray jsonBrands = new JSONArray(); ingredient.getBrands().forEach(jsonBrands::add); jsonIngredient.put("brands", jsonBrands); JSONArray jsonAllergens = new JSONArray(); ingredient.getAllergens().forEach(jsonAllergens::add); jsonIngredient.put("allergens", jsonAllergens); JSONArray jsonNutrition = new JSONArray(); for (Map.Entry<String, Nutrition> entry : ingredient.getNutrition().entrySet()) { JSONObject nutritionObj = new JSONObject(); nutritionObj.put("englishName", entry.getKey()); nutritionObj.put("polishName", entry.getValue().getPolishName()); nutritionObj.put("value", entry.getValue().getValue()); nutritionObj.put("unit", entry.getValue().getUnit()); jsonNutrition.add(nutritionObj); } jsonIngredient.put("nutrition", jsonNutrition); jsonIngredients.add(jsonIngredient); System.out.println(String.format("Added %s", ingredient.getName())); }); try(FileWriter file = new FileWriter(fileName)){ file.write(jsonIngredients.toJSONString()); } catch (IOException e) { e.printStackTrace(); return false; } return true; } }
2,751
0.58197
0.58197
67
40.0597
30.057596
101
false
false
0
0
0
0
0
0
0.835821
false
false
15
62977f593e6f99f6b78206c84c27d40171fef204
30,502,857,780,180
fb8d947ff28c4099a70a08aee953437aa8b174a1
/src/main/java/com/smartApps/tracomSolutions/exceptions/BranchNotFountException.java
f482e044e28172d9371cf81106abd148d4411877
[]
no_license
samtheboss/trancomSolutions
https://github.com/samtheboss/trancomSolutions
20170ab44614bb0d1013309b93fad398b496868d
dfdc6b3a43b9875d660d9c543ebaa408b1e5e3be
refs/heads/master
2023-08-25T00:29:20.601000
2021-11-03T18:18:07
2021-11-03T18:19:48
424,204,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smartApps.tracomSolutions.exceptions; public class BranchNotFountException extends RuntimeException{ public BranchNotFountException(String branch_not_found) { super(branch_not_found); } }
UTF-8
Java
219
java
BranchNotFountException.java
Java
[]
null
[]
package com.smartApps.tracomSolutions.exceptions; public class BranchNotFountException extends RuntimeException{ public BranchNotFountException(String branch_not_found) { super(branch_not_found); } }
219
0.771689
0.771689
8
26.375
26.400461
63
false
false
0
0
0
0
0
0
0.25
false
false
15
2d6d09d25a81fb8c32461c4f165805fcb9cad129
21,698,174,806,089
73fc126836a5b9ae0faa251273a60ce643d2dd60
/app/src/main/java/com/oceanwing/securitytool/login/model/ILoginModel.java
260da36bfe18c0c8486d1e5460e6a72eb6c06927
[]
no_license
Wing-Li-oceanwing/SecurityTool
https://github.com/Wing-Li-oceanwing/SecurityTool
5ab1a1db150b9ecd15c3206dd943e7e3b6d4b017
12a4ca455d028b226de81b489dc7ff68087f77a9
refs/heads/master
2020-03-16T22:05:24.766000
2018-10-26T08:21:56
2018-10-26T08:21:56
133,026,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oceanwing.securitytool.login.model; import android.content.Context; import com.oceanwing.securitytool.bean.UserBean; /** * @author wing.li * @date on 2018/3/2. **/ public interface ILoginModel { void toAssessDatabase(Context context, String username, String password, AssessListener listener); interface AssessListener{ void onComplate(UserBean bean); void onError(String error); } }
UTF-8
Java
451
java
ILoginModel.java
Java
[ { "context": "ing.securitytool.bean.UserBean;\r\n\r\n/**\r\n * @author wing.li\r\n * @date on 2018/3/2.\r\n **/\r\n\r\npublic interface ", "end": 161, "score": 0.9362436532974243, "start": 154, "tag": "USERNAME", "value": "wing.li" } ]
null
[]
package com.oceanwing.securitytool.login.model; import android.content.Context; import com.oceanwing.securitytool.bean.UserBean; /** * @author wing.li * @date on 2018/3/2. **/ public interface ILoginModel { void toAssessDatabase(Context context, String username, String password, AssessListener listener); interface AssessListener{ void onComplate(UserBean bean); void onError(String error); } }
451
0.698448
0.685144
19
21.736841
25.343622
102
false
false
0
0
0
0
0
0
0.473684
false
false
15
2d1b9db5ae8cf1302cb5de6a5e6b87e4a799c8eb
32,006,096,333,542
9b74bac632319669aac66cea617ef62e2b5ef02e
/org.eclipse.emf.henshin.model/src/org/eclipse/emf/henshin/model/util/ScriptEngineWrapper.java
e63e8951d76b10411e9f7bee7931e968eb882d1b
[]
no_license
de-tu-berlin-tfs/Henshin-Editor
https://github.com/de-tu-berlin-tfs/Henshin-Editor
805d34a45c6f0ab1122a3040b21042955e3db5e0
de76e116488d6c0d3a783b407e73905fbfeed5e3
refs/heads/master
2021-01-23T22:32:20.438000
2015-03-23T07:20:17
2015-03-23T07:20:17
3,592,583
4
2
null
false
2016-10-27T11:23:22
2012-03-01T14:22:29
2016-01-26T06:46:10
2016-10-25T16:26:32
108,714
8
2
5
Java
null
null
/** * <copyright> * Copyright (c) 2010-2014 Henshin developers. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * </copyright> */ package org.eclipse.emf.henshin.model.util; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * Script engine wrapper for automatic handling of Java imports. */ public class ScriptEngineWrapper { /** * Wildcard pattern */ private static final Pattern WILDCARD_PATTERN = Pattern.compile("(.*)\\.\\*$"); /** * The original scripting engine to delegate to. */ private final ScriptEngine engine; /** * List of global imports. */ private final List<String> globalImports; /** * Constructor. * * @param engine Script engine to be used. * @param globalImports List of global Java imports. */ public ScriptEngineWrapper(ScriptEngine engine, String[] globalImports) { this.engine = engine; this.globalImports = new ArrayList<String>(); if (globalImports != null) { for (int i = 0; i < globalImports.length; i++) { this.globalImports.add(globalImports[i]); } } if (engine == null) { System.err.println("Warning: cannot find JavaScript engine"); } } /** * Constructor. * * @param globalImports List of global Java imports. */ public ScriptEngineWrapper(String[] globalImports) { this(new ScriptEngineManager().getEngineByName("JavaScript"), globalImports); } /** * Get the wrapped JavaScript engine. * * @return The wrapped JavaScript engine. */ public ScriptEngine getEngine() { return engine; } /** * Evaluates a given expression in a context which is extended with the provided imports. The imports are on purpose * not added to the global scope to prevent pollution of the namespace. * * @param script Script to be executed. * @param localImports List of imports. * @return The result. * @throws ScriptException On script execution errors. */ @SuppressWarnings("unchecked") public Object eval(String script, List<String> localImports) throws ScriptException { if (!globalImports.isEmpty() || !localImports.isEmpty()) { script = "with (new JavaImporter(" + toImportString(globalImports, localImports) + ")) { " + script + " }"; } return engine.eval(script); } /** * Converts a list of imports like List("foo.Foo", "foo.bar.*") into one string "foo.Foo, foo.bar" */ private static String toImportString(List<String>... imports) { StringBuffer out = new StringBuffer(); String delim = ""; for (int i = 0; i < imports.length; i++) { for (String entry : imports[i]) { out.append(delim).append(stripWildcard(entry)); delim = ", "; } } return out.toString(); } private static String stripWildcard(String imp) { return isWildcard(imp) ? imp.substring(0, imp.length() - 2) : imp; } private static boolean isWildcard(String imp) { return WILDCARD_PATTERN.matcher(imp).matches(); } }
UTF-8
Java
3,220
java
ScriptEngineWrapper.java
Java
[]
null
[]
/** * <copyright> * Copyright (c) 2010-2014 Henshin developers. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * </copyright> */ package org.eclipse.emf.henshin.model.util; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * Script engine wrapper for automatic handling of Java imports. */ public class ScriptEngineWrapper { /** * Wildcard pattern */ private static final Pattern WILDCARD_PATTERN = Pattern.compile("(.*)\\.\\*$"); /** * The original scripting engine to delegate to. */ private final ScriptEngine engine; /** * List of global imports. */ private final List<String> globalImports; /** * Constructor. * * @param engine Script engine to be used. * @param globalImports List of global Java imports. */ public ScriptEngineWrapper(ScriptEngine engine, String[] globalImports) { this.engine = engine; this.globalImports = new ArrayList<String>(); if (globalImports != null) { for (int i = 0; i < globalImports.length; i++) { this.globalImports.add(globalImports[i]); } } if (engine == null) { System.err.println("Warning: cannot find JavaScript engine"); } } /** * Constructor. * * @param globalImports List of global Java imports. */ public ScriptEngineWrapper(String[] globalImports) { this(new ScriptEngineManager().getEngineByName("JavaScript"), globalImports); } /** * Get the wrapped JavaScript engine. * * @return The wrapped JavaScript engine. */ public ScriptEngine getEngine() { return engine; } /** * Evaluates a given expression in a context which is extended with the provided imports. The imports are on purpose * not added to the global scope to prevent pollution of the namespace. * * @param script Script to be executed. * @param localImports List of imports. * @return The result. * @throws ScriptException On script execution errors. */ @SuppressWarnings("unchecked") public Object eval(String script, List<String> localImports) throws ScriptException { if (!globalImports.isEmpty() || !localImports.isEmpty()) { script = "with (new JavaImporter(" + toImportString(globalImports, localImports) + ")) { " + script + " }"; } return engine.eval(script); } /** * Converts a list of imports like List("foo.Foo", "foo.bar.*") into one string "foo.Foo, foo.bar" */ private static String toImportString(List<String>... imports) { StringBuffer out = new StringBuffer(); String delim = ""; for (int i = 0; i < imports.length; i++) { for (String entry : imports[i]) { out.append(delim).append(stripWildcard(entry)); delim = ", "; } } return out.toString(); } private static String stripWildcard(String imp) { return isWildcard(imp) ? imp.substring(0, imp.length() - 2) : imp; } private static boolean isWildcard(String imp) { return WILDCARD_PATTERN.matcher(imp).matches(); } }
3,220
0.695652
0.690683
117
26.521368
27.275925
117
false
false
0
0
0
0
0
0
1.376068
false
false
15
e3b7aa04b9928b824fd34f2b13750c21cffd3c7c
19,335,942,813,349
6cea667c27ea6507220fa216c22df6af1097d542
/Familiar/src/main/java/Singleton/_2_.java
5f75cd2e2643bb5f9c481b7ba062c81fd21bbbfe
[]
no_license
Hobert-Li/BetterPlace
https://github.com/Hobert-Li/BetterPlace
e7302bab6f4421aa1a050b0971d2350e26d1159b
31068ed24263024c062c5a6cec87759f6172adbb
refs/heads/master
2022-06-21T16:33:43.455000
2020-02-05T12:26:14
2020-02-05T12:26:14
202,354,442
0
0
null
false
2022-06-17T02:25:24
2019-08-14T13:18:06
2020-02-05T12:26:25
2022-06-17T02:25:24
763
1
0
1
Java
false
false
package Singleton; /** * <p>名字: 懒汉模式(线程不安全)</p> * <p> * 描述: 懒汉模式申明了一个静态对象,在用户第一次调用时初始化, * 虽然节约了资源,但第一次加载时需要实例化, * 反映稍慢一些,而且在多线程不能正常工作。 * </p> * <p>示例:</p> * * @author 李宏博 * @create 2019/8/27 12:20 */ public class _2_ { private static _2_ instance; private _2_() { } public static _2_ getInstance() { if (instance == null) { instance = new _2_(); } return instance; } }
UTF-8
Java
650
java
_2_.java
Java
[ { "context": "线程不能正常工作。\r\n * </p>\r\n * <p>示例:</p>\r\n *\r\n * @author 李宏博\r\n * @create 2019/8/27 12:20\r\n */\r\n\r\npublic class ", "end": 191, "score": 0.9982048273086548, "start": 188, "tag": "NAME", "value": "李宏博" } ]
null
[]
package Singleton; /** * <p>名字: 懒汉模式(线程不安全)</p> * <p> * 描述: 懒汉模式申明了一个静态对象,在用户第一次调用时初始化, * 虽然节约了资源,但第一次加载时需要实例化, * 反映稍慢一些,而且在多线程不能正常工作。 * </p> * <p>示例:</p> * * @author 李宏博 * @create 2019/8/27 12:20 */ public class _2_ { private static _2_ instance; private _2_() { } public static _2_ getInstance() { if (instance == null) { instance = new _2_(); } return instance; } }
650
0.49359
0.459402
28
14.714286
12.147478
37
false
false
0
0
0
0
0
0
0.142857
false
false
15
2d48a112d1fdb6adc4fcb0a7a8da3b23ecfdbe0c
7,524,782,703,424
f7f17fd66223dcb9fb6d22e37c28c199db632a5c
/src/main/java/com/minh/nguyen/validator/CourseValidator.java
e46011e65314ec8da859fdfade108c8d00da4afa
[]
no_license
Sheldelraze/amadeus
https://github.com/Sheldelraze/amadeus
24291a244f3aa69c0344f77d4cee8692b10585ac
62b73b484c86ec1199551acf3f5a872442dfe961
refs/heads/master
2018-11-16T08:07:52.939000
2018-09-02T15:51:06
2018-09-02T15:51:06
115,876,406
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.minh.nguyen.validator; import com.minh.nguyen.constants.Constants; import com.minh.nguyen.dto.AuthorityDTO; import com.minh.nguyen.entity.ApplicationEntity; import com.minh.nguyen.entity.CourseEntity; import com.minh.nguyen.entity.SubmissionEntity; import com.minh.nguyen.exception.NoSuchPageException; import com.minh.nguyen.form.BaseForm; import com.minh.nguyen.mapper.ApplicationMapper; import com.minh.nguyen.mapper.AuthorityMapper; import com.minh.nguyen.mapper.CourseMapper; import com.minh.nguyen.mapper.SubmissionMapper; import com.minh.nguyen.validator.common.BaseValidator; import com.minh.nguyen.validator.common.BindingResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import javax.servlet.http.HttpSession; import java.util.List; /** * @author Mr.Minh * @since 14/03/2018 * Purpose: */ @Component("CourseValidator") public class CourseValidator extends BaseValidator { @Autowired private HttpSession httpSession; @Autowired private AuthorityMapper authorityMapper; @Autowired private CourseMapper courseMapper; @Autowired private ApplicationMapper applicationMapper; @Autowired private SubmissionMapper submissionMapper; public boolean checkApplyPermission(Integer ceId, Integer urId) { if (urId == null || ceId == null) { return false; } if (!checkRole(Constants.ROLE_STUDENT_TEXT)) { return false; } ApplicationEntity applicationEntity = new ApplicationEntity(); applicationEntity.setCeId(ceId); applicationEntity.setUrId(urId); List<ApplicationEntity> lstApply = applicationMapper.selectWithExample(applicationEntity); for (ApplicationEntity apply : lstApply) { if (apply.getStatus().equals(Constants.APPLICATION_STATUS_ACCEPTED)) { return false; } if (apply.getStatus().equals(Constants.APPLICATION_STATUS_PENDING)) { return false; } } return true; } //check if curent user has any authority in current contest public boolean checkPermission(Authentication auth, Integer ceId, String... authority) throws NoSuchPageException { List<AuthorityDTO> lstAuthority = authorityMapper.getCourseAuthority(ceId, auth.getName()); for (AuthorityDTO curAuth : lstAuthority) { for (String requireAuth : authority) { if (requireAuth.equals(curAuth.getName())) { return true; } } } return false; } public boolean checkViewSubmissionPermission(Authentication auth,Integer snId,Integer ceId){ List<AuthorityDTO> lstAuthority = authorityMapper.getCourseAuthority(ceId, auth.getName()); boolean flag = false; for (AuthorityDTO curAuth : lstAuthority) { if (curAuth.getId().equals(Constants.AUTH_VIEW_COURSE_ID)) { return true; } if (curAuth.getId().equals(Constants.AUTH_PARTICIPATE_COURSE_ID)) { flag = true; } } if (!flag){ return false; } CourseEntity courseEntity = getCourseById(ceId); if (courseEntity.getShowSubmit().equals(Constants.SHOW_SUBMIT_ALL)){ return true; } SubmissionEntity submissionEntity = new SubmissionEntity(); submissionEntity.setId(snId); List<SubmissionEntity> lstSubmission = submissionMapper.selectWithExample(submissionEntity); if (lstSubmission.size() != 1){ throw new NoSuchPageException("Submission not found!"); } //check if submission is from current user submissionEntity = lstSubmission.get(0); Integer currentUserId = (Integer)httpSession.getAttribute(Constants.CURRENT_LOGIN_USER_ID); if (submissionEntity.getUrId().equals(currentUserId)){ return true; } //else check current user has solved this problem and this contests allow to view solved problem's solutions if (courseEntity.getShowSubmit().equals(Constants.SHOW_SUBMIT_SOLVED)){ Integer solveCnt = submissionMapper.checkSolvedStatusInContest(ceId,submissionEntity.getPmId(),submissionEntity.getUrId()); return solveCnt > 0; } return false; } public boolean checkRole(String roleName) { Object currentRole = httpSession.getAttribute(Constants.CURRENT_LOGIN_USER_ROLE_NAME); return currentRole != null && currentRole.toString().equals(roleName); } public boolean checkParticipate(Authentication auth, Integer ctId) throws NoSuchPageException { List<AuthorityDTO> lstAuthority = authorityMapper.getCourseAuthority(ctId, auth.getName()); for (AuthorityDTO curAuth : lstAuthority) { if (curAuth.getId().equals(Constants.AUTH_PARTICIPATE_COURSE_ID)) { return true; } } //not participator return false; } //Check if user is the contest's creator public boolean checkCreator(Authentication authentication, Integer ceId) { CourseEntity courseEntity = getCourseById(ceId); return courseEntity.getCreateUser().equals(authentication.getName()); } @Override public void validateField(String fieldName, String fieldValue, BindingResult errors) { } @Override public void validateLogic(BaseForm clazz, BindingResult errors) { } private CourseEntity getCourseById(int ceId) { CourseEntity courseEntity = new CourseEntity(); courseEntity.setId(ceId); courseEntity = courseMapper.selectByPK(courseEntity); if (null == courseEntity) { throw new NoSuchPageException("Contest not found!"); } return courseEntity; } }
UTF-8
Java
5,992
java
CourseValidator.java
Java
[ { "context": "ttpSession;\nimport java.util.List;\n\n/**\n * @author Mr.Minh\n * @since 14/03/2018\n * Purpose:\n */\n@Component(\"", "end": 907, "score": 0.9849480390548706, "start": 900, "tag": "NAME", "value": "Mr.Minh" } ]
null
[]
package com.minh.nguyen.validator; import com.minh.nguyen.constants.Constants; import com.minh.nguyen.dto.AuthorityDTO; import com.minh.nguyen.entity.ApplicationEntity; import com.minh.nguyen.entity.CourseEntity; import com.minh.nguyen.entity.SubmissionEntity; import com.minh.nguyen.exception.NoSuchPageException; import com.minh.nguyen.form.BaseForm; import com.minh.nguyen.mapper.ApplicationMapper; import com.minh.nguyen.mapper.AuthorityMapper; import com.minh.nguyen.mapper.CourseMapper; import com.minh.nguyen.mapper.SubmissionMapper; import com.minh.nguyen.validator.common.BaseValidator; import com.minh.nguyen.validator.common.BindingResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import javax.servlet.http.HttpSession; import java.util.List; /** * @author Mr.Minh * @since 14/03/2018 * Purpose: */ @Component("CourseValidator") public class CourseValidator extends BaseValidator { @Autowired private HttpSession httpSession; @Autowired private AuthorityMapper authorityMapper; @Autowired private CourseMapper courseMapper; @Autowired private ApplicationMapper applicationMapper; @Autowired private SubmissionMapper submissionMapper; public boolean checkApplyPermission(Integer ceId, Integer urId) { if (urId == null || ceId == null) { return false; } if (!checkRole(Constants.ROLE_STUDENT_TEXT)) { return false; } ApplicationEntity applicationEntity = new ApplicationEntity(); applicationEntity.setCeId(ceId); applicationEntity.setUrId(urId); List<ApplicationEntity> lstApply = applicationMapper.selectWithExample(applicationEntity); for (ApplicationEntity apply : lstApply) { if (apply.getStatus().equals(Constants.APPLICATION_STATUS_ACCEPTED)) { return false; } if (apply.getStatus().equals(Constants.APPLICATION_STATUS_PENDING)) { return false; } } return true; } //check if curent user has any authority in current contest public boolean checkPermission(Authentication auth, Integer ceId, String... authority) throws NoSuchPageException { List<AuthorityDTO> lstAuthority = authorityMapper.getCourseAuthority(ceId, auth.getName()); for (AuthorityDTO curAuth : lstAuthority) { for (String requireAuth : authority) { if (requireAuth.equals(curAuth.getName())) { return true; } } } return false; } public boolean checkViewSubmissionPermission(Authentication auth,Integer snId,Integer ceId){ List<AuthorityDTO> lstAuthority = authorityMapper.getCourseAuthority(ceId, auth.getName()); boolean flag = false; for (AuthorityDTO curAuth : lstAuthority) { if (curAuth.getId().equals(Constants.AUTH_VIEW_COURSE_ID)) { return true; } if (curAuth.getId().equals(Constants.AUTH_PARTICIPATE_COURSE_ID)) { flag = true; } } if (!flag){ return false; } CourseEntity courseEntity = getCourseById(ceId); if (courseEntity.getShowSubmit().equals(Constants.SHOW_SUBMIT_ALL)){ return true; } SubmissionEntity submissionEntity = new SubmissionEntity(); submissionEntity.setId(snId); List<SubmissionEntity> lstSubmission = submissionMapper.selectWithExample(submissionEntity); if (lstSubmission.size() != 1){ throw new NoSuchPageException("Submission not found!"); } //check if submission is from current user submissionEntity = lstSubmission.get(0); Integer currentUserId = (Integer)httpSession.getAttribute(Constants.CURRENT_LOGIN_USER_ID); if (submissionEntity.getUrId().equals(currentUserId)){ return true; } //else check current user has solved this problem and this contests allow to view solved problem's solutions if (courseEntity.getShowSubmit().equals(Constants.SHOW_SUBMIT_SOLVED)){ Integer solveCnt = submissionMapper.checkSolvedStatusInContest(ceId,submissionEntity.getPmId(),submissionEntity.getUrId()); return solveCnt > 0; } return false; } public boolean checkRole(String roleName) { Object currentRole = httpSession.getAttribute(Constants.CURRENT_LOGIN_USER_ROLE_NAME); return currentRole != null && currentRole.toString().equals(roleName); } public boolean checkParticipate(Authentication auth, Integer ctId) throws NoSuchPageException { List<AuthorityDTO> lstAuthority = authorityMapper.getCourseAuthority(ctId, auth.getName()); for (AuthorityDTO curAuth : lstAuthority) { if (curAuth.getId().equals(Constants.AUTH_PARTICIPATE_COURSE_ID)) { return true; } } //not participator return false; } //Check if user is the contest's creator public boolean checkCreator(Authentication authentication, Integer ceId) { CourseEntity courseEntity = getCourseById(ceId); return courseEntity.getCreateUser().equals(authentication.getName()); } @Override public void validateField(String fieldName, String fieldValue, BindingResult errors) { } @Override public void validateLogic(BaseForm clazz, BindingResult errors) { } private CourseEntity getCourseById(int ceId) { CourseEntity courseEntity = new CourseEntity(); courseEntity.setId(ceId); courseEntity = courseMapper.selectByPK(courseEntity); if (null == courseEntity) { throw new NoSuchPageException("Contest not found!"); } return courseEntity; } }
5,992
0.677737
0.675901
166
35.096386
30.854151
135
false
false
0
0
0
0
0
0
0.493976
false
false
15
a59d6a1362a1e0472fcda26eecf84c32410d0b81
2,800,318,737,595
258368999dc3e8f8c7991b2f102d7da091467cab
/src/test/java/WeatherForecastRepositoryTest.java
f3b3861847d5d3801a9a4e56a5a0f4a9f4392ad3
[]
no_license
lauraliism/weatherForecast
https://github.com/lauraliism/weatherForecast
c96afb821ee177a64f90f0e194ed0a186da8880f
d7c8072889c28bed8f5b0816484e6e8494f070e2
refs/heads/master
2021-08-31T12:31:37.578000
2017-12-21T09:16:31
2017-12-21T09:16:31
104,679,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.openweathermap.api.models.request.WeatherRequest; import org.openweathermap.api.repository.WeatherForecastRepository; import org.openweathermap.api.utility.HttpUtility; import org.openweathermap.api.utility.constants.Constants; import org.openweathermap.exception.NoWeatherReportException; import java.io.IOException; import java.util.HashMap; import static com.sun.tools.internal.ws.wsdl.parser.Util.fail; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Created by lauraliismetsvaht on 11/09/2017. */ public class WeatherForecastRepositoryTest { String mockCityName = "London"; String apiKey = "db1fb1d0d306a8dedfc165d671dd5e4d"; Constants.UNIT units = Constants.UNIT.metric; WeatherRequest request; WeatherForecastRepository repository; String currentWeatherResponse = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":300,\"main\":\"Drizzle\",\"description\":\"light intensity drizzle\",\"icon\":\"09n\"},{\"id\":701,\"main\":\"Mist\",\"description\":\"mist\",\"icon\":\"50n\"}],\"base\":\"stations\",\"main\":{\"temp\":10,\"pressure\":1035,\"humidity\":100,\"temp_min\":10,\"temp_max\":10},\"visibility\":1800,\"wind\":{\"speed\":2.6,\"deg\":260},\"clouds\":{\"all\":75},\"dt\":1513804800,\"sys\":{\"type\":1,\"id\":5088,\"message\":0.0051,\"country\":\"GB\",\"sunrise\":1513757029,\"sunset\":1513785210},\"id\":2643741,\"name\":\"London\",\"cod\":200}"; final String currentWeatherRequestUrl = "https://api.openweathermap.org/%2Fdata%2F2.5%2Fweather?q=Tallinn&units=metric&appid=db1fb1d0d306a8dedfc165d671dd5e4d"; @Before public void init() { request = new WeatherRequest(mockCityName, apiKey, units); repository = new WeatherForecastRepository(); } @Test public void doesGetCurrentTemperatureReturnTemperature() { try { assertEquals(repository.getCurrentTemperature(request).getClass(), Double.class); } catch (Exception e) { fail("Failure was caused by: "+ e.getMessage()); } } @Test public void doesGetThreeDaysHighestAndLowestTempReturnHashMap() { try { assertEquals(repository.getThreeDaysHighestAndLowestTemp(request).getClass(), HashMap.class); } catch (Exception e) { fail("Failure was caused by: "+ e.getMessage()); } } @Test public void doesGetCityCoordinatesReturnCoordinates() { try { assertEquals(repository.getCityCoordinates(request).getClass(), JSONObject.class); } catch (Exception e) { fail("Failure was caused by: "+ e.getMessage()); } } @Test public void testIfResponseWrittenToFileIsRequestedWithCorrectAppId() { try { final String APPID = repository.APPID; assertEquals(apiKey, APPID); } catch (Exception e) { fail("Failure was caused by: " + e.getMessage()); } } @Test public void testIfGetCityCoordinates2ReturnsCorrectResponse() throws IOException, NoWeatherReportException, JSONException { String coordinates = "{\"lon\":-0.13,\"lat\":51.51}"; JSONObject jsonObj = new JSONObject(coordinates); System.out.println("jsonObj" + jsonObj); HttpUtility utility = mock(HttpUtility.class); Mockito.when(utility.makeApiRequest(currentWeatherRequestUrl)).thenReturn(currentWeatherResponse); assertEquals(repository.getCityCoordinates2(currentWeatherRequestUrl, utility).toString(), jsonObj.toString()); } @Test public void testIfGetCityCoordinates2CallsCorrectAction() throws NoWeatherReportException, JSONException, IOException { HttpUtility utility = mock(HttpUtility.class); Mockito.when(utility.makeApiRequest(currentWeatherRequestUrl)).thenReturn(currentWeatherResponse); repository.getCityCoordinates2(currentWeatherRequestUrl, utility); verify(utility, times(1)).makeApiRequest(currentWeatherRequestUrl); } }
UTF-8
Java
3,942
java
WeatherForecastRepositoryTest.java
Java
[ { "context": "tic org.mockito.Mockito.verify;\n\n/**\n * Created by lauraliismetsvaht on 11/09/2017.\n */\npublic class WeatherForecastRe", "end": 759, "score": 0.9993129968643188, "start": 742, "tag": "USERNAME", "value": "lauraliismetsvaht" }, { "context": "String mockCityName = \"London\";\n\tString apiKey = \"db1fb1d0d306a8dedfc165d671dd5e4d\";\n\tConstants.UNIT units = Constants.UNIT.metric;\n", "end": 907, "score": 0.9997661113739014, "start": 875, "tag": "KEY", "value": "db1fb1d0d306a8dedfc165d671dd5e4d" } ]
null
[]
import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.openweathermap.api.models.request.WeatherRequest; import org.openweathermap.api.repository.WeatherForecastRepository; import org.openweathermap.api.utility.HttpUtility; import org.openweathermap.api.utility.constants.Constants; import org.openweathermap.exception.NoWeatherReportException; import java.io.IOException; import java.util.HashMap; import static com.sun.tools.internal.ws.wsdl.parser.Util.fail; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Created by lauraliismetsvaht on 11/09/2017. */ public class WeatherForecastRepositoryTest { String mockCityName = "London"; String apiKey = "db1fb1d0d306a8dedfc165d671dd5e4d"; Constants.UNIT units = Constants.UNIT.metric; WeatherRequest request; WeatherForecastRepository repository; String currentWeatherResponse = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":300,\"main\":\"Drizzle\",\"description\":\"light intensity drizzle\",\"icon\":\"09n\"},{\"id\":701,\"main\":\"Mist\",\"description\":\"mist\",\"icon\":\"50n\"}],\"base\":\"stations\",\"main\":{\"temp\":10,\"pressure\":1035,\"humidity\":100,\"temp_min\":10,\"temp_max\":10},\"visibility\":1800,\"wind\":{\"speed\":2.6,\"deg\":260},\"clouds\":{\"all\":75},\"dt\":1513804800,\"sys\":{\"type\":1,\"id\":5088,\"message\":0.0051,\"country\":\"GB\",\"sunrise\":1513757029,\"sunset\":1513785210},\"id\":2643741,\"name\":\"London\",\"cod\":200}"; final String currentWeatherRequestUrl = "https://api.openweathermap.org/%2Fdata%2F2.5%2Fweather?q=Tallinn&units=metric&appid=db1fb1d0d306a8dedfc165d671dd5e4d"; @Before public void init() { request = new WeatherRequest(mockCityName, apiKey, units); repository = new WeatherForecastRepository(); } @Test public void doesGetCurrentTemperatureReturnTemperature() { try { assertEquals(repository.getCurrentTemperature(request).getClass(), Double.class); } catch (Exception e) { fail("Failure was caused by: "+ e.getMessage()); } } @Test public void doesGetThreeDaysHighestAndLowestTempReturnHashMap() { try { assertEquals(repository.getThreeDaysHighestAndLowestTemp(request).getClass(), HashMap.class); } catch (Exception e) { fail("Failure was caused by: "+ e.getMessage()); } } @Test public void doesGetCityCoordinatesReturnCoordinates() { try { assertEquals(repository.getCityCoordinates(request).getClass(), JSONObject.class); } catch (Exception e) { fail("Failure was caused by: "+ e.getMessage()); } } @Test public void testIfResponseWrittenToFileIsRequestedWithCorrectAppId() { try { final String APPID = repository.APPID; assertEquals(apiKey, APPID); } catch (Exception e) { fail("Failure was caused by: " + e.getMessage()); } } @Test public void testIfGetCityCoordinates2ReturnsCorrectResponse() throws IOException, NoWeatherReportException, JSONException { String coordinates = "{\"lon\":-0.13,\"lat\":51.51}"; JSONObject jsonObj = new JSONObject(coordinates); System.out.println("jsonObj" + jsonObj); HttpUtility utility = mock(HttpUtility.class); Mockito.when(utility.makeApiRequest(currentWeatherRequestUrl)).thenReturn(currentWeatherResponse); assertEquals(repository.getCityCoordinates2(currentWeatherRequestUrl, utility).toString(), jsonObj.toString()); } @Test public void testIfGetCityCoordinates2CallsCorrectAction() throws NoWeatherReportException, JSONException, IOException { HttpUtility utility = mock(HttpUtility.class); Mockito.when(utility.makeApiRequest(currentWeatherRequestUrl)).thenReturn(currentWeatherResponse); repository.getCityCoordinates2(currentWeatherRequestUrl, utility); verify(utility, times(1)).makeApiRequest(currentWeatherRequestUrl); } }
3,942
0.748097
0.71106
98
39.224491
69.008064
633
false
false
0
0
0
0
0
0
1.94898
false
false
15
51ce77c69d47a9f73103a899fbc17d3add448fb4
6,210,522,749,114
30aea6a4f5dd70e96996c69b262c03e0afb32a9d
/src/LoginService.java
ec2de2730cbfa122cbd34e831bee2621c8b419d5
[]
no_license
basakozokcu/B21Project2
https://github.com/basakozokcu/B21Project2
109ab0db6f2b337ab5f21725e76938337957c048
c1478e125d77ca7b3f144678d385f70a0d0321b9
refs/heads/master
2023-01-11T07:09:35.496000
2020-11-17T23:45:08
2020-11-17T23:45:08
313,717,916
0
0
null
false
2020-11-17T23:45:09
2020-11-17T19:12:19
2020-11-17T23:42:11
2020-11-17T23:45:08
3
0
0
0
Java
false
false
public class LoginService { //awesome utulity here }
UTF-8
Java
57
java
LoginService.java
Java
[]
null
[]
public class LoginService { //awesome utulity here }
57
0.719298
0.719298
3
18
12.027745
27
false
false
0
0
0
0
0
0
0
false
false
15
d6c935eb4e708c464848e99268c1985d6e0cbe2c
18,348,100,307,611
ea5d4f2f63495acde31813fb2fd2ac9e893fcedb
/src/org/javaturk/oopj/ch13/string/StringPerformanceTest.java
d28d1bd0d50a38af6404f71d4072d9578e05d0a8
[ "MIT" ]
permissive
javaturk/OOPJ
https://github.com/javaturk/OOPJ
6a45256511b98a535af7147f467a83bb0c753025
37cd4d7f5517051a4894d8cf700ae9e0badd97fb
refs/heads/main
2023-08-15T03:27:51.833000
2023-07-19T15:39:34
2023-07-19T15:39:34
316,269,011
140
57
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.javaturk.oopj.ch13.string; /* * Method 100,000 1,000,000 10,000,000 * -------------------------------------------------------------- * String 15692 * StringBuilder 17 56 410 * StringBuffer 17 71 601 */ public class StringPerformanceTest { public static void main(String[] args) { // buildStringWithPlus("Java", 100_000); // buildStringWithStringBuilder("Java", 100_000); buildStringWithStringBuffer("Java", 100_000); } public static void buildStringWithPlus(String string, int count) { long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { string = string + i; } long end = System.currentTimeMillis(); System.out.println("buildStringWithPlus: Time to build string is " + (end - start) + " ms."); System.out.println("String length: " + string.length()); } public static void buildStringWithStringBuilder(String string, int count) { StringBuilder sb = new StringBuilder(string); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { sb.append(i); } long end = System.currentTimeMillis(); System.out.println("buildStringWithStringBuilder: Time to build string is " + (end - start) + " ms."); System.out.println("String length: " + sb.toString().length()); } public static void buildStringWithStringBuffer(String string, int count) { StringBuffer sb = new StringBuffer(string); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { sb.append(i); } long end = System.currentTimeMillis(); System.out.println("buildStringWithStringBuffer: Time to build string is " + (end - start) + " ms."); System.out.println("String length: " + sb.toString().length()); } }
UTF-8
Java
1,754
java
StringPerformanceTest.java
Java
[]
null
[]
package org.javaturk.oopj.ch13.string; /* * Method 100,000 1,000,000 10,000,000 * -------------------------------------------------------------- * String 15692 * StringBuilder 17 56 410 * StringBuffer 17 71 601 */ public class StringPerformanceTest { public static void main(String[] args) { // buildStringWithPlus("Java", 100_000); // buildStringWithStringBuilder("Java", 100_000); buildStringWithStringBuffer("Java", 100_000); } public static void buildStringWithPlus(String string, int count) { long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { string = string + i; } long end = System.currentTimeMillis(); System.out.println("buildStringWithPlus: Time to build string is " + (end - start) + " ms."); System.out.println("String length: " + string.length()); } public static void buildStringWithStringBuilder(String string, int count) { StringBuilder sb = new StringBuilder(string); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { sb.append(i); } long end = System.currentTimeMillis(); System.out.println("buildStringWithStringBuilder: Time to build string is " + (end - start) + " ms."); System.out.println("String length: " + sb.toString().length()); } public static void buildStringWithStringBuffer(String string, int count) { StringBuffer sb = new StringBuffer(string); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { sb.append(i); } long end = System.currentTimeMillis(); System.out.println("buildStringWithStringBuffer: Time to build string is " + (end - start) + " ms."); System.out.println("String length: " + sb.toString().length()); } }
1,754
0.643101
0.607184
49
34.775509
28.553041
104
false
false
0
0
0
0
0
0
2.55102
false
false
15
dcbcd9c46817dcb5b38ba163311981cb24cec917
20,650,202,786,661
eafae636c22b5d95db19e5271d58796bd7be4a66
/app-release-unsigned/sources/com/ismaeldivita/chipnavigation/ChipNavigationBar.java
a67974918417f8f96e1d20b8b708196af8e7c362
[]
no_license
agustrinaldokurniawan/News_Kotlin_Native
https://github.com/agustrinaldokurniawan/News_Kotlin_Native
5fb97e9c9199c464e64a6ef901b133c88da3db55
411f2ae0c01f2cc490f9b80a6b8f40196bc74176
refs/heads/main
2023-05-31T20:59:44.356000
2021-06-15T14:43:42
2021-06-15T14:43:42
377,077,236
0
0
null
false
2021-06-15T07:44:11
2021-06-15T07:38:27
2021-06-15T07:40:00
2021-06-15T07:44:11
0
0
0
0
null
false
false
package com.ismaeldivita.chipnavigation; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; import android.transition.TransitionManager; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import androidx.constraintlayout.helper.widget.Flow; import androidx.constraintlayout.widget.ConstraintLayout; import com.ismaeldivita.chipnavigation.model.Menu; import com.ismaeldivita.chipnavigation.model.MenuItem; import com.ismaeldivita.chipnavigation.model.MenuParser; import com.ismaeldivita.chipnavigation.model.MenuStyle; import com.ismaeldivita.chipnavigation.util.InsetsKt; import com.ismaeldivita.chipnavigation.util.ViewGroupKt; import com.ismaeldivita.chipnavigation.view.HorizontalMenuItemView; import com.ismaeldivita.chipnavigation.view.MenuItemView; import com.ismaeldivita.chipnavigation.view.VerticalMenuItemView; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import kotlin.NoWhenBranchMatchedException; import kotlin.TypeCastException; import kotlin.Unit; import kotlin.collections.CollectionsKt; import kotlin.collections.MapsKt; import kotlin.jvm.functions.Function1; import kotlin.jvm.internal.DefaultConstructorMarker; import kotlin.jvm.internal.Intrinsics; import kotlin.sequences.Sequence; import kotlin.sequences.SequencesKt; public final class ChipNavigationBar extends ConstraintLayout { private HashMap _$_findViewCache; private final Map<Integer, Integer> badgesState; private boolean isExpanded; private OnItemSelectedListener listener; private int menuRes; private final MenuStyle menuStyle; private int minimumExpandedWidth; private MenuOrientation orientationMode; public enum MenuOrientation { HORIZONTAL, VERTICAL } public interface OnItemSelectedListener { void onItemSelected(int i); } public final /* synthetic */ class WhenMappings { public static final /* synthetic */ int[] $EnumSwitchMapping$0; public static final /* synthetic */ int[] $EnumSwitchMapping$1; public static final /* synthetic */ int[] $EnumSwitchMapping$2; static { int[] iArr = new int[MenuOrientation.values().length]; $EnumSwitchMapping$0 = iArr; iArr[MenuOrientation.HORIZONTAL.ordinal()] = 1; iArr[MenuOrientation.VERTICAL.ordinal()] = 2; int[] iArr2 = new int[MenuOrientation.values().length]; $EnumSwitchMapping$1 = iArr2; iArr2[MenuOrientation.VERTICAL.ordinal()] = 1; iArr2[MenuOrientation.HORIZONTAL.ordinal()] = 2; int[] iArr3 = new int[MenuOrientation.values().length]; $EnumSwitchMapping$2 = iArr3; iArr3[MenuOrientation.HORIZONTAL.ordinal()] = 1; iArr3[MenuOrientation.VERTICAL.ordinal()] = 2; } } public ChipNavigationBar(Context context) { this(context, null, 2, null); } public void _$_clearFindViewByIdCache() { HashMap hashMap = this._$_findViewCache; if (hashMap != null) { hashMap.clear(); } } public View _$_findCachedViewById(int i) { if (this._$_findViewCache == null) { this._$_findViewCache = new HashMap(); } View view = (View) this._$_findViewCache.get(Integer.valueOf(i)); if (view != null) { return view; } View findViewById = findViewById(i); this._$_findViewCache.put(Integer.valueOf(i), findViewById); return findViewById; } /* JADX INFO: this call moved to the top of the method (can break code semantics) */ public /* synthetic */ ChipNavigationBar(Context context, AttributeSet attributeSet, int i, DefaultConstructorMarker defaultConstructorMarker) { this(context, (i & 2) != 0 ? null : attributeSet); } /* JADX INFO: super call moved to the top of the method (can break code semantics) */ public ChipNavigationBar(Context context, AttributeSet attributeSet) { super(context, attributeSet); MenuOrientation menuOrientation; Intrinsics.checkParameterIsNotNull(context, "context"); this.menuRes = -1; this.badgesState = new LinkedHashMap(); TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, R.styleable.ChipNavigationBar); int resourceId = obtainStyledAttributes.getResourceId(R.styleable.ChipNavigationBar_cnb_menuResource, -1); float dimension = obtainStyledAttributes.getDimension(R.styleable.ChipNavigationBar_cnb_minExpandedWidth, 0.0f); boolean z = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addLeftInset, false); boolean z2 = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addTopInset, false); boolean z3 = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addRightInset, false); boolean z4 = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addBottomInset, false); int i = obtainStyledAttributes.getInt(R.styleable.ChipNavigationBar_cnb_orientationMode, 0); if (i == 0) { menuOrientation = MenuOrientation.HORIZONTAL; } else if (i != 1) { menuOrientation = MenuOrientation.HORIZONTAL; } else { menuOrientation = MenuOrientation.VERTICAL; } Intrinsics.checkExpressionValueIsNotNull(obtainStyledAttributes, "a"); this.menuStyle = new MenuStyle(context, obtainStyledAttributes); obtainStyledAttributes.recycle(); setMenuOrientation(menuOrientation); if (resourceId >= 0) { setMenuResource(resourceId); } setMinimumExpandedWidth((int) dimension); InsetsKt.applyWindowInsets(this, z, z2, z3, z4); collapse(); setClickable(true); } public final void setMenuResource(int i) { Flow flow; this.menuRes = i; Context context = getContext(); Intrinsics.checkExpressionValueIsNotNull(context, "context"); Menu parse = new MenuParser(context).parse(i, this.menuStyle); ChipNavigationBar$setMenuResource$childListener$1 chipNavigationBar$setMenuResource$childListener$1 = new ChipNavigationBar$setMenuResource$childListener$1(this); removeAllViews(); Iterator<T> it = parse.getItems().iterator(); while (it.hasNext()) { MenuItemView createMenuItem = createMenuItem(); createMenuItem.bind(it.next()); createMenuItem.setOnClickListener(new ChipNavigationBar$sam$i$android_view_View_OnClickListener$0(chipNavigationBar$setMenuResource$childListener$1)); addView(createMenuItem); } MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } int i2 = WhenMappings.$EnumSwitchMapping$0[menuOrientation.ordinal()]; if (i2 == 1) { flow = getHorizontalFlow(); } else if (i2 == 2) { flow = getVerticalFlow(); } else { throw new NoWhenBranchMatchedException(); } List<MenuItem> items = parse.getItems(); ArrayList arrayList = new ArrayList(CollectionsKt.collectionSizeOrDefault(items, 10)); Iterator<T> it2 = items.iterator(); while (it2.hasNext()) { arrayList.add(Integer.valueOf(it2.next().getId())); } flow.setReferencedIds(CollectionsKt.toIntArray(arrayList)); addView(flow); } public final void setMenuOrientation(MenuOrientation menuOrientation) { Intrinsics.checkParameterIsNotNull(menuOrientation, "menuOrientation"); this.orientationMode = menuOrientation; } public final void setItemEnabled(int i, boolean z) { MenuItemView itemById = getItemById(i); if (itemById != null) { itemById.setEnabled(z); } } public static /* synthetic */ void setItemSelected$default(ChipNavigationBar chipNavigationBar, int i, boolean z, int i2, Object obj) { if ((i2 & 2) != 0) { z = true; } chipNavigationBar.setItemSelected(i, z); } public final void setItemSelected(int i, boolean z) { setItemSelected(i, z, true); } public final void setMinimumExpandedWidth(int i) { this.minimumExpandedWidth = i; } public final void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) { Intrinsics.checkParameterIsNotNull(onItemSelectedListener, "listener"); this.listener = onItemSelectedListener; } public final void setOnItemSelectedListener(Function1<? super Integer, Unit> function1) { Intrinsics.checkParameterIsNotNull(function1, "block"); setOnItemSelectedListener(new ChipNavigationBar$setOnItemSelectedListener$1(function1)); } public final void showBadge(int i) { this.badgesState.put(Integer.valueOf(i), 0); MenuItemView itemById = getItemById(i); if (itemById != null) { MenuItemView.showBadge$default(itemById, 0, 1, null); } } public final void showBadge(int i, int i2) { this.badgesState.put(Integer.valueOf(i), Integer.valueOf(i2)); MenuItemView itemById = getItemById(i); if (itemById != null) { itemById.showBadge(i2); } } public final void dismissBadge(int i) { this.badgesState.remove(Integer.valueOf(i)); MenuItemView itemById = getItemById(i); if (itemById != null) { itemById.dismissBadge(); } } public final void collapse() { this.isExpanded = false; MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } if (menuOrientation == MenuOrientation.VERTICAL) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View childAt = getChildAt(i); Intrinsics.checkExpressionValueIsNotNull(childAt, "getChildAt(i)"); childAt.setMinimumWidth(0); if (!(childAt instanceof VerticalMenuItemView)) { childAt = null; } VerticalMenuItemView verticalMenuItemView = (VerticalMenuItemView) childAt; if (verticalMenuItemView != null) { verticalMenuItemView.collapse(); } } } } public final void expand() { this.isExpanded = true; MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } if (menuOrientation == MenuOrientation.VERTICAL) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View childAt = getChildAt(i); Intrinsics.checkExpressionValueIsNotNull(childAt, "getChildAt(i)"); childAt.setMinimumWidth(this.minimumExpandedWidth); if (!(childAt instanceof VerticalMenuItemView)) { childAt = null; } VerticalMenuItemView verticalMenuItemView = (VerticalMenuItemView) childAt; if (verticalMenuItemView != null) { verticalMenuItemView.expand(); } } } } public final boolean isExpanded() { MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } int i = WhenMappings.$EnumSwitchMapping$1[menuOrientation.ordinal()]; if (i == 1) { return this.isExpanded; } if (i == 2) { return false; } throw new NoWhenBranchMatchedException(); } public final int getSelectedItemId() { View selectedItem = getSelectedItem(); if (selectedItem != null) { return selectedItem.getId(); } return -1; } private final void setItemSelected(int i, boolean z, boolean z2) { MenuItemView itemById; OnItemSelectedListener onItemSelectedListener; View selectedItem = getSelectedItem(); if (z && (selectedItem == null || selectedItem.getId() != i)) { if (selectedItem != null) { selectedItem.setSelected(false); } MenuItemView itemById2 = getItemById(i); if (itemById2 != null) { TransitionManager.beginDelayedTransition(this); itemById2.setSelected(true); if (z2 && (onItemSelectedListener = this.listener) != null) { onItemSelectedListener.onItemSelected(i); } } } else if (!z && (itemById = getItemById(i)) != null) { TransitionManager.beginDelayedTransition(this); itemById.setSelected(false); } } private final View getSelectedItem() { View view; Iterator<View> it = ViewGroupKt.getChildren(this).iterator(); while (true) { if (!it.hasNext()) { view = null; break; } view = it.next(); if (view.isSelected()) { break; } } return view; } private final MenuItemView getItemById(int i) { Object obj; boolean z; Sequence filter = SequencesKt.filter(ViewGroupKt.getChildren(this), ChipNavigationBar$getItemById$$inlined$filterIsInstance$1.INSTANCE); if (filter != null) { Iterator it = filter.iterator(); while (true) { if (!it.hasNext()) { obj = null; break; } obj = it.next(); if (((MenuItemView) obj).getId() == i) { z = true; continue; } else { z = false; continue; } if (z) { break; } } return (MenuItemView) obj; } throw new TypeCastException("null cannot be cast to non-null type kotlin.sequences.Sequence<R>"); } private final MenuItemView createMenuItem() { MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } int i = WhenMappings.$EnumSwitchMapping$2[menuOrientation.ordinal()]; if (i == 1) { Context context = getContext(); Intrinsics.checkExpressionValueIsNotNull(context, "context"); return new HorizontalMenuItemView(context, null, 2, null); } else if (i == 2) { Context context2 = getContext(); Intrinsics.checkExpressionValueIsNotNull(context2, "context"); return new VerticalMenuItemView(context2, null, 2, null); } else { throw new NoWhenBranchMatchedException(); } } private final Flow getHorizontalFlow() { Flow flow = new Flow(getContext()); flow.setOrientation(0); flow.setHorizontalStyle(0); flow.setHorizontalAlign(0); flow.setLayoutParams(new ViewGroup.LayoutParams(-1, -1)); return flow; } private final Flow getVerticalFlow() { Flow flow = new Flow(getContext()); flow.setOrientation(1); flow.setHorizontalAlign(0); flow.setLayoutParams(new ViewGroup.LayoutParams(-1, -2)); return flow; } public Parcelable onSaveInstanceState() { State state = new State(super.onSaveInstanceState(), new Bundle()); state.setMenuId(this.menuRes); state.setSelectedItem(getSelectedItemId()); state.setBadges(this.badgesState); state.setExpanded(this.isExpanded); state.setEnabled(MapsKt.toMap(SequencesKt.map(ViewGroupKt.getChildren(this), ChipNavigationBar$onSaveInstanceState$1$1.INSTANCE))); return state; } public void onRestoreInstanceState(Parcelable parcelable) { MenuItemView itemById; if (parcelable instanceof State) { State state = (State) parcelable; super.onRestoreInstanceState(state.getSuperState()); if (state.getMenuId() != -1) { setMenuResource(state.getMenuId()); } if (state.getSelectedItem() != -1) { setItemSelected(state.getSelectedItem(), true, false); } if (state.getExpanded()) { expand(); } else { collapse(); } for (Map.Entry<Integer, Integer> entry : state.getBadges().entrySet()) { int intValue = entry.getKey().intValue(); int intValue2 = entry.getValue().intValue(); if (intValue2 > 0) { showBadge(intValue, intValue2); } else { showBadge(intValue); } } for (Map.Entry<Integer, Boolean> entry2 : state.getEnabled().entrySet()) { int intValue3 = entry2.getKey().intValue(); boolean booleanValue = entry2.getValue().booleanValue(); if (!booleanValue && (itemById = getItemById(intValue3)) != null) { itemById.setEnabled(booleanValue); } } return; } super.onRestoreInstanceState(parcelable); } }
UTF-8
Java
18,147
java
ChipNavigationBar.java
Java
[]
null
[]
package com.ismaeldivita.chipnavigation; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; import android.transition.TransitionManager; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import androidx.constraintlayout.helper.widget.Flow; import androidx.constraintlayout.widget.ConstraintLayout; import com.ismaeldivita.chipnavigation.model.Menu; import com.ismaeldivita.chipnavigation.model.MenuItem; import com.ismaeldivita.chipnavigation.model.MenuParser; import com.ismaeldivita.chipnavigation.model.MenuStyle; import com.ismaeldivita.chipnavigation.util.InsetsKt; import com.ismaeldivita.chipnavigation.util.ViewGroupKt; import com.ismaeldivita.chipnavigation.view.HorizontalMenuItemView; import com.ismaeldivita.chipnavigation.view.MenuItemView; import com.ismaeldivita.chipnavigation.view.VerticalMenuItemView; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import kotlin.NoWhenBranchMatchedException; import kotlin.TypeCastException; import kotlin.Unit; import kotlin.collections.CollectionsKt; import kotlin.collections.MapsKt; import kotlin.jvm.functions.Function1; import kotlin.jvm.internal.DefaultConstructorMarker; import kotlin.jvm.internal.Intrinsics; import kotlin.sequences.Sequence; import kotlin.sequences.SequencesKt; public final class ChipNavigationBar extends ConstraintLayout { private HashMap _$_findViewCache; private final Map<Integer, Integer> badgesState; private boolean isExpanded; private OnItemSelectedListener listener; private int menuRes; private final MenuStyle menuStyle; private int minimumExpandedWidth; private MenuOrientation orientationMode; public enum MenuOrientation { HORIZONTAL, VERTICAL } public interface OnItemSelectedListener { void onItemSelected(int i); } public final /* synthetic */ class WhenMappings { public static final /* synthetic */ int[] $EnumSwitchMapping$0; public static final /* synthetic */ int[] $EnumSwitchMapping$1; public static final /* synthetic */ int[] $EnumSwitchMapping$2; static { int[] iArr = new int[MenuOrientation.values().length]; $EnumSwitchMapping$0 = iArr; iArr[MenuOrientation.HORIZONTAL.ordinal()] = 1; iArr[MenuOrientation.VERTICAL.ordinal()] = 2; int[] iArr2 = new int[MenuOrientation.values().length]; $EnumSwitchMapping$1 = iArr2; iArr2[MenuOrientation.VERTICAL.ordinal()] = 1; iArr2[MenuOrientation.HORIZONTAL.ordinal()] = 2; int[] iArr3 = new int[MenuOrientation.values().length]; $EnumSwitchMapping$2 = iArr3; iArr3[MenuOrientation.HORIZONTAL.ordinal()] = 1; iArr3[MenuOrientation.VERTICAL.ordinal()] = 2; } } public ChipNavigationBar(Context context) { this(context, null, 2, null); } public void _$_clearFindViewByIdCache() { HashMap hashMap = this._$_findViewCache; if (hashMap != null) { hashMap.clear(); } } public View _$_findCachedViewById(int i) { if (this._$_findViewCache == null) { this._$_findViewCache = new HashMap(); } View view = (View) this._$_findViewCache.get(Integer.valueOf(i)); if (view != null) { return view; } View findViewById = findViewById(i); this._$_findViewCache.put(Integer.valueOf(i), findViewById); return findViewById; } /* JADX INFO: this call moved to the top of the method (can break code semantics) */ public /* synthetic */ ChipNavigationBar(Context context, AttributeSet attributeSet, int i, DefaultConstructorMarker defaultConstructorMarker) { this(context, (i & 2) != 0 ? null : attributeSet); } /* JADX INFO: super call moved to the top of the method (can break code semantics) */ public ChipNavigationBar(Context context, AttributeSet attributeSet) { super(context, attributeSet); MenuOrientation menuOrientation; Intrinsics.checkParameterIsNotNull(context, "context"); this.menuRes = -1; this.badgesState = new LinkedHashMap(); TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, R.styleable.ChipNavigationBar); int resourceId = obtainStyledAttributes.getResourceId(R.styleable.ChipNavigationBar_cnb_menuResource, -1); float dimension = obtainStyledAttributes.getDimension(R.styleable.ChipNavigationBar_cnb_minExpandedWidth, 0.0f); boolean z = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addLeftInset, false); boolean z2 = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addTopInset, false); boolean z3 = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addRightInset, false); boolean z4 = obtainStyledAttributes.getBoolean(R.styleable.ChipNavigationBar_cnb_addBottomInset, false); int i = obtainStyledAttributes.getInt(R.styleable.ChipNavigationBar_cnb_orientationMode, 0); if (i == 0) { menuOrientation = MenuOrientation.HORIZONTAL; } else if (i != 1) { menuOrientation = MenuOrientation.HORIZONTAL; } else { menuOrientation = MenuOrientation.VERTICAL; } Intrinsics.checkExpressionValueIsNotNull(obtainStyledAttributes, "a"); this.menuStyle = new MenuStyle(context, obtainStyledAttributes); obtainStyledAttributes.recycle(); setMenuOrientation(menuOrientation); if (resourceId >= 0) { setMenuResource(resourceId); } setMinimumExpandedWidth((int) dimension); InsetsKt.applyWindowInsets(this, z, z2, z3, z4); collapse(); setClickable(true); } public final void setMenuResource(int i) { Flow flow; this.menuRes = i; Context context = getContext(); Intrinsics.checkExpressionValueIsNotNull(context, "context"); Menu parse = new MenuParser(context).parse(i, this.menuStyle); ChipNavigationBar$setMenuResource$childListener$1 chipNavigationBar$setMenuResource$childListener$1 = new ChipNavigationBar$setMenuResource$childListener$1(this); removeAllViews(); Iterator<T> it = parse.getItems().iterator(); while (it.hasNext()) { MenuItemView createMenuItem = createMenuItem(); createMenuItem.bind(it.next()); createMenuItem.setOnClickListener(new ChipNavigationBar$sam$i$android_view_View_OnClickListener$0(chipNavigationBar$setMenuResource$childListener$1)); addView(createMenuItem); } MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } int i2 = WhenMappings.$EnumSwitchMapping$0[menuOrientation.ordinal()]; if (i2 == 1) { flow = getHorizontalFlow(); } else if (i2 == 2) { flow = getVerticalFlow(); } else { throw new NoWhenBranchMatchedException(); } List<MenuItem> items = parse.getItems(); ArrayList arrayList = new ArrayList(CollectionsKt.collectionSizeOrDefault(items, 10)); Iterator<T> it2 = items.iterator(); while (it2.hasNext()) { arrayList.add(Integer.valueOf(it2.next().getId())); } flow.setReferencedIds(CollectionsKt.toIntArray(arrayList)); addView(flow); } public final void setMenuOrientation(MenuOrientation menuOrientation) { Intrinsics.checkParameterIsNotNull(menuOrientation, "menuOrientation"); this.orientationMode = menuOrientation; } public final void setItemEnabled(int i, boolean z) { MenuItemView itemById = getItemById(i); if (itemById != null) { itemById.setEnabled(z); } } public static /* synthetic */ void setItemSelected$default(ChipNavigationBar chipNavigationBar, int i, boolean z, int i2, Object obj) { if ((i2 & 2) != 0) { z = true; } chipNavigationBar.setItemSelected(i, z); } public final void setItemSelected(int i, boolean z) { setItemSelected(i, z, true); } public final void setMinimumExpandedWidth(int i) { this.minimumExpandedWidth = i; } public final void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) { Intrinsics.checkParameterIsNotNull(onItemSelectedListener, "listener"); this.listener = onItemSelectedListener; } public final void setOnItemSelectedListener(Function1<? super Integer, Unit> function1) { Intrinsics.checkParameterIsNotNull(function1, "block"); setOnItemSelectedListener(new ChipNavigationBar$setOnItemSelectedListener$1(function1)); } public final void showBadge(int i) { this.badgesState.put(Integer.valueOf(i), 0); MenuItemView itemById = getItemById(i); if (itemById != null) { MenuItemView.showBadge$default(itemById, 0, 1, null); } } public final void showBadge(int i, int i2) { this.badgesState.put(Integer.valueOf(i), Integer.valueOf(i2)); MenuItemView itemById = getItemById(i); if (itemById != null) { itemById.showBadge(i2); } } public final void dismissBadge(int i) { this.badgesState.remove(Integer.valueOf(i)); MenuItemView itemById = getItemById(i); if (itemById != null) { itemById.dismissBadge(); } } public final void collapse() { this.isExpanded = false; MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } if (menuOrientation == MenuOrientation.VERTICAL) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View childAt = getChildAt(i); Intrinsics.checkExpressionValueIsNotNull(childAt, "getChildAt(i)"); childAt.setMinimumWidth(0); if (!(childAt instanceof VerticalMenuItemView)) { childAt = null; } VerticalMenuItemView verticalMenuItemView = (VerticalMenuItemView) childAt; if (verticalMenuItemView != null) { verticalMenuItemView.collapse(); } } } } public final void expand() { this.isExpanded = true; MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } if (menuOrientation == MenuOrientation.VERTICAL) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View childAt = getChildAt(i); Intrinsics.checkExpressionValueIsNotNull(childAt, "getChildAt(i)"); childAt.setMinimumWidth(this.minimumExpandedWidth); if (!(childAt instanceof VerticalMenuItemView)) { childAt = null; } VerticalMenuItemView verticalMenuItemView = (VerticalMenuItemView) childAt; if (verticalMenuItemView != null) { verticalMenuItemView.expand(); } } } } public final boolean isExpanded() { MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } int i = WhenMappings.$EnumSwitchMapping$1[menuOrientation.ordinal()]; if (i == 1) { return this.isExpanded; } if (i == 2) { return false; } throw new NoWhenBranchMatchedException(); } public final int getSelectedItemId() { View selectedItem = getSelectedItem(); if (selectedItem != null) { return selectedItem.getId(); } return -1; } private final void setItemSelected(int i, boolean z, boolean z2) { MenuItemView itemById; OnItemSelectedListener onItemSelectedListener; View selectedItem = getSelectedItem(); if (z && (selectedItem == null || selectedItem.getId() != i)) { if (selectedItem != null) { selectedItem.setSelected(false); } MenuItemView itemById2 = getItemById(i); if (itemById2 != null) { TransitionManager.beginDelayedTransition(this); itemById2.setSelected(true); if (z2 && (onItemSelectedListener = this.listener) != null) { onItemSelectedListener.onItemSelected(i); } } } else if (!z && (itemById = getItemById(i)) != null) { TransitionManager.beginDelayedTransition(this); itemById.setSelected(false); } } private final View getSelectedItem() { View view; Iterator<View> it = ViewGroupKt.getChildren(this).iterator(); while (true) { if (!it.hasNext()) { view = null; break; } view = it.next(); if (view.isSelected()) { break; } } return view; } private final MenuItemView getItemById(int i) { Object obj; boolean z; Sequence filter = SequencesKt.filter(ViewGroupKt.getChildren(this), ChipNavigationBar$getItemById$$inlined$filterIsInstance$1.INSTANCE); if (filter != null) { Iterator it = filter.iterator(); while (true) { if (!it.hasNext()) { obj = null; break; } obj = it.next(); if (((MenuItemView) obj).getId() == i) { z = true; continue; } else { z = false; continue; } if (z) { break; } } return (MenuItemView) obj; } throw new TypeCastException("null cannot be cast to non-null type kotlin.sequences.Sequence<R>"); } private final MenuItemView createMenuItem() { MenuOrientation menuOrientation = this.orientationMode; if (menuOrientation == null) { Intrinsics.throwUninitializedPropertyAccessException("orientationMode"); } int i = WhenMappings.$EnumSwitchMapping$2[menuOrientation.ordinal()]; if (i == 1) { Context context = getContext(); Intrinsics.checkExpressionValueIsNotNull(context, "context"); return new HorizontalMenuItemView(context, null, 2, null); } else if (i == 2) { Context context2 = getContext(); Intrinsics.checkExpressionValueIsNotNull(context2, "context"); return new VerticalMenuItemView(context2, null, 2, null); } else { throw new NoWhenBranchMatchedException(); } } private final Flow getHorizontalFlow() { Flow flow = new Flow(getContext()); flow.setOrientation(0); flow.setHorizontalStyle(0); flow.setHorizontalAlign(0); flow.setLayoutParams(new ViewGroup.LayoutParams(-1, -1)); return flow; } private final Flow getVerticalFlow() { Flow flow = new Flow(getContext()); flow.setOrientation(1); flow.setHorizontalAlign(0); flow.setLayoutParams(new ViewGroup.LayoutParams(-1, -2)); return flow; } public Parcelable onSaveInstanceState() { State state = new State(super.onSaveInstanceState(), new Bundle()); state.setMenuId(this.menuRes); state.setSelectedItem(getSelectedItemId()); state.setBadges(this.badgesState); state.setExpanded(this.isExpanded); state.setEnabled(MapsKt.toMap(SequencesKt.map(ViewGroupKt.getChildren(this), ChipNavigationBar$onSaveInstanceState$1$1.INSTANCE))); return state; } public void onRestoreInstanceState(Parcelable parcelable) { MenuItemView itemById; if (parcelable instanceof State) { State state = (State) parcelable; super.onRestoreInstanceState(state.getSuperState()); if (state.getMenuId() != -1) { setMenuResource(state.getMenuId()); } if (state.getSelectedItem() != -1) { setItemSelected(state.getSelectedItem(), true, false); } if (state.getExpanded()) { expand(); } else { collapse(); } for (Map.Entry<Integer, Integer> entry : state.getBadges().entrySet()) { int intValue = entry.getKey().intValue(); int intValue2 = entry.getValue().intValue(); if (intValue2 > 0) { showBadge(intValue, intValue2); } else { showBadge(intValue); } } for (Map.Entry<Integer, Boolean> entry2 : state.getEnabled().entrySet()) { int intValue3 = entry2.getKey().intValue(); boolean booleanValue = entry2.getValue().booleanValue(); if (!booleanValue && (itemById = getItemById(intValue3)) != null) { itemById.setEnabled(booleanValue); } } return; } super.onRestoreInstanceState(parcelable); } }
18,147
0.623299
0.617127
458
38.622272
28.711472
170
false
false
0
0
0
0
0
0
0.700873
false
false
15
e8608242f4abcb76a1032e8d3caaeb164f452141
27,874,337,755,348
ac4f7345d2b01856875721cd64b0d1dee2afa3fb
/src/model/Karyawan.java
a2f62b63972cd742f217bb037bd6357dd7ff9f0a
[]
no_license
KaisarV/SIA
https://github.com/KaisarV/SIA
325e82404df9e58a074c0ca3aacc27030e9cc026
c16c9cdc816049c6baca4cb1a6477ff7bd1c9ab5
refs/heads/master
2023-08-10T20:22:26.367000
2021-09-30T04:22:42
2021-09-30T04:22:42
411,917,561
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import java.util.ArrayList; /** * * @author MrKaisar */ public class Karyawan extends Staff{ private int salary; private ArrayList<HadirEnum> listPresensiStaff = new ArrayList<HadirEnum>(); public Karyawan(){} public Karyawan(int salary) { this.salary = salary; } public Karyawan(int salary, String NIK) { super(NIK); this.salary = salary; } public Karyawan(int salary, String NIK, String nama, String alamat, String ttl, String telepon, ArrayList<HadirEnum> listPresensiStaff) { super(NIK, nama, alamat, ttl, telepon); this.salary = salary; this.listPresensiStaff = listPresensiStaff; } //getter setter public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public ArrayList<HadirEnum> getListPresensiStaff() { return listPresensiStaff; } public void setListPresensiStaff(ArrayList<HadirEnum> listPresensiStaff) { this.listPresensiStaff = listPresensiStaff; } @Override public String toString() { return super.toString() + "Karyawan{" + "salary=" + salary + ", listPresensiStaff=" + listPresensiStaff + '}'; } }
UTF-8
Java
1,285
java
Karyawan.java
Java
[ { "context": "l;\n\nimport java.util.ArrayList;\n\n/**\n *\n * @author MrKaisar\n */\npublic class Karyawan extends Staff{\n priv", "end": 72, "score": 0.998448371887207, "start": 64, "tag": "USERNAME", "value": "MrKaisar" } ]
null
[]
package model; import java.util.ArrayList; /** * * @author MrKaisar */ public class Karyawan extends Staff{ private int salary; private ArrayList<HadirEnum> listPresensiStaff = new ArrayList<HadirEnum>(); public Karyawan(){} public Karyawan(int salary) { this.salary = salary; } public Karyawan(int salary, String NIK) { super(NIK); this.salary = salary; } public Karyawan(int salary, String NIK, String nama, String alamat, String ttl, String telepon, ArrayList<HadirEnum> listPresensiStaff) { super(NIK, nama, alamat, ttl, telepon); this.salary = salary; this.listPresensiStaff = listPresensiStaff; } //getter setter public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public ArrayList<HadirEnum> getListPresensiStaff() { return listPresensiStaff; } public void setListPresensiStaff(ArrayList<HadirEnum> listPresensiStaff) { this.listPresensiStaff = listPresensiStaff; } @Override public String toString() { return super.toString() + "Karyawan{" + "salary=" + salary + ", listPresensiStaff=" + listPresensiStaff + '}'; } }
1,285
0.636576
0.636576
54
22.777779
28.838417
141
false
false
0
0
0
0
0
0
0.5
false
false
15
4233ecc57415302cb1e44d803d545f224b175489
884,763,311,869
fad94f8614d06efe1b90a62e983493d13c1062b5
/src/main/java/com/david/spring/aopconf/AopconfDemo.java
e04f447d7d3c9120986f9fc9c5620d601f26c7bf
[]
no_license
davidelena/java_learning
https://github.com/davidelena/java_learning
6e901e87c38e9c2f47081cbdf6609998fbe69414
1bf86914ca13e6718340b3d14de3a5a0ddd4896d
refs/heads/master
2022-05-19T00:15:59.257000
2016-01-21T07:05:15
2016-01-21T07:05:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.david.spring.aopconf; import org.apache.log4j.Logger; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AopconfDemo { private static Logger logger = Logger.getLogger(AopconfDemo.class.getSimpleName()); public static void main(String[] args) { logger.info("AopconfDemo Start..."); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("aop-spring-conf.xml"); CalculatorService service = (CalculatorService) ctx.getBean("calculatorService"); System.out.println(service.getClass().getName()); int add = service.add(1, 2); int divide = service.divide(12, 6); System.out.println("add result: " + add); System.out.println("divide result: " + divide); ctx.close(); logger.info("AopconfDemo End..."); } }
UTF-8
Java
791
java
AopconfDemo.java
Java
[]
null
[]
package com.david.spring.aopconf; import org.apache.log4j.Logger; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AopconfDemo { private static Logger logger = Logger.getLogger(AopconfDemo.class.getSimpleName()); public static void main(String[] args) { logger.info("AopconfDemo Start..."); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("aop-spring-conf.xml"); CalculatorService service = (CalculatorService) ctx.getBean("calculatorService"); System.out.println(service.getClass().getName()); int add = service.add(1, 2); int divide = service.divide(12, 6); System.out.println("add result: " + add); System.out.println("divide result: " + divide); ctx.close(); logger.info("AopconfDemo End..."); } }
791
0.750948
0.743363
22
34.954544
28.733063
97
false
false
0
0
0
0
0
0
1.818182
false
false
15
6f93956bca915effcfea9f1714c4f083f1c7c774
21,380,347,248,719
bd46fcd58357a4eec9d8e9b34560d99306aa6e48
/src/cn/chiucheung/pojo/warehouse/storagewarehouseworkcardstockin/Quantity.java
c9e310fa1ca1f84e0e21ba9c37d58ce0f7810a0d
[]
no_license
shishangzhe/chiucheung
https://github.com/shishangzhe/chiucheung
7d9be129e1a4436b4307dd62e79d2c1aebdda0dd
f5e56de765c758305a7e8295057f0ba049aa96c6
refs/heads/master
2020-08-03T14:42:33.164000
2019-09-30T09:40:09
2019-09-30T09:40:09
211,789,157
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.chiucheung.pojo.warehouse.storagewarehouseworkcardstockin; /** * 用于入库单的重新审核,存储入库单对应物料的入库数量、现存数量、占有量 * @author adm-03 * */ public class Quantity { private Integer stockInQuantity;//入库数量 private Integer existingQuantity;//现存数量 private Integer occupyQuantity;//占有量 public Integer getStockInQuantity() { return stockInQuantity; } public void setStockInQuantity(Integer stockInQuantity) { this.stockInQuantity = stockInQuantity; } public Integer getExistingQuantity() { return existingQuantity; } public void setExistingQuantity(Integer existingQuantity) { this.existingQuantity = existingQuantity; } public Integer getOccupyQuantity() { return occupyQuantity; } public void setOccupyQuantity(Integer occupyQuantity) { this.occupyQuantity = occupyQuantity; } }
UTF-8
Java
898
java
Quantity.java
Java
[ { "context": "*\n * 用于入库单的重新审核,存储入库单对应物料的入库数量、现存数量、占有量\n * @author adm-03\n *\n */\npublic class Quantity {\n\tprivate Integer s", "end": 129, "score": 0.9995673894882202, "start": 123, "tag": "USERNAME", "value": "adm-03" } ]
null
[]
package cn.chiucheung.pojo.warehouse.storagewarehouseworkcardstockin; /** * 用于入库单的重新审核,存储入库单对应物料的入库数量、现存数量、占有量 * @author adm-03 * */ public class Quantity { private Integer stockInQuantity;//入库数量 private Integer existingQuantity;//现存数量 private Integer occupyQuantity;//占有量 public Integer getStockInQuantity() { return stockInQuantity; } public void setStockInQuantity(Integer stockInQuantity) { this.stockInQuantity = stockInQuantity; } public Integer getExistingQuantity() { return existingQuantity; } public void setExistingQuantity(Integer existingQuantity) { this.existingQuantity = existingQuantity; } public Integer getOccupyQuantity() { return occupyQuantity; } public void setOccupyQuantity(Integer occupyQuantity) { this.occupyQuantity = occupyQuantity; } }
898
0.779703
0.777228
38
20.289474
21.278736
69
false
false
0
0
0
0
0
0
1.026316
false
false
15
cc39db72055cd6a80a76305663116b3c503843e0
26,113,401,169,210
01f07cffa35e1b1f706f7eafefce0e05bf44f82b
/Training/src/exceptions/sum.java
6782162b57e1313adcef82d2ccc7e0ca7e2d814b
[]
no_license
rupikareddy1/Training
https://github.com/rupikareddy1/Training
9ac39f131942b038b1fbf3a9e557fd5ee7c18d8d
ea9d6fdd7dd9738eab1d9c27a02184a1f1758c43
refs/heads/master
2020-06-04T12:35:13.837000
2019-06-24T16:39:53
2019-06-24T16:39:53
192,024,033
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exceptions; import java.util.Scanner; public class sum { public static void main(String args[]) { int a,b,c,sum=0; Scanner s=new Scanner(System.in); System.out.println("Enter the value of a"); a=s.nextInt(); System.out.println("Enter the value of b"); b=s.nextInt(); System.out.println("Enter the value of c"); c=s.nextInt(); s.close(); try { sum=a+b+c; if(sum>=100) { throw new Exception("Please enter the numbers whose total is below 100"); } else { System.out.println("The sum is:"+sum); } } catch(Exception e) { System.out.println(e); } } }
UTF-8
Java
635
java
sum.java
Java
[]
null
[]
package exceptions; import java.util.Scanner; public class sum { public static void main(String args[]) { int a,b,c,sum=0; Scanner s=new Scanner(System.in); System.out.println("Enter the value of a"); a=s.nextInt(); System.out.println("Enter the value of b"); b=s.nextInt(); System.out.println("Enter the value of c"); c=s.nextInt(); s.close(); try { sum=a+b+c; if(sum>=100) { throw new Exception("Please enter the numbers whose total is below 100"); } else { System.out.println("The sum is:"+sum); } } catch(Exception e) { System.out.println(e); } } }
635
0.606299
0.595276
34
16.67647
17.571234
76
false
false
0
0
0
0
0
0
1.882353
false
false
15
01ac2076b749aa4f45d64ff268bd74f001c3b7e9
2,173,253,494,503
b4bef481cbba7b0114d69395c3564e1a6a057bad
/faceshow-interface/src/test/java/com/imTest/ImDelGropBean.java
e4e4c2b8b70e0abc5a570c17e2a8eb328fa9452e
[]
no_license
mls1615/faceshow
https://github.com/mls1615/faceshow
03376d18a8b126c43762ec221f7d475b618e44e1
a1e10053464e5211bc33fbbc19bf8f80fecbb61a
refs/heads/master
2020-04-16T17:10:34.429000
2019-01-14T06:52:38
2019-01-14T06:52:38
165,765,640
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imTest; import java.util.List; public class ImDelGropBean { private String GroupId; private String[]MemberToDel_Account; public String getGroupId() { return GroupId; } public void setGroupId(String groupId) { GroupId = groupId; } public String[] getMemberToDel_Account() { return MemberToDel_Account; } public void setMemberToDel_Account(String[] memberToDel_Account) { MemberToDel_Account = memberToDel_Account; } }
UTF-8
Java
507
java
ImDelGropBean.java
Java
[]
null
[]
package com.imTest; import java.util.List; public class ImDelGropBean { private String GroupId; private String[]MemberToDel_Account; public String getGroupId() { return GroupId; } public void setGroupId(String groupId) { GroupId = groupId; } public String[] getMemberToDel_Account() { return MemberToDel_Account; } public void setMemberToDel_Account(String[] memberToDel_Account) { MemberToDel_Account = memberToDel_Account; } }
507
0.668639
0.668639
24
20.125
19.626328
70
false
false
0
0
0
0
0
0
0.333333
false
false
15
98877fef22ee5474a741dc703fd6bbf6f2b4d7c7
29,824,252,950,798
b2f687f8386795e934894ad43a5bf6ef09f4531a
/src/com/revature/SampleLauncher.java
7b64505ec21e2de3c8607d55a471fd0d84d8b1f9
[]
no_license
revature-191007/hello-world
https://github.com/revature-191007/hello-world
db6f93d59329f44e64e44a36ab5bb8fc0eba6ee4
c47325663e4f795aaff562ce791d25b867f04a0f
refs/heads/master
2020-08-07T12:21:29.027000
2019-10-09T18:15:58
2019-10-09T18:15:58
213,448,960
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.revature; /** * Java Conventions: * * Packages - Classes are organized into packages. Packages are written * in all lower case, with subpackages referenced using dot-notation, and * generally start with reverse domain name convention. * * * Classes - Classes represent encapsulated types within Java. All Java * code is within some kind of class. Java files (.java) must have the same * name as the top-level public type contained within. A single .java file can have * only one top-level public type. * * * Main method - The main method represent the starting point for execution * in a java application. A Java app can have more than one main method, * but probably shouldn't. The Java main method has a strictly defined * method signature, if you do not follow that method signature correctly * it will not be recognized as the starting point. * * Valid Variations: * public static void main(String[] args) {} <-- most common * public static void main(String args[]) {} * public static void main(String... args) {} <-- using varargs * * Compiling Java: * javac * Use javac to compile .java files to .class files (bytecode) * -- javac SampleLauncher.java * Running: * java * Use java to run compiled .java files (from src folder with package names) * -- java com.revature.SampleLauncher */ public class SampleLauncher { public static void main(String[] args) { System.out.println("Hello World!"); } }
UTF-8
Java
1,489
java
SampleLauncher.java
Java
[]
null
[]
package com.revature; /** * Java Conventions: * * Packages - Classes are organized into packages. Packages are written * in all lower case, with subpackages referenced using dot-notation, and * generally start with reverse domain name convention. * * * Classes - Classes represent encapsulated types within Java. All Java * code is within some kind of class. Java files (.java) must have the same * name as the top-level public type contained within. A single .java file can have * only one top-level public type. * * * Main method - The main method represent the starting point for execution * in a java application. A Java app can have more than one main method, * but probably shouldn't. The Java main method has a strictly defined * method signature, if you do not follow that method signature correctly * it will not be recognized as the starting point. * * Valid Variations: * public static void main(String[] args) {} <-- most common * public static void main(String args[]) {} * public static void main(String... args) {} <-- using varargs * * Compiling Java: * javac * Use javac to compile .java files to .class files (bytecode) * -- javac SampleLauncher.java * Running: * java * Use java to run compiled .java files (from src folder with package names) * -- java com.revature.SampleLauncher */ public class SampleLauncher { public static void main(String[] args) { System.out.println("Hello World!"); } }
1,489
0.707858
0.707858
37
39.18919
28.657188
84
false
false
0
0
0
0
0
0
0.810811
false
false
15
69d8cddf0c49cceab9558e74a92948f65a50832b
33,672,543,636,366
46c85d2f6a53193e685af8d988e0eef69f9b9113
/src/com/alysoft/algo/heap/RearrangeCharacters.java
d0abcde13fc131505ab649fd2c98d9db8466082d
[]
no_license
ymohammad/algorithms
https://github.com/ymohammad/algorithms
7a4613c50f89bc0cd89456e5d8a1a70a1bebf076
44ea66b0bd7ef7a9a49a9c759e60b260d20065e5
refs/heads/master
2021-08-07T19:34:03.579000
2021-07-28T07:42:03
2021-07-28T07:42:03
97,962,372
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alysoft.algo.heap; import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; /** * Given a string S with repeated characters (only lowercase). The task is to rearrange characters in a string such that no two * adjacent characters are same. Note : It may be assumed that the string has only lowercase English alphabets. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a single line containing a string of lowercase english alphabets. Output: For each test case in a new line print "1" (without quotes) if the generated string doesn't contains any same adjacent characters, else if no such string is possible to be made print "0" (without quotes). Your Task: You are required to complete the method rearrangeString() which takes 1 argument and returns the string without any same adjacent character. Constraints: 1 <= T <= 100 1 <= length of string <= 104 Example: Input: 3 geeksforgeeks bbbabaaacd bbbbb Output: 1 1 0 Explanation: Testcase 1: All the repeated characters of the given string can be rearranged so that no adjacent characters in the string is equal. Testcase 3: Repeated characters in the string cannot be rearranged such that there should not be any adjacent repeated character. * @author ymohammad * */ public class RearrangeCharacters { public static void main(String[] args) { String str = "kkk"; rearrangeCharacters(str); } static boolean rearrangeCharacters(String str) { int[] charHash = new int[26]; char[] charArr = str.toCharArray(); for (char ch : charArr) { charHash[getCharIndex(ch)]++; } PriorityQueue<CharBean> pq = new PriorityQueue<CharBean>(new ComparatorHandler()); for (int i = 0; i<26; i++) { if (charHash[i]>0) { pq.add(new CharBean(getChar(i), charHash[i])); } } CharBean prevBean = null; CharBean temp = null; while (!pq.isEmpty()) { temp = pq.poll(); temp.freq--; if (prevBean != null && temp.ch == prevBean.ch) return false; if (prevBean != null && prevBean.freq > 0) { pq.add(prevBean); } if (pq.isEmpty() && temp.freq > 0) return false; if (!pq.isEmpty()) prevBean = temp; } if (prevBean.ch == temp.ch) return false; return true; } static char getChar(int index) { int x = 'a'+index; return (char)x; } static int getCharIndex(char ch) { return ch-'a'; } static class ComparatorHandler implements Comparator<CharBean> { @Override public int compare(CharBean b1, CharBean b2) { if (b1.freq > b2.freq) return -1; if (b1.freq == b2.freq) return 0; return 1; } } static class CharBean { char ch; int freq; public CharBean(char ch, int freq) { this.ch = ch; this.freq = freq; } @Override public String toString() { return "Char=" + ch + "; Freq=" + freq; } } }
UTF-8
Java
3,105
java
RearrangeCharacters.java
Java
[ { "context": "ot be any adjacent repeated character.\r\n * @author ymohammad\r\n *\r\n */\r\npublic class RearrangeCharacters\r\n{\r\n\r\n", "end": 1405, "score": 0.9280182123184204, "start": 1396, "tag": "USERNAME", "value": "ymohammad" } ]
null
[]
package com.alysoft.algo.heap; import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; /** * Given a string S with repeated characters (only lowercase). The task is to rearrange characters in a string such that no two * adjacent characters are same. Note : It may be assumed that the string has only lowercase English alphabets. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a single line containing a string of lowercase english alphabets. Output: For each test case in a new line print "1" (without quotes) if the generated string doesn't contains any same adjacent characters, else if no such string is possible to be made print "0" (without quotes). Your Task: You are required to complete the method rearrangeString() which takes 1 argument and returns the string without any same adjacent character. Constraints: 1 <= T <= 100 1 <= length of string <= 104 Example: Input: 3 geeksforgeeks bbbabaaacd bbbbb Output: 1 1 0 Explanation: Testcase 1: All the repeated characters of the given string can be rearranged so that no adjacent characters in the string is equal. Testcase 3: Repeated characters in the string cannot be rearranged such that there should not be any adjacent repeated character. * @author ymohammad * */ public class RearrangeCharacters { public static void main(String[] args) { String str = "kkk"; rearrangeCharacters(str); } static boolean rearrangeCharacters(String str) { int[] charHash = new int[26]; char[] charArr = str.toCharArray(); for (char ch : charArr) { charHash[getCharIndex(ch)]++; } PriorityQueue<CharBean> pq = new PriorityQueue<CharBean>(new ComparatorHandler()); for (int i = 0; i<26; i++) { if (charHash[i]>0) { pq.add(new CharBean(getChar(i), charHash[i])); } } CharBean prevBean = null; CharBean temp = null; while (!pq.isEmpty()) { temp = pq.poll(); temp.freq--; if (prevBean != null && temp.ch == prevBean.ch) return false; if (prevBean != null && prevBean.freq > 0) { pq.add(prevBean); } if (pq.isEmpty() && temp.freq > 0) return false; if (!pq.isEmpty()) prevBean = temp; } if (prevBean.ch == temp.ch) return false; return true; } static char getChar(int index) { int x = 'a'+index; return (char)x; } static int getCharIndex(char ch) { return ch-'a'; } static class ComparatorHandler implements Comparator<CharBean> { @Override public int compare(CharBean b1, CharBean b2) { if (b1.freq > b2.freq) return -1; if (b1.freq == b2.freq) return 0; return 1; } } static class CharBean { char ch; int freq; public CharBean(char ch, int freq) { this.ch = ch; this.freq = freq; } @Override public String toString() { return "Char=" + ch + "; Freq=" + freq; } } }
3,105
0.647343
0.636393
117
24.538462
31.263845
140
false
false
0
0
0
0
0
0
1.350427
false
false
15
82da1f13a95267b08d6e091ff214ecd2d8081087
20,925,080,689,308
d812824f1a152054fbc4b7deaf03c94daf8baca1
/src/Graph.java
029290df7270758424cccc16c14d8aa76417188d
[]
no_license
bbain123/LabyrinthSolver
https://github.com/bbain123/LabyrinthSolver
601e076b6439f6a0de96dd1fbd6b29e82d3a9bd4
6423b3e076af1e5eb680dabdefb66a25d9d027dc
refs/heads/main
2023-07-14T02:17:54.749000
2021-08-13T02:26:02
2021-08-13T02:26:02
395,497,813
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class Graph implements GraphADT{ private int numNodes; private Edge adjMat[][]; //Adjacency matrix storing edges private Node nodesInGraph[]; //list of nodes in graph public Graph(int n) { adjMat = new Edge[n][n]; nodesInGraph = new Node[n]; for (int i = 0; i < n; i++) //store Nodes 0 to n-1 nodesInGraph[i] = new Node(i); } public void insertEdge(Node nodeu, Node nodev, int type, String label) throws GraphException{ Edge tempEdge = new Edge(nodeu, nodev, type, label); if(nodeu == null || nodev == null) { //check if nodes exist throw new GraphException("node doesnt exist"); } if(nodev.getName() < nodeu.getName()) //set smaller node as first in pair tempEdge = new Edge(nodev, nodeu, type, label); //place temp in [u][v] and [v][u] if its empty (smaller node, larger node) if(adjMat[nodeu.getName()][nodev.getName()] == null && adjMat[nodev.getName()][nodeu.getName()] == null) { adjMat[nodeu.getName()][nodev.getName()] = tempEdge; adjMat[nodev.getName()][nodeu.getName()] = tempEdge; } else throw new GraphException("cannot replace edge"); //if edge already stored, throw Graphexception } public void insertEdge(Node nodeu, Node nodev, int type) throws GraphException{ //same but without label Edge tempEdge = new Edge(nodeu, nodev, type); if(nodeu == null || nodev == null) throw new GraphException("node doesnt exist"); if(nodeu.getName() >= nodesInGraph.length || nodev.getName() >= nodesInGraph.length) throw new GraphException("invalid edge"); if(nodev.getName() < nodeu.getName()) tempEdge = new Edge(nodev, nodeu, type); //place temp in [u][v] and [v][u] if it doesnt have anything else if(adjMat[nodeu.getName()][nodev.getName()] == null && adjMat[nodev.getName()][nodeu.getName()] == null) { adjMat[nodeu.getName()][nodev.getName()] = tempEdge; adjMat[nodev.getName()][nodeu.getName()] = tempEdge; } else throw new GraphException("cannot replace edge"); } public Node getNode(int u) throws GraphException{ //if u is not in range of 0 to n - 1, dont have node for(int i = 0; i < nodesInGraph.length; i++) { if (nodesInGraph[i].getName() == u) return nodesInGraph[i]; } throw new GraphException("Node " + u + " is not in the graph"); } public Iterator<Edge> incidentEdges(Node u) throws GraphException{ //returns edges incident to u getNode(u.getName()); //check if node exists ArrayList<Edge>incident = new ArrayList<Edge>(); for(int i = 0; i < nodesInGraph.length; i++) { //from same column as u name, go row by row and add all that arent null if(adjMat[u.getName()][i] != null) incident.add(adjMat[u.getName()][i]); } Iterator<Edge>incidents = incident.iterator(); return incidents; } public Edge getEdge(Node u, Node v) throws GraphException{ //return edge of u and v if it exists getNode(u.getName()); getNode(v.getName()); if(adjMat[u.getName()][v.getName()] != null) return adjMat[u.getName()][v.getName()]; else throw new GraphException("no edge between node " + u.getName() + " and node "+v.getName()); } public boolean areAdjacent(Node u, Node v) throws GraphException{ //for each node incident to u, check if nodes incident to that are paired with v getNode(u.getName()); getNode(v.getName()); Iterator<Edge>uEdges = incidentEdges(u); Node connectedU; //node that is connected to u while(uEdges.hasNext()) { Edge nextConnectU = uEdges.next(); //next edge connected to u if(nextConnectU.firstEndpoint().getName() == u.getName()) //get the node from edge that is not u connectedU = nextConnectU.secondEndpoint(); else connectedU = nextConnectU.firstEndpoint(); Iterator<Edge>neighEdges = incidentEdges(connectedU); //get edges connected to edge connected to u while(neighEdges.hasNext()) { Edge nextConnectCU = neighEdges.next(); //node that is connected to connectedU Node connectedCU; if(nextConnectCU.firstEndpoint().getName() == connectedU.getName()) connectedCU = nextConnectCU.secondEndpoint(); else connectedCU = nextConnectCU.firstEndpoint(); Iterator<Edge> vEdges = incidentEdges(connectedCU); //get edges of neighEdges and look for v while(vEdges.hasNext()) { Edge vNext = vEdges.next(); if(vNext.firstEndpoint().getName() == v.getName()) return true; else if (vNext.secondEndpoint().getName() == v.getName()) return true; } } } return false; } }
UTF-8
Java
4,712
java
Graph.java
Java
[]
null
[]
import java.util.*; public class Graph implements GraphADT{ private int numNodes; private Edge adjMat[][]; //Adjacency matrix storing edges private Node nodesInGraph[]; //list of nodes in graph public Graph(int n) { adjMat = new Edge[n][n]; nodesInGraph = new Node[n]; for (int i = 0; i < n; i++) //store Nodes 0 to n-1 nodesInGraph[i] = new Node(i); } public void insertEdge(Node nodeu, Node nodev, int type, String label) throws GraphException{ Edge tempEdge = new Edge(nodeu, nodev, type, label); if(nodeu == null || nodev == null) { //check if nodes exist throw new GraphException("node doesnt exist"); } if(nodev.getName() < nodeu.getName()) //set smaller node as first in pair tempEdge = new Edge(nodev, nodeu, type, label); //place temp in [u][v] and [v][u] if its empty (smaller node, larger node) if(adjMat[nodeu.getName()][nodev.getName()] == null && adjMat[nodev.getName()][nodeu.getName()] == null) { adjMat[nodeu.getName()][nodev.getName()] = tempEdge; adjMat[nodev.getName()][nodeu.getName()] = tempEdge; } else throw new GraphException("cannot replace edge"); //if edge already stored, throw Graphexception } public void insertEdge(Node nodeu, Node nodev, int type) throws GraphException{ //same but without label Edge tempEdge = new Edge(nodeu, nodev, type); if(nodeu == null || nodev == null) throw new GraphException("node doesnt exist"); if(nodeu.getName() >= nodesInGraph.length || nodev.getName() >= nodesInGraph.length) throw new GraphException("invalid edge"); if(nodev.getName() < nodeu.getName()) tempEdge = new Edge(nodev, nodeu, type); //place temp in [u][v] and [v][u] if it doesnt have anything else if(adjMat[nodeu.getName()][nodev.getName()] == null && adjMat[nodev.getName()][nodeu.getName()] == null) { adjMat[nodeu.getName()][nodev.getName()] = tempEdge; adjMat[nodev.getName()][nodeu.getName()] = tempEdge; } else throw new GraphException("cannot replace edge"); } public Node getNode(int u) throws GraphException{ //if u is not in range of 0 to n - 1, dont have node for(int i = 0; i < nodesInGraph.length; i++) { if (nodesInGraph[i].getName() == u) return nodesInGraph[i]; } throw new GraphException("Node " + u + " is not in the graph"); } public Iterator<Edge> incidentEdges(Node u) throws GraphException{ //returns edges incident to u getNode(u.getName()); //check if node exists ArrayList<Edge>incident = new ArrayList<Edge>(); for(int i = 0; i < nodesInGraph.length; i++) { //from same column as u name, go row by row and add all that arent null if(adjMat[u.getName()][i] != null) incident.add(adjMat[u.getName()][i]); } Iterator<Edge>incidents = incident.iterator(); return incidents; } public Edge getEdge(Node u, Node v) throws GraphException{ //return edge of u and v if it exists getNode(u.getName()); getNode(v.getName()); if(adjMat[u.getName()][v.getName()] != null) return adjMat[u.getName()][v.getName()]; else throw new GraphException("no edge between node " + u.getName() + " and node "+v.getName()); } public boolean areAdjacent(Node u, Node v) throws GraphException{ //for each node incident to u, check if nodes incident to that are paired with v getNode(u.getName()); getNode(v.getName()); Iterator<Edge>uEdges = incidentEdges(u); Node connectedU; //node that is connected to u while(uEdges.hasNext()) { Edge nextConnectU = uEdges.next(); //next edge connected to u if(nextConnectU.firstEndpoint().getName() == u.getName()) //get the node from edge that is not u connectedU = nextConnectU.secondEndpoint(); else connectedU = nextConnectU.firstEndpoint(); Iterator<Edge>neighEdges = incidentEdges(connectedU); //get edges connected to edge connected to u while(neighEdges.hasNext()) { Edge nextConnectCU = neighEdges.next(); //node that is connected to connectedU Node connectedCU; if(nextConnectCU.firstEndpoint().getName() == connectedU.getName()) connectedCU = nextConnectCU.secondEndpoint(); else connectedCU = nextConnectCU.firstEndpoint(); Iterator<Edge> vEdges = incidentEdges(connectedCU); //get edges of neighEdges and look for v while(vEdges.hasNext()) { Edge vNext = vEdges.next(); if(vNext.firstEndpoint().getName() == v.getName()) return true; else if (vNext.secondEndpoint().getName() == v.getName()) return true; } } } return false; } }
4,712
0.646435
0.644949
126
35.412697
34.39529
148
false
false
0
0
0
0
0
0
3.246032
false
false
15
47e3cb74b589a4dab5d83e605657a29802a031a7
2,181,843,444,235
7b968b63f48667bdc81ef9d04cdc8541e5c22696
/src/fatec/json/handler/QSon.java
b049a8b450fa5d6ba87fc3f5c37a3097ac2a019c
[]
no_license
vitfgarcia/QDA-Library
https://github.com/vitfgarcia/QDA-Library
e9cfd1dcf5a91afaa3d8c7a5deb37fa9f77e4425
38a70d05f863ebb4cd9da40d0c12eda95dd4f30a
refs/heads/master
2021-07-15T18:50:34.255000
2017-09-08T15:21:44
2017-09-08T15:21:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fatec.json.handler; import java.io.FileReader; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import fatec.json.model.QSonElement; public class QSon { public JsonElement stringToJson(String str) { return new JsonParser().parse(str); } public JsonElement fileToJson(FileReader path) throws IOException { return new JsonParser().parse(path); } public Map<String, Map<String, String>> jsonToMap(JsonElement element) { Map<String, Map<String, String>> jsonMap = new TreeMap<String, Map<String, String>>(); JsonObject obj = (JsonObject) element; obj.entrySet().forEach(entry -> { JsonObject objects = (JsonObject) elementToJson(entry.getValue()); Map<String, String> childs = getChildNodes(objects.entrySet()); jsonMap.put(entry.getKey(), childs); }); return jsonMap; } public JsonElement merge(QSonElement... elements) { JsonElement[] verifiedJsons = prepareElements(elements); JsonElement[] jsons = elementsToJsonArray(verifiedJsons); JsonObject result = (JsonObject) jsons[0]; int length = jsons.length; for (int index = 1; length > 1; index++, length--) { JsonObject obj = (JsonObject) jsons[index]; result = (JsonObject) recursivelyMerge(result, obj); } return result; } public JsonElement jsonToAttribute(String key, JsonElement element) { JsonElement json = element; if (json.isJsonNull()) { return element; } String str = json.toString(); String attr = String.format("{ \"%s\": ", key); attr = String.format("{ \"%s\": ", key); attr = attr.concat(str).concat("}"); return stringToJson(attr); } private JsonElement elementToJson(JsonElement json) { return json; } private JsonElement[] elementsToJsonArray(JsonElement... str) { JsonElement[] elements = new JsonElement[str.length]; for (int i = 0; i < elements.length; i++) { elements[i] = str[i]; } return elements; } private Map<String, String> getChildNodes(Set<Entry<String, JsonElement>> entries) { Map<String, String> jsonChildsMap = new TreeMap<String, String>(); entries.forEach(entry -> { jsonChildsMap.put(entry.getKey(), entry.getValue().getAsString()); }); return jsonChildsMap; } private JsonElement[] prepareElements(QSonElement[] elements) { JsonElement[] result = new JsonElement[elements.length]; for (int i = 0; i < elements.length; i++) { JsonElement json = elements[i].getJson(); if (json.isJsonArray()) { elements[i].setJson(jsonToAttribute(elements[i].getKey(), json)); } result[i] = elements[i].getJson(); } return result; } private JsonElement recursivelyMerge(JsonObject target, JsonObject source) { source.entrySet().forEach(entry -> { if (!target.has(entry.getKey())) { target.add(entry.getKey(), entry.getValue()); } }); return target; } }
UTF-8
Java
2,999
java
QSon.java
Java
[]
null
[]
package fatec.json.handler; import java.io.FileReader; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import fatec.json.model.QSonElement; public class QSon { public JsonElement stringToJson(String str) { return new JsonParser().parse(str); } public JsonElement fileToJson(FileReader path) throws IOException { return new JsonParser().parse(path); } public Map<String, Map<String, String>> jsonToMap(JsonElement element) { Map<String, Map<String, String>> jsonMap = new TreeMap<String, Map<String, String>>(); JsonObject obj = (JsonObject) element; obj.entrySet().forEach(entry -> { JsonObject objects = (JsonObject) elementToJson(entry.getValue()); Map<String, String> childs = getChildNodes(objects.entrySet()); jsonMap.put(entry.getKey(), childs); }); return jsonMap; } public JsonElement merge(QSonElement... elements) { JsonElement[] verifiedJsons = prepareElements(elements); JsonElement[] jsons = elementsToJsonArray(verifiedJsons); JsonObject result = (JsonObject) jsons[0]; int length = jsons.length; for (int index = 1; length > 1; index++, length--) { JsonObject obj = (JsonObject) jsons[index]; result = (JsonObject) recursivelyMerge(result, obj); } return result; } public JsonElement jsonToAttribute(String key, JsonElement element) { JsonElement json = element; if (json.isJsonNull()) { return element; } String str = json.toString(); String attr = String.format("{ \"%s\": ", key); attr = String.format("{ \"%s\": ", key); attr = attr.concat(str).concat("}"); return stringToJson(attr); } private JsonElement elementToJson(JsonElement json) { return json; } private JsonElement[] elementsToJsonArray(JsonElement... str) { JsonElement[] elements = new JsonElement[str.length]; for (int i = 0; i < elements.length; i++) { elements[i] = str[i]; } return elements; } private Map<String, String> getChildNodes(Set<Entry<String, JsonElement>> entries) { Map<String, String> jsonChildsMap = new TreeMap<String, String>(); entries.forEach(entry -> { jsonChildsMap.put(entry.getKey(), entry.getValue().getAsString()); }); return jsonChildsMap; } private JsonElement[] prepareElements(QSonElement[] elements) { JsonElement[] result = new JsonElement[elements.length]; for (int i = 0; i < elements.length; i++) { JsonElement json = elements[i].getJson(); if (json.isJsonArray()) { elements[i].setJson(jsonToAttribute(elements[i].getKey(), json)); } result[i] = elements[i].getJson(); } return result; } private JsonElement recursivelyMerge(JsonObject target, JsonObject source) { source.entrySet().forEach(entry -> { if (!target.has(entry.getKey())) { target.add(entry.getKey(), entry.getValue()); } }); return target; } }
2,999
0.696566
0.694898
124
23.185484
24.629633
88
false
false
0
0
0
0
0
0
1.822581
false
false
15
c9ea822947587b22eb4ab36f09b1ef281826c913
14,044,543,080,378
cd7c96c056af5b18193346e19bc17db097edbdef
/myedu/src/main/java/com/myedu/project/store/domain/YunStoreEqu.java
88c1d4348655d1154750ed9a6d5ee475ef34307d
[ "MIT" ]
permissive
HiveEdu/CloudEdu
https://github.com/HiveEdu/CloudEdu
05732b9b4e436ab79eda1de4800c8a3502669a3a
ddc7592400734cdb7cc21448a2e0a0f37451d6ad
refs/heads/master
2022-11-30T17:26:52.001000
2020-08-14T14:14:27
2020-08-14T14:14:27
229,068,841
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myedu.project.store.domain; import com.myedu.framework.aspectj.lang.annotation.Excel; import com.myedu.framework.web.domain.BaseEntity; import io.swagger.annotations.ApiModelProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * 门店设备对象 yun_store_equ * * @author lsp * @date 2020-05-04 */ public class YunStoreEqu extends BaseEntity { private static final long serialVersionUID = 1L; /** 主键 */ private Long id; /** 所属门店 */ @Excel(name = "所属门店") private Long storeId; /** 设备名称 */ @Excel(name = "设备名称") private String equName; /** 设备型号 */ @Excel(name = "设备型号") private String model; /** 设备地址 */ @Excel(name = "设备地址") private String address; /** 设备登录名 */ @Excel(name = "设备登录名") private String userName; /** 设备登录密码 */ @Excel(name = "设备登录密码") private String passward; /** 端口 */ @Excel(name = "端口") private String port; /** 状态(1在线2离线) */ @Excel(name = "状态(1在线2离线)") private String status; /** 是否可用 */ @Excel(name = "是否可用") private String isuse; /** 删除标志(0代表存在 1代表删除) */ private String delFlag; /** 创建人Id */ @Excel(name = "创建人Id") private Long createById; /** 门店名称 */ private String storeName; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setStoreId(Long storeId) { this.storeId = storeId; } public Long getStoreId() { return storeId; } public void setEquName(String equName) { this.equName = equName; } public String getEquName() { return equName; } public void setModel(String model) { this.model = model; } public String getModel() { return model; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public void setUserName(String userName) { this.userName = userName; } public String getUserName() { return userName; } public void setPassward(String passward) { this.passward = passward; } public String getPassward() { return passward; } public void setPort(String port) { this.port = port; } public String getPort() { return port; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setIsuse(String isuse) { this.isuse = isuse; } public String getIsuse() { return isuse; } public void setDelFlag(String delFlag) { this.delFlag = delFlag; } public String getDelFlag() { return delFlag; } public void setCreateById(Long createById) { this.createById = createById; } public Long getCreateById() { return createById; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("storeId", getStoreId()) .append("equName", getEquName()) .append("model", getModel()) .append("address", getAddress()) .append("userName", getUserName()) .append("passward", getPassward()) .append("port", getPort()) .append("status", getStatus()) .append("isuse", getIsuse()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("delFlag", getDelFlag()) .append("createById", getCreateById()) .append("storeName", getStoreName()) .toString(); } }
UTF-8
Java
4,462
java
YunStoreEqu.java
Java
[ { "context": "gStyle;\n/**\n * 门店设备对象 yun_store_equ\n * \n * @author lsp\n * @date 2020-05-04\n */\npublic class YunStoreEqu ", "end": 355, "score": 0.999475359916687, "start": 352, "tag": "USERNAME", "value": "lsp" }, { "context": "me(String userName) \n {\n this.userName = userName;\n }\n\n public String getUserName() \n {\n ", "end": 2157, "score": 0.9887433052062988, "start": 2149, "tag": "USERNAME", "value": "userName" }, { "context": " public String getUserName() \n {\n return userName;\n }\n public void setPassward(String passwar", "end": 2228, "score": 0.9552209377288818, "start": 2220, "tag": "USERNAME", "value": "userName" }, { "context": " getAddress())\n .append(\"userName\", getUserName())\n .append(\"passward\", getPassward())", "end": 3694, "score": 0.9360582828521729, "start": 3686, "tag": "USERNAME", "value": "UserName" } ]
null
[]
package com.myedu.project.store.domain; import com.myedu.framework.aspectj.lang.annotation.Excel; import com.myedu.framework.web.domain.BaseEntity; import io.swagger.annotations.ApiModelProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * 门店设备对象 yun_store_equ * * @author lsp * @date 2020-05-04 */ public class YunStoreEqu extends BaseEntity { private static final long serialVersionUID = 1L; /** 主键 */ private Long id; /** 所属门店 */ @Excel(name = "所属门店") private Long storeId; /** 设备名称 */ @Excel(name = "设备名称") private String equName; /** 设备型号 */ @Excel(name = "设备型号") private String model; /** 设备地址 */ @Excel(name = "设备地址") private String address; /** 设备登录名 */ @Excel(name = "设备登录名") private String userName; /** 设备登录密码 */ @Excel(name = "设备登录密码") private String passward; /** 端口 */ @Excel(name = "端口") private String port; /** 状态(1在线2离线) */ @Excel(name = "状态(1在线2离线)") private String status; /** 是否可用 */ @Excel(name = "是否可用") private String isuse; /** 删除标志(0代表存在 1代表删除) */ private String delFlag; /** 创建人Id */ @Excel(name = "创建人Id") private Long createById; /** 门店名称 */ private String storeName; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setStoreId(Long storeId) { this.storeId = storeId; } public Long getStoreId() { return storeId; } public void setEquName(String equName) { this.equName = equName; } public String getEquName() { return equName; } public void setModel(String model) { this.model = model; } public String getModel() { return model; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public void setUserName(String userName) { this.userName = userName; } public String getUserName() { return userName; } public void setPassward(String passward) { this.passward = passward; } public String getPassward() { return passward; } public void setPort(String port) { this.port = port; } public String getPort() { return port; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setIsuse(String isuse) { this.isuse = isuse; } public String getIsuse() { return isuse; } public void setDelFlag(String delFlag) { this.delFlag = delFlag; } public String getDelFlag() { return delFlag; } public void setCreateById(Long createById) { this.createById = createById; } public Long getCreateById() { return createById; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("storeId", getStoreId()) .append("equName", getEquName()) .append("model", getModel()) .append("address", getAddress()) .append("userName", getUserName()) .append("passward", getPassward()) .append("port", getPort()) .append("status", getStatus()) .append("isuse", getIsuse()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("delFlag", getDelFlag()) .append("createById", getCreateById()) .append("storeName", getStoreName()) .toString(); } }
4,462
0.562235
0.558227
204
19.794117
16.479837
71
false
false
0
0
0
0
0
0
0.318627
false
false
15
cc50077c3435b6e3580883cb0fcbf54df514f274
29,635,274,369,678
4b4dcd257fe292f0e50a6e6565b96fc418af98eb
/algoritmos/OrientacaoObj/Orientacao_a_Objetos/TesteTurma.java
492c13e251757b5d2503191e373cbe3b4020c3e5
[]
no_license
ItamarHavenstein/Algorit
https://github.com/ItamarHavenstein/Algorit
fda91eeabb6b3e13648784b7fc17e3fea5802b6f
f7ff7e3e5eebf4ef753213be9e5b36a8755aab4f
refs/heads/master
2021-01-21T11:26:51.384000
2017-08-19T02:09:35
2017-08-19T02:09:35
91,739,682
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Orientacao_a_Objetos; public class TesteTurma { public static void main(String[] args) { Turma turma1 = new Turma (); turma1.setPeriodo("Matutino"); turma1.setSerie(1); turma1.setSigla("MAT"); turma1.setTipoEnsino("Presencial"); System.out.println("Periodo "+turma1.getPeriodo()+ " da serie "+turma1.getSerie()+ " da turma "+turma1.getSigla()+ " com tipo de ensino "+turma1.getTipoEnsino()); } }
UTF-8
Java
482
java
TesteTurma.java
Java
[]
null
[]
package Orientacao_a_Objetos; public class TesteTurma { public static void main(String[] args) { Turma turma1 = new Turma (); turma1.setPeriodo("Matutino"); turma1.setSerie(1); turma1.setSigla("MAT"); turma1.setTipoEnsino("Presencial"); System.out.println("Periodo "+turma1.getPeriodo()+ " da serie "+turma1.getSerie()+ " da turma "+turma1.getSigla()+ " com tipo de ensino "+turma1.getTipoEnsino()); } }
482
0.612033
0.591286
18
24.777779
17.290188
55
false
false
0
0
0
0
0
0
1.277778
false
false
15
4ba5bfa84d7cd857e3900537e4f182bed5440d28
8,383,776,181,960
c5feaf4401ff6071958aabe7ad1917f1c7d13c23
/src/main/model/Warrior.java
733e0e21ebdffe8646f1cc6dc217bd0330f05cb7
[]
no_license
Zou-jj/CPSC210_project
https://github.com/Zou-jj/CPSC210_project
f5d45090a1d1c23637a554a9c2ef1ce6aa2e8eeb
085503148ec4792bc44aa774c752ccae5628cba8
refs/heads/master
2023-04-20T00:45:12.729000
2021-05-12T06:07:40
2021-05-12T06:07:40
366,608,464
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import org.json.JSONObject; import persistence.Writable; import java.util.Objects; // Represents a warrior with some abilities public class Warrior implements Writable { private String name; private int attack; private int defense; // REQUIRES: name has a non-zero length // EFFECTS: creates a warrior with the name given public Warrior(String name) { this.name = name; } public String getName() { return name; } public int getAttack() { return attack; } public int getDefense() { return defense; } // REQUIRES: name has a non-zero length // MODIFIES: this // EFFECTS: rename the warrior with the name given public void rename(String name) { this.name = name; } // MODIFIES: this // EFFECTS: set warrior's attack to given value public void setAttack(int attack) { if (attack > 0) { this.attack = attack; } else { this.attack = 0; } } // MODIFIES: this // EFFECTS: set warrior's defense to given value public void setDefense(int defense) { if (defense > 0) { this.defense = defense; } else { this.defense = 0; } } // EFFECTS: add this warrior to the json file and returns the json file @Override public JSONObject toJson() { JSONObject json = new JSONObject(); json.put("name", name); json.put("attack", attack); json.put("defense", defense); return json; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Warrior warrior = (Warrior) o; return Objects.equals(name, warrior.name); } @Override public int hashCode() { return Objects.hash(name); } } /* *Title:JsonSerializationDemo *Author:Paul Carter *Date:Oct 17, 2020 *Availability:https://github.students.cs.ubc.ca/CPSC210/JsonSerializationDemo */
UTF-8
Java
2,122
java
Warrior.java
Java
[ { "context": " }\n}\n\n/*\n *Title:JsonSerializationDemo\n *Author:Paul Carter\n *Date:Oct 17, 2020\n *Availability:https://github", "end": 2019, "score": 0.9998716115951538, "start": 2008, "tag": "NAME", "value": "Paul Carter" } ]
null
[]
package model; import org.json.JSONObject; import persistence.Writable; import java.util.Objects; // Represents a warrior with some abilities public class Warrior implements Writable { private String name; private int attack; private int defense; // REQUIRES: name has a non-zero length // EFFECTS: creates a warrior with the name given public Warrior(String name) { this.name = name; } public String getName() { return name; } public int getAttack() { return attack; } public int getDefense() { return defense; } // REQUIRES: name has a non-zero length // MODIFIES: this // EFFECTS: rename the warrior with the name given public void rename(String name) { this.name = name; } // MODIFIES: this // EFFECTS: set warrior's attack to given value public void setAttack(int attack) { if (attack > 0) { this.attack = attack; } else { this.attack = 0; } } // MODIFIES: this // EFFECTS: set warrior's defense to given value public void setDefense(int defense) { if (defense > 0) { this.defense = defense; } else { this.defense = 0; } } // EFFECTS: add this warrior to the json file and returns the json file @Override public JSONObject toJson() { JSONObject json = new JSONObject(); json.put("name", name); json.put("attack", attack); json.put("defense", defense); return json; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Warrior warrior = (Warrior) o; return Objects.equals(name, warrior.name); } @Override public int hashCode() { return Objects.hash(name); } } /* *Title:JsonSerializationDemo *Author:<NAME> *Date:Oct 17, 2020 *Availability:https://github.students.cs.ubc.ca/CPSC210/JsonSerializationDemo */
2,117
0.583412
0.577286
92
22.076086
17.603256
78
false
false
0
0
0
0
0
0
0.358696
false
false
15
998fbc5f2223fdf5df5582780db40a3fef4a8944
14,654,428,440,534
365097452340a56f0d7dfb1c1b061bfc54585887
/app/src/main/java/br/com/homelab/artnate/Dialogs/BarcodeDialog.java
55298cb9c2fa53db4f13fd1385ae52f7c63f8146
[]
no_license
enzotiezzi/ArtNate
https://github.com/enzotiezzi/ArtNate
9503c12b65d55519091df46182e6b0c9487b3b46
3113ee7d1d8e1c2f2d4a3addcf15418d41cc8941
refs/heads/master
2021-01-17T21:11:09.328000
2016-08-09T18:39:58
2016-08-09T18:39:58
65,096,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.homelab.artnate.Dialogs; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; import br.com.homelab.artnate.R; /** * Created by enzo on 07/08/2016. */ public class BarcodeDialog extends Dialog { private String codigo = ""; public BarcodeDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.content_codigobarras); TextView textViewCancelar = (TextView) findViewById(R.id.textViewCancelar); textViewCancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } public void setCodigo(String codigo) { this.codigo = codigo; } }
UTF-8
Java
1,122
java
BarcodeDialog.java
Java
[ { "context": "mport br.com.homelab.artnate.R;\n\n/**\n * Created by enzo on 07/08/2016.\n */\npublic class BarcodeDialog ext", "end": 330, "score": 0.9995646476745605, "start": 326, "tag": "USERNAME", "value": "enzo" } ]
null
[]
package br.com.homelab.artnate.Dialogs; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; import br.com.homelab.artnate.R; /** * Created by enzo on 07/08/2016. */ public class BarcodeDialog extends Dialog { private String codigo = ""; public BarcodeDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.content_codigobarras); TextView textViewCancelar = (TextView) findViewById(R.id.textViewCancelar); textViewCancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } public void setCodigo(String codigo) { this.codigo = codigo; } }
1,122
0.661319
0.654189
48
22.375
19.956854
83
false
false
0
0
0
0
0
0
0.395833
false
false
15
2944ecd3063571602eccc0abaa655a7fb60d3d51
16,690,242,936,688
797ef2713aeb0280b2167481644c708d8f941ff9
/Assignments/Assignment6/Main.java
4e58584a08b6dcb9099c0433feb4a3cb72ba0654
[]
no_license
HenziKou/CIS-212_18S
https://github.com/HenziKou/CIS-212_18S
fc87ca417122a3204fd8d2e1c7ffa313f7b9482a
4d064604d8e14f30ee825a8eb4eb6fa630e63c15
refs/heads/master
2021-01-09T12:01:14.491000
2020-02-23T01:00:16
2020-02-23T01:00:16
242,293,654
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; public class Main { public static void main(String[] args) { // testing functionality of OccurrenceSet class with integers OccurrenceSet<Integer> intSet = new OccurrenceSet<Integer> (); // adding integer elements to the intSet intSet.add(1); intSet.add(3); intSet.add(5); intSet.add(5); intSet.add(3); intSet.add(3); intSet.add(3); System.out.println(intSet); // to array types System.out.println("to array: " + Arrays.toString(intSet.toArray())); intSet.add(9); intSet.add(10); intSet.add(3); intSet.add(3); System.out.println(intSet); Integer[] intList = new Integer[intSet.size()]; System.out.println("to array S[]: " + Arrays.toString(intSet.toArray(intList))); System.out.println("size: " + intSet.size()); System.out.println("contains 5: " + intSet.contains(5)); // testing functionality of OccurrenceSet class with strings OccurrenceSet<String> stringSet = new OccurrenceSet<String> (); // adding string elements to the stringSet stringSet.add("hello"); stringSet.add("hello"); stringSet.add("world"); stringSet.add("world"); stringSet.add("world"); stringSet.add("here"); System.out.println(stringSet); // test cases for each method in OccurrenceSet System.out.println(stringSet.size()); System.out.println(stringSet.isEmpty()); System.out.println(stringSet.contains(1)); System.out.println(stringSet.contains("hello")); System.out.println(stringSet.add("is")); System.out.println(stringSet.contains("is")); System.out.println(stringSet.remove("is")); System.out.println(stringSet.contains("is")); stringSet.clear(); System.out.println(stringSet.size()); // size and string representation System.out.println(); System.out.println(stringSet + " " + stringSet.size()); // testing addAll OccurrenceSet<String> addtest = new OccurrenceSet<String>(); addtest.add("hello"); addtest.add("there"); addtest.add("world"); addtest.add("a"); addtest.add("is"); System.out.println(); System.out.println(addtest); stringSet.addAll(addtest); System.out.println(stringSet); // remove all test and contains all tests System.out.println(); System.out.println(stringSet.containsAll(addtest)); stringSet.removeAll(addtest); System.out.println(); System.out.println(stringSet); System.out.println(stringSet.containsAll(addtest)); stringSet.clear(); System.out.println(); System.out.println("clear: " + stringSet); } } // end class Main
UTF-8
Java
2,577
java
Main.java
Java
[]
null
[]
import java.util.Arrays; public class Main { public static void main(String[] args) { // testing functionality of OccurrenceSet class with integers OccurrenceSet<Integer> intSet = new OccurrenceSet<Integer> (); // adding integer elements to the intSet intSet.add(1); intSet.add(3); intSet.add(5); intSet.add(5); intSet.add(3); intSet.add(3); intSet.add(3); System.out.println(intSet); // to array types System.out.println("to array: " + Arrays.toString(intSet.toArray())); intSet.add(9); intSet.add(10); intSet.add(3); intSet.add(3); System.out.println(intSet); Integer[] intList = new Integer[intSet.size()]; System.out.println("to array S[]: " + Arrays.toString(intSet.toArray(intList))); System.out.println("size: " + intSet.size()); System.out.println("contains 5: " + intSet.contains(5)); // testing functionality of OccurrenceSet class with strings OccurrenceSet<String> stringSet = new OccurrenceSet<String> (); // adding string elements to the stringSet stringSet.add("hello"); stringSet.add("hello"); stringSet.add("world"); stringSet.add("world"); stringSet.add("world"); stringSet.add("here"); System.out.println(stringSet); // test cases for each method in OccurrenceSet System.out.println(stringSet.size()); System.out.println(stringSet.isEmpty()); System.out.println(stringSet.contains(1)); System.out.println(stringSet.contains("hello")); System.out.println(stringSet.add("is")); System.out.println(stringSet.contains("is")); System.out.println(stringSet.remove("is")); System.out.println(stringSet.contains("is")); stringSet.clear(); System.out.println(stringSet.size()); // size and string representation System.out.println(); System.out.println(stringSet + " " + stringSet.size()); // testing addAll OccurrenceSet<String> addtest = new OccurrenceSet<String>(); addtest.add("hello"); addtest.add("there"); addtest.add("world"); addtest.add("a"); addtest.add("is"); System.out.println(); System.out.println(addtest); stringSet.addAll(addtest); System.out.println(stringSet); // remove all test and contains all tests System.out.println(); System.out.println(stringSet.containsAll(addtest)); stringSet.removeAll(addtest); System.out.println(); System.out.println(stringSet); System.out.println(stringSet.containsAll(addtest)); stringSet.clear(); System.out.println(); System.out.println("clear: " + stringSet); } } // end class Main
2,577
0.67986
0.67404
97
25.567011
19.640011
84
false
false
0
0
0
0
0
0
2.731959
false
false
15
bcf89701baa3d02097abcda3779cb46af88df371
4,733,053,987,177
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_227ca54dc882222ff01436895a99d3e9652d975d/DigitalSensor/2_227ca54dc882222ff01436895a99d3e9652d975d_DigitalSensor_t.java
f3e19e0766704c4d612d25ef38ff405e705e1638
[]
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
/* * This file is part of LinkJVM. * * Java Framework for the KIPR Link * Copyright (C) 2013 Markus Klein<m@mklein.co.at> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package linkjvm.high.sensors.digital; import linkjvm.high.sensors.InvalidPortException; import linkjvm.low.Digital; import linkjvm.low.factory.JNIController; /** * An instance of this class is used to control one digital sensor on the specified sensor port. * @author Markus Klein * @since 2.0.0 * @version 2.0.0 */ public class DigitalSensor implements IDigitalSensor{ private volatile Digital jniSensor; private int port; /** * Creates a new digital sensor on the specified port. * The invocation {@code DigitalSensor sensor = new DigitalSensor(0)} is equivalent to: * {@code DigitalSensor sensor = new DigitalSensor(); * sensor.setPort(0);} * * @param port the sensor's port * @throws InvalidPortException */ public DigitalSensor(int port) throws InvalidPortException{ if(port < 8 || port > 15){ throw new InvalidPortException(); } this.port = port; jniSensor = JNIController.getInstance().getDigitalFactory().getInstance(port); } /** * Returns the sensor port. * @return sensor port */ public int getPort(){ return port; } /** * Sets the sensor's port. * @param port sensor's port */ public void setPort(int port){ jniSensor = JNIController.getInstance().getDigitalFactory().getInstance(port); this.port = port; } /** * Returns the current sensor value. * @return sensor value */ @Override public boolean getValue(){ return !jniSensor.value(); } }
UTF-8
Java
2,289
java
2_227ca54dc882222ff01436895a99d3e9652d975d_DigitalSensor_t.java
Java
[ { "context": "Framework for the KIPR Link\n * Copyright (C) 2013 Markus Klein<m@mklein.co.at>\n *\n * This program is free soft", "end": 114, "score": 0.9998944401741028, "start": 102, "tag": "NAME", "value": "Markus Klein" }, { "context": "the KIPR Link\n * Copyright (C) 2013 Markus Klein<m@mklein.co.at>\n *\n * This program is free software: you can r", "end": 129, "score": 0.999933123588562, "start": 115, "tag": "EMAIL", "value": "m@mklein.co.at" }, { "context": "l sensor on the specified sensor port.\n * @author Markus Klein\n * @since 2.0.0\n * @version 2.0.0\n */\n public ", "end": 1074, "score": 0.9998928904533386, "start": 1062, "tag": "NAME", "value": "Markus Klein" } ]
null
[]
/* * This file is part of LinkJVM. * * Java Framework for the KIPR Link * Copyright (C) 2013 <NAME><<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package linkjvm.high.sensors.digital; import linkjvm.high.sensors.InvalidPortException; import linkjvm.low.Digital; import linkjvm.low.factory.JNIController; /** * An instance of this class is used to control one digital sensor on the specified sensor port. * @author <NAME> * @since 2.0.0 * @version 2.0.0 */ public class DigitalSensor implements IDigitalSensor{ private volatile Digital jniSensor; private int port; /** * Creates a new digital sensor on the specified port. * The invocation {@code DigitalSensor sensor = new DigitalSensor(0)} is equivalent to: * {@code DigitalSensor sensor = new DigitalSensor(); * sensor.setPort(0);} * * @param port the sensor's port * @throws InvalidPortException */ public DigitalSensor(int port) throws InvalidPortException{ if(port < 8 || port > 15){ throw new InvalidPortException(); } this.port = port; jniSensor = JNIController.getInstance().getDigitalFactory().getInstance(port); } /** * Returns the sensor port. * @return sensor port */ public int getPort(){ return port; } /** * Sets the sensor's port. * @param port sensor's port */ public void setPort(int port){ jniSensor = JNIController.getInstance().getDigitalFactory().getInstance(port); this.port = port; } /** * Returns the current sensor value. * @return sensor value */ @Override public boolean getValue(){ return !jniSensor.value(); } }
2,270
0.688073
0.681083
81
27.246914
25.869822
97
false
false
0
0
0
0
0
0
0.876543
false
false
15
c6717c79c0d6f30dfada0c617cad6ec509176581
20,779,051,800,868
6e9de9ac18bfc45b8010d35bc64c773c62e05608
/bpel.editors/src/org/netbeans/modules/bpel/properties/PropertyNodeFactory.java
f93649cc0ad4e0f7d2d015c21189fef0a76a88dc
[]
no_license
SRabbelier/Netbeans
https://github.com/SRabbelier/Netbeans
b6b1039d48b7898d31f3c7c572a4cadad73b6265
873d80ea8fa49fbf4bb5ecf76d275dcfa3cea6df
HEAD
2016-09-03T07:02:28.657000
2009-07-31T19:04:49
2009-07-31T19:04:49
267,579
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.modules.bpel.properties; import org.netbeans.modules.bpel.editors.api.nodes.NodeType; import org.netbeans.modules.bpel.nodes.BooleanExprNode; import org.netbeans.modules.bpel.nodes.CompletionConditionNode; import org.netbeans.modules.bpel.nodes.CopyNode; import org.netbeans.modules.bpel.nodes.CorrelationNode; import org.netbeans.modules.bpel.nodes.CorrelationPNode; import org.netbeans.modules.bpel.nodes.CorrelationPropertyNode; import org.netbeans.modules.bpel.nodes.CorrelationSetContainerNode; import org.netbeans.modules.bpel.nodes.CorrelationSetNode; import org.netbeans.modules.bpel.nodes.DefaultBpelEntityNode; import org.netbeans.modules.bpel.nodes.EmbeddedSchemaNode; import org.netbeans.modules.bpel.nodes.FromNode; import org.netbeans.modules.bpel.nodes.FromPartNode; import org.netbeans.modules.bpel.nodes.GlobalElementNode; import org.netbeans.modules.bpel.nodes.MessageExchangeContainerNode; import org.netbeans.modules.bpel.nodes.MessageExchangeNode; import org.netbeans.modules.bpel.nodes.MessagePartNode; import org.netbeans.modules.bpel.nodes.MessageTypeNode; import org.netbeans.modules.bpel.nodes.PartnerLinkTypeNode; import org.netbeans.modules.bpel.nodes.PartnerRoleNode; import org.netbeans.modules.bpel.nodes.PropertyAliasNode; import org.netbeans.modules.bpel.nodes.QueryNode; import org.netbeans.modules.bpel.nodes.SchemaFileNode; import org.netbeans.modules.bpel.nodes.ToNode; import org.netbeans.modules.bpel.nodes.ToPartNode; import org.netbeans.modules.bpel.nodes.VariableContainerNode; import org.netbeans.modules.bpel.nodes.VariableNode; import org.netbeans.modules.bpel.nodes.WsdlFileNode; import org.netbeans.modules.bpel.nodes.AssignNode; import org.netbeans.modules.bpel.nodes.BpelProcessNode; import org.netbeans.modules.bpel.nodes.CatchAllNode; import org.netbeans.modules.bpel.nodes.CatchNode; import org.netbeans.modules.bpel.nodes.CompensateNode; import org.netbeans.modules.bpel.nodes.CompensateScopeNode; import org.netbeans.modules.bpel.nodes.CompensationHandlerNode; import org.netbeans.modules.bpel.nodes.ElseIfNode; import org.netbeans.modules.bpel.nodes.ElseNode; import org.netbeans.modules.bpel.nodes.EmptyNode; import org.netbeans.modules.bpel.nodes.EventHandlersNode; import org.netbeans.modules.bpel.nodes.FaultHandlersNode; import org.netbeans.modules.bpel.nodes.FlowNode; import org.netbeans.modules.bpel.nodes.ForEachNode; import org.netbeans.modules.bpel.nodes.InvokeNode; import org.netbeans.modules.bpel.nodes.OnAlarmNode; import org.netbeans.modules.bpel.nodes.OnMessageNode; import org.netbeans.modules.bpel.nodes.PartnerLinkNode; import org.netbeans.modules.bpel.nodes.PickNode; import org.netbeans.modules.bpel.nodes.ReceiveNode; import org.netbeans.modules.bpel.nodes.RepeatUntilNode; import org.netbeans.modules.bpel.nodes.ReplyNode; import org.netbeans.modules.bpel.nodes.ScopeNode; import org.netbeans.modules.bpel.nodes.SequenceNode; import org.netbeans.modules.bpel.nodes.ExitNode; import org.netbeans.modules.bpel.nodes.FaultNode; import org.netbeans.modules.bpel.nodes.GlobalComplexTypeNode; import org.netbeans.modules.bpel.nodes.GlobalSimpleTypeNode; import org.netbeans.modules.bpel.nodes.IfNode; import org.netbeans.modules.bpel.nodes.ImportContainerNode; import org.netbeans.modules.bpel.nodes.ImportNode; import org.netbeans.modules.bpel.nodes.ImportSchemaNode; import org.netbeans.modules.bpel.nodes.ImportWsdlNode; import org.netbeans.modules.bpel.nodes.OnAlarmEventNode; import org.netbeans.modules.bpel.nodes.OnEventNode; import org.netbeans.modules.bpel.nodes.ReThrowNode; import org.netbeans.modules.bpel.nodes.TerminationHandlerNode; import org.netbeans.modules.bpel.nodes.ThenNode; import org.netbeans.modules.bpel.nodes.ThrowNode; import org.netbeans.modules.bpel.nodes.WaitNode; import org.netbeans.modules.bpel.nodes.WhileNode; import org.netbeans.modules.soa.ui.nodes.ReflectionNodeFactory; /** * Constructs BPEL Nodes * * @author nk160297 */ public class PropertyNodeFactory extends ReflectionNodeFactory<NodeType> { private static PropertyNodeFactory instance = new PropertyNodeFactory(); public static PropertyNodeFactory getInstance() { return instance; } private PropertyNodeFactory() { super(80); // key2Class.put(NodeType.PROCESS, BpelProcessNode.class); // key2Class.put(NodeType.SCOPE, ScopeNode.class); key2Class.put(NodeType.SEQUENCE, SequenceNode.class); key2Class.put(NodeType.FLOW, FlowNode.class); key2Class.put(NodeType.WHILE, WhileNode.class); key2Class.put(NodeType.IF, IfNode.class); key2Class.put(NodeType.ELSE_IF, ElseIfNode.class); key2Class.put(NodeType.ELSE, ElseNode.class); key2Class.put(NodeType.THEN, ThenNode.class); // key2Class.put(NodeType.EMPTY, EmptyNode.class); key2Class.put(NodeType.INVOKE, InvokeNode.class); key2Class.put(NodeType.RECEIVE, ReceiveNode.class); key2Class.put(NodeType.REPLY, ReplyNode.class); key2Class.put(NodeType.PICK, PickNode.class); key2Class.put(NodeType.ASSIGN, AssignNode.class); key2Class.put(NodeType.WAIT, WaitNode.class); key2Class.put(NodeType.THROW, ThrowNode.class); key2Class.put(NodeType.RETHROW, ReThrowNode.class); key2Class.put(NodeType.EXIT, ExitNode.class); key2Class.put(NodeType.COMPENSATE, CompensateNode.class); key2Class.put(NodeType.COMPENSATE_SCOPE, CompensateScopeNode.class); key2Class.put(NodeType.CATCH, CatchNode.class); key2Class.put(NodeType.CATCH_ALL, CatchAllNode.class); key2Class.put(NodeType.TERMINATION_HANDLER, TerminationHandlerNode.class); key2Class.put(NodeType.COMPENSATION_HANDLER, CompensationHandlerNode.class); key2Class.put(NodeType.EVENT_HANDLERS, EventHandlersNode.class); key2Class.put(NodeType.FAULT_HANDLERS, FaultHandlersNode.class); // key2Class.put(NodeType.PARTNER_LINK, PartnerLinkNode.class); key2Class.put(NodeType.PARTNER_LINK_TYPE, PartnerLinkTypeNode.class); key2Class.put(NodeType.PARTNER_ROLE, PartnerRoleNode.class); key2Class.put(NodeType.QUERY, QueryNode.class); // key2Class.put(NodeType.ALARM_HANDLER, OnAlarmNode.class); key2Class.put(NodeType.ALARM_EVENT_HANDLER, OnAlarmEventNode.class); key2Class.put(NodeType.MESSAGE_HANDLER, OnMessageNode.class); key2Class.put(NodeType.ON_EVENT, OnEventNode.class); // key2Class.put(NodeType.MESSAGE_TYPE, MessageTypeNode.class); key2Class.put(NodeType.WSDL_FILE, WsdlFileNode.class); key2Class.put(NodeType.SCHEMA_FILE, SchemaFileNode.class); // key2Class.put(NodeType.VARIABLE_CONTAINER, VariableContainerNode.class); key2Class.put(NodeType.VARIABLE, VariableNode.class); key2Class.put(NodeType.CORRELATION, CorrelationNode.class); key2Class.put(NodeType.CORRELATION_P, CorrelationPNode.class); key2Class.put(NodeType.CORRELATION_SET_CONTAINER, CorrelationSetContainerNode.class); key2Class.put(NodeType.CORRELATION_SET, CorrelationSetNode.class); key2Class.put(NodeType.CORRELATION_PROPERTY, CorrelationPropertyNode.class); key2Class.put(NodeType.CORRELATION_PROPERTY_ALIAS, PropertyAliasNode.class); key2Class.put(NodeType.MESSAGE_PART, MessagePartNode.class); key2Class.put(NodeType.FROM_PART, FromPartNode.class); key2Class.put(NodeType.TO_PART, ToPartNode.class); key2Class.put(NodeType.FROM, FromNode.class); key2Class.put(NodeType.TO, ToNode.class); // key2Class.put(NodeType.COPY, CopyNode.class); key2Class.put(NodeType.IMPORT, ImportNode.class); key2Class.put(NodeType.IMPORT_SCHEMA, ImportSchemaNode.class); key2Class.put(NodeType.IMPORT_WSDL, ImportWsdlNode.class); key2Class.put(NodeType.IMPORT_CONTAINER, ImportContainerNode.class); // key2Class.put(NodeType.MESSAGE_EXCHANGE, MessageExchangeNode.class); key2Class.put(NodeType.MESSAGE_EXCHANGE_CONTAINER , MessageExchangeContainerNode.class); key2Class.put(NodeType.REPEAT_UNTIL, RepeatUntilNode.class); key2Class.put(NodeType.FOR_EACH, ForEachNode.class); // key2Class.put(NodeType.FAULT, FaultNode.class); // key2Class.put(NodeType.EMBEDDED_SCHEMA, EmbeddedSchemaNode.class); // key2Class.put(NodeType.DEFAULT_BPEL_ENTITY_NODE , DefaultBpelEntityNode.class); key2Class.put(NodeType.BOOLEAN_EXPR, BooleanExprNode.class); key2Class.put(NodeType.COMPLETION_CONDITION , CompletionConditionNode.class); // key2Class.put(NodeType.GLOBAL_COMPLEX_TYPE, GlobalComplexTypeNode.class); key2Class.put(NodeType.GLOBAL_SIMPLE_TYPE, GlobalSimpleTypeNode.class); key2Class.put(NodeType.GLOBAL_ELEMENT, GlobalElementNode.class); // // key2Class.put(NodeType., Node.class); // } }
UTF-8
Java
10,037
java
PropertyNodeFactory.java
Java
[ { "context": "tory;\n\n/**\n * Constructs BPEL Nodes \n *\n * @author nk160297\n */\npublic class PropertyNodeFactory extends Refl", "end": 4831, "score": 0.9996172189712524, "start": 4823, "tag": "USERNAME", "value": "nk160297" } ]
null
[]
/* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.modules.bpel.properties; import org.netbeans.modules.bpel.editors.api.nodes.NodeType; import org.netbeans.modules.bpel.nodes.BooleanExprNode; import org.netbeans.modules.bpel.nodes.CompletionConditionNode; import org.netbeans.modules.bpel.nodes.CopyNode; import org.netbeans.modules.bpel.nodes.CorrelationNode; import org.netbeans.modules.bpel.nodes.CorrelationPNode; import org.netbeans.modules.bpel.nodes.CorrelationPropertyNode; import org.netbeans.modules.bpel.nodes.CorrelationSetContainerNode; import org.netbeans.modules.bpel.nodes.CorrelationSetNode; import org.netbeans.modules.bpel.nodes.DefaultBpelEntityNode; import org.netbeans.modules.bpel.nodes.EmbeddedSchemaNode; import org.netbeans.modules.bpel.nodes.FromNode; import org.netbeans.modules.bpel.nodes.FromPartNode; import org.netbeans.modules.bpel.nodes.GlobalElementNode; import org.netbeans.modules.bpel.nodes.MessageExchangeContainerNode; import org.netbeans.modules.bpel.nodes.MessageExchangeNode; import org.netbeans.modules.bpel.nodes.MessagePartNode; import org.netbeans.modules.bpel.nodes.MessageTypeNode; import org.netbeans.modules.bpel.nodes.PartnerLinkTypeNode; import org.netbeans.modules.bpel.nodes.PartnerRoleNode; import org.netbeans.modules.bpel.nodes.PropertyAliasNode; import org.netbeans.modules.bpel.nodes.QueryNode; import org.netbeans.modules.bpel.nodes.SchemaFileNode; import org.netbeans.modules.bpel.nodes.ToNode; import org.netbeans.modules.bpel.nodes.ToPartNode; import org.netbeans.modules.bpel.nodes.VariableContainerNode; import org.netbeans.modules.bpel.nodes.VariableNode; import org.netbeans.modules.bpel.nodes.WsdlFileNode; import org.netbeans.modules.bpel.nodes.AssignNode; import org.netbeans.modules.bpel.nodes.BpelProcessNode; import org.netbeans.modules.bpel.nodes.CatchAllNode; import org.netbeans.modules.bpel.nodes.CatchNode; import org.netbeans.modules.bpel.nodes.CompensateNode; import org.netbeans.modules.bpel.nodes.CompensateScopeNode; import org.netbeans.modules.bpel.nodes.CompensationHandlerNode; import org.netbeans.modules.bpel.nodes.ElseIfNode; import org.netbeans.modules.bpel.nodes.ElseNode; import org.netbeans.modules.bpel.nodes.EmptyNode; import org.netbeans.modules.bpel.nodes.EventHandlersNode; import org.netbeans.modules.bpel.nodes.FaultHandlersNode; import org.netbeans.modules.bpel.nodes.FlowNode; import org.netbeans.modules.bpel.nodes.ForEachNode; import org.netbeans.modules.bpel.nodes.InvokeNode; import org.netbeans.modules.bpel.nodes.OnAlarmNode; import org.netbeans.modules.bpel.nodes.OnMessageNode; import org.netbeans.modules.bpel.nodes.PartnerLinkNode; import org.netbeans.modules.bpel.nodes.PickNode; import org.netbeans.modules.bpel.nodes.ReceiveNode; import org.netbeans.modules.bpel.nodes.RepeatUntilNode; import org.netbeans.modules.bpel.nodes.ReplyNode; import org.netbeans.modules.bpel.nodes.ScopeNode; import org.netbeans.modules.bpel.nodes.SequenceNode; import org.netbeans.modules.bpel.nodes.ExitNode; import org.netbeans.modules.bpel.nodes.FaultNode; import org.netbeans.modules.bpel.nodes.GlobalComplexTypeNode; import org.netbeans.modules.bpel.nodes.GlobalSimpleTypeNode; import org.netbeans.modules.bpel.nodes.IfNode; import org.netbeans.modules.bpel.nodes.ImportContainerNode; import org.netbeans.modules.bpel.nodes.ImportNode; import org.netbeans.modules.bpel.nodes.ImportSchemaNode; import org.netbeans.modules.bpel.nodes.ImportWsdlNode; import org.netbeans.modules.bpel.nodes.OnAlarmEventNode; import org.netbeans.modules.bpel.nodes.OnEventNode; import org.netbeans.modules.bpel.nodes.ReThrowNode; import org.netbeans.modules.bpel.nodes.TerminationHandlerNode; import org.netbeans.modules.bpel.nodes.ThenNode; import org.netbeans.modules.bpel.nodes.ThrowNode; import org.netbeans.modules.bpel.nodes.WaitNode; import org.netbeans.modules.bpel.nodes.WhileNode; import org.netbeans.modules.soa.ui.nodes.ReflectionNodeFactory; /** * Constructs BPEL Nodes * * @author nk160297 */ public class PropertyNodeFactory extends ReflectionNodeFactory<NodeType> { private static PropertyNodeFactory instance = new PropertyNodeFactory(); public static PropertyNodeFactory getInstance() { return instance; } private PropertyNodeFactory() { super(80); // key2Class.put(NodeType.PROCESS, BpelProcessNode.class); // key2Class.put(NodeType.SCOPE, ScopeNode.class); key2Class.put(NodeType.SEQUENCE, SequenceNode.class); key2Class.put(NodeType.FLOW, FlowNode.class); key2Class.put(NodeType.WHILE, WhileNode.class); key2Class.put(NodeType.IF, IfNode.class); key2Class.put(NodeType.ELSE_IF, ElseIfNode.class); key2Class.put(NodeType.ELSE, ElseNode.class); key2Class.put(NodeType.THEN, ThenNode.class); // key2Class.put(NodeType.EMPTY, EmptyNode.class); key2Class.put(NodeType.INVOKE, InvokeNode.class); key2Class.put(NodeType.RECEIVE, ReceiveNode.class); key2Class.put(NodeType.REPLY, ReplyNode.class); key2Class.put(NodeType.PICK, PickNode.class); key2Class.put(NodeType.ASSIGN, AssignNode.class); key2Class.put(NodeType.WAIT, WaitNode.class); key2Class.put(NodeType.THROW, ThrowNode.class); key2Class.put(NodeType.RETHROW, ReThrowNode.class); key2Class.put(NodeType.EXIT, ExitNode.class); key2Class.put(NodeType.COMPENSATE, CompensateNode.class); key2Class.put(NodeType.COMPENSATE_SCOPE, CompensateScopeNode.class); key2Class.put(NodeType.CATCH, CatchNode.class); key2Class.put(NodeType.CATCH_ALL, CatchAllNode.class); key2Class.put(NodeType.TERMINATION_HANDLER, TerminationHandlerNode.class); key2Class.put(NodeType.COMPENSATION_HANDLER, CompensationHandlerNode.class); key2Class.put(NodeType.EVENT_HANDLERS, EventHandlersNode.class); key2Class.put(NodeType.FAULT_HANDLERS, FaultHandlersNode.class); // key2Class.put(NodeType.PARTNER_LINK, PartnerLinkNode.class); key2Class.put(NodeType.PARTNER_LINK_TYPE, PartnerLinkTypeNode.class); key2Class.put(NodeType.PARTNER_ROLE, PartnerRoleNode.class); key2Class.put(NodeType.QUERY, QueryNode.class); // key2Class.put(NodeType.ALARM_HANDLER, OnAlarmNode.class); key2Class.put(NodeType.ALARM_EVENT_HANDLER, OnAlarmEventNode.class); key2Class.put(NodeType.MESSAGE_HANDLER, OnMessageNode.class); key2Class.put(NodeType.ON_EVENT, OnEventNode.class); // key2Class.put(NodeType.MESSAGE_TYPE, MessageTypeNode.class); key2Class.put(NodeType.WSDL_FILE, WsdlFileNode.class); key2Class.put(NodeType.SCHEMA_FILE, SchemaFileNode.class); // key2Class.put(NodeType.VARIABLE_CONTAINER, VariableContainerNode.class); key2Class.put(NodeType.VARIABLE, VariableNode.class); key2Class.put(NodeType.CORRELATION, CorrelationNode.class); key2Class.put(NodeType.CORRELATION_P, CorrelationPNode.class); key2Class.put(NodeType.CORRELATION_SET_CONTAINER, CorrelationSetContainerNode.class); key2Class.put(NodeType.CORRELATION_SET, CorrelationSetNode.class); key2Class.put(NodeType.CORRELATION_PROPERTY, CorrelationPropertyNode.class); key2Class.put(NodeType.CORRELATION_PROPERTY_ALIAS, PropertyAliasNode.class); key2Class.put(NodeType.MESSAGE_PART, MessagePartNode.class); key2Class.put(NodeType.FROM_PART, FromPartNode.class); key2Class.put(NodeType.TO_PART, ToPartNode.class); key2Class.put(NodeType.FROM, FromNode.class); key2Class.put(NodeType.TO, ToNode.class); // key2Class.put(NodeType.COPY, CopyNode.class); key2Class.put(NodeType.IMPORT, ImportNode.class); key2Class.put(NodeType.IMPORT_SCHEMA, ImportSchemaNode.class); key2Class.put(NodeType.IMPORT_WSDL, ImportWsdlNode.class); key2Class.put(NodeType.IMPORT_CONTAINER, ImportContainerNode.class); // key2Class.put(NodeType.MESSAGE_EXCHANGE, MessageExchangeNode.class); key2Class.put(NodeType.MESSAGE_EXCHANGE_CONTAINER , MessageExchangeContainerNode.class); key2Class.put(NodeType.REPEAT_UNTIL, RepeatUntilNode.class); key2Class.put(NodeType.FOR_EACH, ForEachNode.class); // key2Class.put(NodeType.FAULT, FaultNode.class); // key2Class.put(NodeType.EMBEDDED_SCHEMA, EmbeddedSchemaNode.class); // key2Class.put(NodeType.DEFAULT_BPEL_ENTITY_NODE , DefaultBpelEntityNode.class); key2Class.put(NodeType.BOOLEAN_EXPR, BooleanExprNode.class); key2Class.put(NodeType.COMPLETION_CONDITION , CompletionConditionNode.class); // key2Class.put(NodeType.GLOBAL_COMPLEX_TYPE, GlobalComplexTypeNode.class); key2Class.put(NodeType.GLOBAL_SIMPLE_TYPE, GlobalSimpleTypeNode.class); key2Class.put(NodeType.GLOBAL_ELEMENT, GlobalElementNode.class); // // key2Class.put(NodeType., Node.class); // } }
10,037
0.758195
0.749726
200
49.185001
21.687572
93
false
false
0
0
0
0
0
0
1.085
false
false
15
7047b36ab189b39015af57c4785d6e625e91f472
20,151,986,621,483
5b4aa50aedc755a58b8a14cbcf1da95af03c144a
/src/main/java/Run.java
7c69bf64095a4b271d93d1fbd0c2a85ac6b9604b
[ "MIT" ]
permissive
xtreeio/spn
https://github.com/xtreeio/spn
7566c25718247aab5ef4d07d93f91a37eac28216
e906a7ae0f89ea4bf7be06a83ec58dd5eb971881
refs/heads/master
2016-09-13T20:50:43.570000
2016-05-16T08:27:33
2016-05-16T08:27:33
56,118,256
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Run { }
UTF-8
Java
25
java
Run.java
Java
[]
null
[]
public class Run { }
25
0.56
0.56
4
4.75
7.660777
18
false
false
0
0
0
0
0
0
0
false
false
15
92a785b1e8d128b4f07c1349547ddb3c1782d3fc
37,271,726,216,173
1bdd30cc501cd2eb5f7b21d9681397e10531269a
/src/main/java/tvestergaard/fog/data/orders/OrderUpdater.java
556f7b13d001319598d3f463513e82f8bb8e7937
[]
no_license
Thomas-Rosenkrans-Vestergaard/fog
https://github.com/Thomas-Rosenkrans-Vestergaard/fog
259d6b3f32dea5075fdc2f3c0e2c23ed3703bb46
05239f4f094b30daf39a72cbaf2bb990a1d8bc98
refs/heads/master
2020-03-12T01:58:30.521000
2018-06-02T08:39:33
2018-06-02T08:39:33
130,370,988
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tvestergaard.fog.data.orders; public interface OrderUpdater extends OrderBlueprint { /** * Returns a new order updater from the provided information. * * @param id The id of the order to update. * @param customer The customer of the order to specify in the updater. * @param width The width of the order to specify in the updater. * @param length The length of the order to specify in the updater. * @param height The height of the order to specify in the updater. * @param roofing The roofing of the order to specify in the updater. * @param slope The slope of the order to specify in the updater. * @param active The active status of the order in the updater. * @param shedUpdater The shed to include in the order. {@code null} when the order has no shed. * @param comment The comment by the customer about the order. * @return The newly created order updater. */ static OrderUpdater from(int id, int customer, int width, int length, int height, int roofing, int slope, boolean active, ShedUpdater shedUpdater, String comment) { return new OrderRecord(id, customer, null, width, length, height, roofing, null, slope, shedUpdater, shedUpdater, null, comment, active, -1, -1, null); } /** * Returns the unique identifier of the order. * * @return The unique identifier of the order. */ int getId(); /** * Returns the shed updater. * * @return The shed updater. */ ShedUpdater getShedUpdater(); /** * Returns whether or not the order is considered active. * * @return {@code true} if the order is considered active. */ boolean isActive(); }
UTF-8
Java
2,081
java
OrderUpdater.java
Java
[]
null
[]
package tvestergaard.fog.data.orders; public interface OrderUpdater extends OrderBlueprint { /** * Returns a new order updater from the provided information. * * @param id The id of the order to update. * @param customer The customer of the order to specify in the updater. * @param width The width of the order to specify in the updater. * @param length The length of the order to specify in the updater. * @param height The height of the order to specify in the updater. * @param roofing The roofing of the order to specify in the updater. * @param slope The slope of the order to specify in the updater. * @param active The active status of the order in the updater. * @param shedUpdater The shed to include in the order. {@code null} when the order has no shed. * @param comment The comment by the customer about the order. * @return The newly created order updater. */ static OrderUpdater from(int id, int customer, int width, int length, int height, int roofing, int slope, boolean active, ShedUpdater shedUpdater, String comment) { return new OrderRecord(id, customer, null, width, length, height, roofing, null, slope, shedUpdater, shedUpdater, null, comment, active, -1, -1, null); } /** * Returns the unique identifier of the order. * * @return The unique identifier of the order. */ int getId(); /** * Returns the shed updater. * * @return The shed updater. */ ShedUpdater getShedUpdater(); /** * Returns whether or not the order is considered active. * * @return {@code true} if the order is considered active. */ boolean isActive(); }
2,081
0.555502
0.554541
57
35.508774
28.905243
101
false
false
0
0
0
0
0
0
0.526316
false
false
15
1cfae20efb141dea1e3927cc664ea3e31acc650c
37,383,395,347,554
0dccef976f19741f67479f32f15d76c1e90e7f94
/aey.java
b5b4cb0cd3d29adb49babb4ff76221abd30d565f
[]
no_license
Tominous/LabyMod-1.9
https://github.com/Tominous/LabyMod-1.9
a960959d67817b1300272d67bd942cd383dfd668
33e441754a0030d619358fc20ca545df98d55f71
refs/heads/master
2020-05-24T21:35:00.931000
2017-02-06T21:04:08
2017-02-06T21:04:08
187,478,724
1
0
null
true
2019-05-19T13:14:46
2019-05-19T13:14:46
2019-05-19T13:12:37
2017-02-06T21:06:23
6,855
0
0
0
null
false
false
public class aey extends acc { private String[] b; public aey(ajt ☃, boolean ☃) { super(☃); if (☃) { e(0); a(true); } } public int a(int ☃) { return ☃; } public aey a(String[] ☃) { this.b = ☃; return this; } public String f_(adq ☃) { if (this.b == null) { return super.f_(☃); } int ☃ = ☃.i(); if ((☃ >= 0) && (☃ < this.b.length)) { return super.f_(☃) + "." + this.b[☃]; } return super.f_(☃); } }
UTF-8
Java
546
java
aey.java
Java
[]
null
[]
public class aey extends acc { private String[] b; public aey(ajt ☃, boolean ☃) { super(☃); if (☃) { e(0); a(true); } } public int a(int ☃) { return ☃; } public aey a(String[] ☃) { this.b = ☃; return this; } public String f_(adq ☃) { if (this.b == null) { return super.f_(☃); } int ☃ = ☃.i(); if ((☃ >= 0) && (☃ < this.b.length)) { return super.f_(☃) + "." + this.b[☃]; } return super.f_(☃); } }
546
0.404297
0.400391
38
12.473684
11.165588
43
false
false
0
0
0
0
0
0
0.315789
false
false
15
f2c919c7eb992d105dceecbc69e908f01275a1e0
36,953,898,637,443
370229e5bb54fdc4b4b26073e28322d1d8e88bff
/project-custom-message-core/src/main/java/com/acme/example/custom/message/core/config/environment/ProductionConfig.java
c04954b6503da81af0264ed6a9dcacd650c03cda
[ "MIT" ]
permissive
vjmadrid/workspace-spring-lab
https://github.com/vjmadrid/workspace-spring-lab
c02faf7dfa98e14da190056f6880a0b07863bc50
c9730c5e19a0579945a92ddf0115d51cd2ffd1b8
refs/heads/master
2022-12-23T00:39:56.646000
2021-02-14T10:56:41
2021-02-14T10:56:41
173,130,177
0
0
MIT
false
2022-12-10T01:54:34
2019-02-28T14:48:27
2021-02-14T10:56:55
2022-12-10T01:54:31
89
0
0
1
Java
false
false
package com.acme.example.custom.message.core.config.environment; import java.util.Properties; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.core.env.Environment; import com.acme.architecture.common.constant.SpringConfigConstant; @Configuration @PropertySources({ @PropertySource("classpath:persistence/pro-persistence.properties") }) @Profile(SpringConfigConstant.SPRING_PROFILE_PRODUCTION) public class ProductionConfig { private static final Logger LOG = LoggerFactory.getLogger(ProductionConfig.class); @Autowired private Environment env; @Bean(name="dataSource") public DataSource dataSourceProduction() throws NamingException { LOG.debug("[CONFIGURATION] Configuring Datasource in PRO ..."); return null; // return (DataSource) new JndiTemplate().lookup(env.getProperty(ConfigConstant.PROP_JNDI)); } @Bean(name="hibernateProperties") public Properties hibernateProperties() { LOG.debug("[CONFIGURATION] Configuring hibernateProperties in PRO ..."); final Properties hibernateProperties = new Properties(); return hibernateProperties; } }
UTF-8
Java
1,552
java
ProductionConfig.java
Java
[]
null
[]
package com.acme.example.custom.message.core.config.environment; import java.util.Properties; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.core.env.Environment; import com.acme.architecture.common.constant.SpringConfigConstant; @Configuration @PropertySources({ @PropertySource("classpath:persistence/pro-persistence.properties") }) @Profile(SpringConfigConstant.SPRING_PROFILE_PRODUCTION) public class ProductionConfig { private static final Logger LOG = LoggerFactory.getLogger(ProductionConfig.class); @Autowired private Environment env; @Bean(name="dataSource") public DataSource dataSourceProduction() throws NamingException { LOG.debug("[CONFIGURATION] Configuring Datasource in PRO ..."); return null; // return (DataSource) new JndiTemplate().lookup(env.getProperty(ConfigConstant.PROP_JNDI)); } @Bean(name="hibernateProperties") public Properties hibernateProperties() { LOG.debug("[CONFIGURATION] Configuring hibernateProperties in PRO ..."); final Properties hibernateProperties = new Properties(); return hibernateProperties; } }
1,552
0.80799
0.806701
46
32.760868
27.817093
99
false
false
0
0
0
0
0
0
0.934783
false
false
15
ae11608efb154d8cc2c23bb65b6f2e73efa9c4da
37,280,316,140,463
f0a24e9644dd2acbcc28e52466b289b849ff62c9
/TestApp/app/src/main/java/com/receiptbank/android/testapp/rest/model/Weather.java
9c9299f5b7cd64449f096a3dfaf315614123a3ff
[]
no_license
stefotoo/onetap-android-test-stefan
https://github.com/stefotoo/onetap-android-test-stefan
98f3726c1fddef934658fbed04e76a9d5156881d
32114db2b97b8857d6d0924598143981edf5e730
refs/heads/master
2020-04-09T06:37:09.035000
2016-06-21T19:34:09
2016-06-21T19:34:09
61,419,441
0
0
null
true
2016-06-18T06:01:41
2016-06-18T06:01:41
2016-06-15T08:06:29
2016-06-15T08:10:28
0
0
0
0
null
null
null
package com.receiptbank.android.testapp.rest.model; import com.google.gson.annotations.SerializedName; public class Weather { // variables @SerializedName("main") private String title; @SerializedName("description") private String description; // constructor public Weather() { // default } // methods public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
UTF-8
Java
660
java
Weather.java
Java
[]
null
[]
package com.receiptbank.android.testapp.rest.model; import com.google.gson.annotations.SerializedName; public class Weather { // variables @SerializedName("main") private String title; @SerializedName("description") private String description; // constructor public Weather() { // default } // methods public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
660
0.639394
0.639394
34
18.411764
16.413979
52
false
false
0
0
0
0
0
0
0.235294
false
false
15
01a42ebde0cd7474039d6be79532d790f82d6286
34,007,551,088,770
bef4b365b52c643832d08febfd9329d7856b5877
/src/main/java/net/karottenfabrik/appleTrees/blocks/AppleTreeLeaf.java
b7cdb69ea65efd81bf148712e7f1de757201e2e3
[ "CC0-1.0" ]
permissive
KarottenMxn/AppleTrees
https://github.com/KarottenMxn/AppleTrees
21c0524c81a30fe9c36bcb3764b6224752e67fa6
8959ae417eec68bd7d0847d7efe5f2e65fdeedb5
refs/heads/master
2023-07-17T13:17:46.804000
2021-08-22T22:13:43
2021-08-22T22:13:43
398,911,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.karottenfabrik.appleTrees.blocks; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.karottenfabrik.appleTrees.AppleTrees; import net.minecraft.block.AbstractBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.PlantBlock; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.LightningEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.IntProperty; import net.minecraft.state.property.Properties; import net.minecraft.text.LiteralText; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.BlockView; import net.minecraft.world.World; import java.util.Random; public class AppleTreeLeaf extends Block { public static final int MAX_AGE = 3; public static IntProperty AGE; // public static final BooleanProperty HASAPPLES = BooleanProperty.of("hasapples"); // @Override // protected void appendProperties(StateManager.Builder<Block, BlockState> stateManager) { // stateManager.add(HASAPPLES); // } public AppleTreeLeaf(AbstractBlock.Settings settings) { super(settings); this.setDefaultState((BlockState)((BlockState)this.stateManager.getDefaultState()).with(AGE, 0)); } public ItemStack getPickStack(BlockView world, BlockPos pos, BlockState state) { return new ItemStack(AppleTrees.WILD_APPLE); } public boolean hasRandomTicks(BlockState state) { return (Integer)state.get(AGE) < 3; } public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random random) { int i = (Integer)state.get(AGE); if (i < 3 && random.nextInt(5) == 0 && world.getBaseLightLevel(pos.up(), 0) >= 9) { world.setBlockState(pos, (BlockState)state.with(AGE, i + 1), Block.NOTIFY_LISTENERS); } } @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { int i = (Integer)state.get(AGE); boolean bl = i == 3; if (i > 1) { int j = 1 + world.random.nextInt(2); dropStack(world, pos, new ItemStack(AppleTrees.WILD_APPLE, j + (bl ? 1 : 0))); world.playSound((PlayerEntity)null, pos, SoundEvents.BLOCK_SWEET_BERRY_BUSH_PICK_BERRIES, SoundCategory.BLOCKS, 1.0F, 0.8F + world.random.nextFloat() * 0.4F); world.setBlockState(pos, (BlockState)state.with(AGE, 1), Block.NOTIFY_LISTENERS); return ActionResult.success(world.isClient); } else { return super.onUse(state, world, pos, player, hand, hit); } //player.playSound(SoundEvents.BLOCK_SWEET_BERRY_BUSH_PICK_BERRIES, 1, 1); //if (world.getBlockState(pos).get(HASAPPLES)) { // ItemStack stack = new ItemStack(AppleTrees.WILD_APPLE, 2); // ItemEntity itemEntity = new ItemEntity(player.world, pos.getX(), pos.getY(), pos.getZ(), stack); // player.world.spawnEntity(itemEntity); // // } // world.setBlockState(pos, state.with(HASAPPLES, false)); // return ActionResult.SUCCESS; } protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(AGE); } public boolean canGrow(World world, Random random, BlockPos pos, BlockState state) { return true; } public void grow(ServerWorld world, Random random, BlockPos pos, BlockState state) { int i = Math.min(3, (Integer)state.get(AGE) + 1); world.setBlockState(pos, (BlockState)state.with(AGE, i), Block.NOTIFY_LISTENERS); } static { AGE = Properties.AGE_3; } }
UTF-8
Java
4,270
java
AppleTreeLeaf.java
Java
[]
null
[]
package net.karottenfabrik.appleTrees.blocks; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.karottenfabrik.appleTrees.AppleTrees; import net.minecraft.block.AbstractBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.PlantBlock; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.LightningEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.IntProperty; import net.minecraft.state.property.Properties; import net.minecraft.text.LiteralText; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.BlockView; import net.minecraft.world.World; import java.util.Random; public class AppleTreeLeaf extends Block { public static final int MAX_AGE = 3; public static IntProperty AGE; // public static final BooleanProperty HASAPPLES = BooleanProperty.of("hasapples"); // @Override // protected void appendProperties(StateManager.Builder<Block, BlockState> stateManager) { // stateManager.add(HASAPPLES); // } public AppleTreeLeaf(AbstractBlock.Settings settings) { super(settings); this.setDefaultState((BlockState)((BlockState)this.stateManager.getDefaultState()).with(AGE, 0)); } public ItemStack getPickStack(BlockView world, BlockPos pos, BlockState state) { return new ItemStack(AppleTrees.WILD_APPLE); } public boolean hasRandomTicks(BlockState state) { return (Integer)state.get(AGE) < 3; } public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random random) { int i = (Integer)state.get(AGE); if (i < 3 && random.nextInt(5) == 0 && world.getBaseLightLevel(pos.up(), 0) >= 9) { world.setBlockState(pos, (BlockState)state.with(AGE, i + 1), Block.NOTIFY_LISTENERS); } } @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { int i = (Integer)state.get(AGE); boolean bl = i == 3; if (i > 1) { int j = 1 + world.random.nextInt(2); dropStack(world, pos, new ItemStack(AppleTrees.WILD_APPLE, j + (bl ? 1 : 0))); world.playSound((PlayerEntity)null, pos, SoundEvents.BLOCK_SWEET_BERRY_BUSH_PICK_BERRIES, SoundCategory.BLOCKS, 1.0F, 0.8F + world.random.nextFloat() * 0.4F); world.setBlockState(pos, (BlockState)state.with(AGE, 1), Block.NOTIFY_LISTENERS); return ActionResult.success(world.isClient); } else { return super.onUse(state, world, pos, player, hand, hit); } //player.playSound(SoundEvents.BLOCK_SWEET_BERRY_BUSH_PICK_BERRIES, 1, 1); //if (world.getBlockState(pos).get(HASAPPLES)) { // ItemStack stack = new ItemStack(AppleTrees.WILD_APPLE, 2); // ItemEntity itemEntity = new ItemEntity(player.world, pos.getX(), pos.getY(), pos.getZ(), stack); // player.world.spawnEntity(itemEntity); // // } // world.setBlockState(pos, state.with(HASAPPLES, false)); // return ActionResult.SUCCESS; } protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(AGE); } public boolean canGrow(World world, Random random, BlockPos pos, BlockState state) { return true; } public void grow(ServerWorld world, Random random, BlockPos pos, BlockState state) { int i = Math.min(3, (Integer)state.get(AGE) + 1); world.setBlockState(pos, (BlockState)state.with(AGE, i), Block.NOTIFY_LISTENERS); } static { AGE = Properties.AGE_3; } }
4,270
0.706792
0.7
109
38.174313
32.899025
170
false
false
0
0
0
0
0
0
1.036697
false
false
15
cf761be57dd7367ddfda8c5e08123052e6c5c1b0
25,537,875,581,071
95071a610f72c58a35829164ac69eabde5b604c1
/MultithreadingUsingExtendsThreadClass/src/MathematicalTableClass.java
457f452b3e6e62e8cbbde347840ac959624b3d24
[]
no_license
jayuchawla/Java-and-OOP-Training
https://github.com/jayuchawla/Java-and-OOP-Training
7c26faa9f114f569b3eb731bb2c7235dbe5372a2
2eaeeecbdc99720197ae6ed860665a5c250c7d6f
refs/heads/master
2022-12-21T14:56:12.684000
2020-09-30T12:01:45
2020-09-30T12:01:45
297,963,285
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class MathematicalTableClass { //synchronized helps resolving printTable since this is a shared resource public synchronized void printTable(int a) { for(int i = 0;i<10;i++) { System.out.println(a+"*"+(i+1)+"="+a*(i+1)); } } }
UTF-8
Java
261
java
MathematicalTableClass.java
Java
[]
null
[]
public class MathematicalTableClass { //synchronized helps resolving printTable since this is a shared resource public synchronized void printTable(int a) { for(int i = 0;i<10;i++) { System.out.println(a+"*"+(i+1)+"="+a*(i+1)); } } }
261
0.632184
0.613027
10
23.700001
24.912045
74
false
false
0
0
0
0
0
0
1.4
false
false
15
d90ab9fcb69675d5e10479229cc0002f27198a0d
9,199,820,012,699
f834d44e3a0328483cdd3c4e9e43178981214914
/src/main/java/com/etolmach/stream/Iterators.java
b86538aaff07e49d73c09bcd9df53aebedc6fdaf
[]
no_license
etolmach/Janity
https://github.com/etolmach/Janity
86cfa8e3c47055fa0fd018d93f2211d993bd0e55
92eb9ca23fcc05e3ce2fdde4d64457b08cb30268
refs/heads/master
2020-04-16T03:47:46.834000
2019-01-29T14:00:21
2019-01-29T14:00:21
165,245,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.etolmach.stream; import java.util.function.DoubleUnaryOperator; import java.util.function.IntUnaryOperator; import java.util.function.LongUnaryOperator; /** * @author Evgeniy Tolmach */ public class Iterators { public static IntUnaryOperator incrementingBy(int value) { return i -> i + value; } public static LongUnaryOperator incrementingBy(long value) { return i -> i + value; } public static DoubleUnaryOperator incrementingBy(double value) { return i -> i + value; } public static IntUnaryOperator decrementingBy(int value) { return i -> i - value; } public static LongUnaryOperator decrementingBy(long value) { return i -> i - value; } public static DoubleUnaryOperator decrementingBy(double value) { return i -> i - value; } }
UTF-8
Java
852
java
Iterators.java
Java
[ { "context": "a.util.function.LongUnaryOperator;\n\n/**\n * @author Evgeniy Tolmach\n */\npublic class Iterators {\n\n public static I", "end": 197, "score": 0.9998720288276672, "start": 182, "tag": "NAME", "value": "Evgeniy Tolmach" } ]
null
[]
package com.etolmach.stream; import java.util.function.DoubleUnaryOperator; import java.util.function.IntUnaryOperator; import java.util.function.LongUnaryOperator; /** * @author <NAME> */ public class Iterators { public static IntUnaryOperator incrementingBy(int value) { return i -> i + value; } public static LongUnaryOperator incrementingBy(long value) { return i -> i + value; } public static DoubleUnaryOperator incrementingBy(double value) { return i -> i + value; } public static IntUnaryOperator decrementingBy(int value) { return i -> i - value; } public static LongUnaryOperator decrementingBy(long value) { return i -> i - value; } public static DoubleUnaryOperator decrementingBy(double value) { return i -> i - value; } }
843
0.676056
0.676056
36
22.666666
23.651403
68
false
false
0
0
0
0
0
0
0.277778
false
false
15
1a9ef6763905f5b8f5f0fe3483383aee1e7246e4
31,696,858,654,481
9bdabce6d5ae17fad049568ab91f55fb9887b16e
/src/main/java/ru/gruzdov/mvc/dao/DepartmentDAOImpl.java
fecbf85b86182e7e9e91a977683a755dc73183d5
[]
no_license
Evgeny985/crud
https://github.com/Evgeny985/crud
497827fe429bda1e02a87e6d12bd0911d91610ff
87bc5effdaca36c875b18616c0d55c48f0c01bd2
refs/heads/master
2023-02-20T03:39:25.585000
2021-01-04T19:19:44
2021-01-04T19:19:44
317,328,925
4
1
null
false
2020-12-15T13:33:30
2020-11-30T19:46:51
2020-12-14T17:19:07
2020-12-15T13:33:29
44
1
0
0
Java
false
false
package ru.gruzdov.mvc.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import ru.gruzdov.mvc.model.Department; import java.util.List; @Repository public class DepartmentDAOImpl implements DepartmentDAO { @Autowired private SessionFactory sessionFactory; @Override public void addDepartment(Department department) { sessionFactory.getCurrentSession().persist(department); } @Override public Department getDepartmentById(Integer id) { return sessionFactory.getCurrentSession().get(Department.class, id); } @Override public void updateDepartment(Department department) { sessionFactory.getCurrentSession().update(department); } @Override public void deleteDepartment(Integer id) { sessionFactory.getCurrentSession().delete(getDepartmentById(id)); } @Override @SuppressWarnings("unchecked") public List<Department> getAllDepartmentByCityId(Integer cityId) { Session session = sessionFactory.getCurrentSession(); return session.createQuery("select d from Department d join d.city c where c.id=:id").setParameter("id", cityId).list(); } }
UTF-8
Java
1,299
java
DepartmentDAOImpl.java
Java
[]
null
[]
package ru.gruzdov.mvc.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import ru.gruzdov.mvc.model.Department; import java.util.List; @Repository public class DepartmentDAOImpl implements DepartmentDAO { @Autowired private SessionFactory sessionFactory; @Override public void addDepartment(Department department) { sessionFactory.getCurrentSession().persist(department); } @Override public Department getDepartmentById(Integer id) { return sessionFactory.getCurrentSession().get(Department.class, id); } @Override public void updateDepartment(Department department) { sessionFactory.getCurrentSession().update(department); } @Override public void deleteDepartment(Integer id) { sessionFactory.getCurrentSession().delete(getDepartmentById(id)); } @Override @SuppressWarnings("unchecked") public List<Department> getAllDepartmentByCityId(Integer cityId) { Session session = sessionFactory.getCurrentSession(); return session.createQuery("select d from Department d join d.city c where c.id=:id").setParameter("id", cityId).list(); } }
1,299
0.742879
0.742879
42
29.928572
29.367453
129
false
false
0
0
0
0
0
0
0.380952
false
false
15
3fe8843dcdd1deddfc51606b9a10fe6e27054193
944,892,820,535
c91190b30511cd5f6cac63adb30c74fd31cfb2c6
/practica 3/ej5/Client2.java
9c60ebbfdbb1f109fdcb1e7eea4c3a464f1d3810
[]
no_license
cristiansteib/programacionDistribuidaYTiempoReal
https://github.com/cristiansteib/programacionDistribuidaYTiempoReal
dc8462ee81937c4a5a98afd520be1f396c04cfeb
58a1b0f46fba91df1f0672d539418a9395a1d0dc
refs/heads/master
2020-07-25T02:43:31.157000
2019-11-22T20:31:33
2019-11-22T20:31:33
208,138,512
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.rmi.Naming; import java.rmi.registry.Registry; public class Client2 { public static void main(String[] args) { if (args.length != 1) { System.out.println("1 argument needed: (remote) hostname"); System.exit(1); } try { String rname = "//" + args[0] + ":" + Registry.REGISTRY_PORT + "/remote"; RemoteClassInterface remote = (RemoteClassInterface) Naming.lookup(rname); String data = "client 2"; remote.sendThisBack(data); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
620
java
Client2.java
Java
[]
null
[]
import java.rmi.Naming; import java.rmi.registry.Registry; public class Client2 { public static void main(String[] args) { if (args.length != 1) { System.out.println("1 argument needed: (remote) hostname"); System.exit(1); } try { String rname = "//" + args[0] + ":" + Registry.REGISTRY_PORT + "/remote"; RemoteClassInterface remote = (RemoteClassInterface) Naming.lookup(rname); String data = "client 2"; remote.sendThisBack(data); } catch (Exception e) { e.printStackTrace(); } } }
620
0.553226
0.543548
22
27.181818
25.546103
86
false
false
0
0
0
0
0
0
0.409091
false
false
15
d5d7c11732a1e0714c29036dce4b83abbbbe85d2
10,376,641,005,100
3c317c290d741cd212e003dbd995e3e3d3a3d7ba
/buoy-home-set-servlet/src/main/java/com/jnc/BuoySetServletApplication.java
30c778515ff3e10e07b12d77967fb4755c146685
[]
no_license
JJ-Choi1999/BuoyWeb
https://github.com/JJ-Choi1999/BuoyWeb
6847643fb00080f83c69aed968e18f684d1b2cdf
3493e02aaa13874f589a76835325099ec581c7ba
refs/heads/master
2022-12-01T03:22:21.030000
2020-01-05T03:21:28
2020-01-05T03:21:28
231,858,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jnc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * 模块名称: 我的设置服务 * 功能说明: 获取相关信息并储存 * 模块关联实体: * (1)Users * * * 跳入模块URL: http://localhost:8201/set?usersname=${usersname} * 模块自身URL: http://localhost:8401/SetServlet * 模块跳出URL: http://localhost:8131/index?usersname=${usersname} * * * * * @author JNC * */ @SpringBootApplication public class BuoySetServletApplication { /** * RabbitMQ必需同时具有交换器,进入队列和错误队列 * @param args */ public static void main(String[] args) { SpringApplication.run(BuoySetServletApplication.class, args); } }
UTF-8
Java
838
java
BuoySetServletApplication.java
Java
[ { "context": "usersname=${usersname} \n * \n * \n * \n * \n * @author JNC\n *\n */\n@SpringBootApplication\npublic class BuoySe", "end": 477, "score": 0.9996042251586914, "start": 474, "tag": "USERNAME", "value": "JNC" } ]
null
[]
package com.jnc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * 模块名称: 我的设置服务 * 功能说明: 获取相关信息并储存 * 模块关联实体: * (1)Users * * * 跳入模块URL: http://localhost:8201/set?usersname=${usersname} * 模块自身URL: http://localhost:8401/SetServlet * 模块跳出URL: http://localhost:8131/index?usersname=${usersname} * * * * * @author JNC * */ @SpringBootApplication public class BuoySetServletApplication { /** * RabbitMQ必需同时具有交换器,进入队列和错误队列 * @param args */ public static void main(String[] args) { SpringApplication.run(BuoySetServletApplication.class, args); } }
838
0.727778
0.709722
35
19.571428
22.54302
68
false
false
0
0
0
0
0
0
0.428571
false
false
15
8dfb34b243df43267ac578f6e7dce1a8f84299aa
26,096,221,311,623
6f7f198b31803daf36a2b4290add323ab2caf7ff
/Software Construction/Minesweeper/server/Board.java
b0499a9ed005add8ab7d2ddae054b7851e51fc86
[]
no_license
mattyhk/MITWork
https://github.com/mattyhk/MITWork
bcefdc2dfa90261e4bf1d7a2890da398d46b3155
f55342326e1604a936890267c34aa6a23fcb463e
refs/heads/master
2016-09-01T19:53:03.797000
2014-02-07T21:57:28
2014-02-07T21:57:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package minesweeper.server; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; // The board data structure is thread safe because: // 1) Each method accessible to a thread that mutates the state of the Board, i.e. fullDig(), halfDig(), flag(), deFlag() // is wrapped in a synchronized wrapper // - therefore, whichever each thread will acquire the lock only after an earlier thread has fully mutated the board // and will release it before any other thread can mutate the board // 2) Only non-mutable objects are returned to the threads - in this case they are Strings. // 3) Each observer method, i.e. look(), that is available to a thread is also wrapped in a synchronized wrapper // - therefore, a thread can only observe the state of a board after an earlier thread has mutated it and before a later thread mutates it. /** * Class that represents a minesweeper board of size N*N */ public class Board { private Cell[][] board; private final int size; public Board(int N, double probability) { size = N; board = new Cell[N][N]; for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) { if (Math.random() < probability) { board[x][y] = new Cell(x, y, true); } else { board[x][y] = new Cell(x, y, false); } } } } public Board(int N) { size = N; board = new Cell[N][N]; for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) { board[x][y] = new Cell(x, y, false); } } } @SuppressWarnings("resource") public Board(File file, boolean debug) { ArrayList<Cell> boardList = new ArrayList<Cell>(); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; int numLines = 0; int x = 0; int y = 0; ArrayList<Integer> lineLengths = new ArrayList<Integer>(); try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); // dis.available() returns 0 if the file does not have more lines. while (dis.available() != 0) { @SuppressWarnings("deprecation") String currentLine = dis.readLine(); y = 0; numLines++; lineLengths.add(currentLine.length()); // Check the first character of the line char c = currentLine.charAt(0); if (c != '0' && c != '1') { throw new RuntimeException( "invalid input - first character not 0 or 1."); } // Loop through all the characters of the line for (int i = 0; i < currentLine.length(); i++) { char currentChar = currentLine.charAt(i); // Check validity of each character if (currentChar != '1' && currentChar != '0' && currentChar != ' ' && currentChar != '\n') { throw new RuntimeException( "invalid input - character is something other than 1, 0 or space"); } else if (currentChar == '1' || currentChar == '0') { if (i + 1 < currentLine.length()) { char next = currentLine.charAt(i + 1); if (next != ' ' && next != '\n') { throw new RuntimeException( "invalid input - something other than a space or new line follows a 1 or 0"); } } if (currentChar == '1') { boardList.add(new Cell(x, y, true)); y++; } else { boardList.add(new Cell(x, y, false)); y++; } } else if (currentChar == ' ') { if (i + 1 < currentLine.length()) { char next = currentLine.charAt(i + 1); if (next != '1' && next != '0') { throw new RuntimeException( "invalid input - a 1 or 0 does not follow a space"); } } } } // moving on to next line - increment x x++; } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Check the dimensions if (x != y) { throw new RuntimeException("invalid input - dimensions differ"); } // Check every line is the same length for (int i = 0; i < lineLengths.size() - 1; i++) { if (lineLengths.get(i) != lineLengths.get(i + 1)) { throw new RuntimeException( "invalid input - line lengths differ"); } } // Everything is fine size = numLines; board = new Cell[size][size]; for (Cell cell : boardList) { board[cell.getCoordinates()[0]][cell.getCoordinates()[1]] = cell; } } /** * @param x * X coordinate * @param y * Y coordinate * @return The cell at (x, y) * @throws IllegalArgumentException * if coordinates are not valid */ private Cell getCell(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } return board[x][y]; } /** * Sets the state of the cell at (x, y) Assumes valid coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @param state * The state to be set */ public void setCellState(int x, int y, String state) { getCell(x, y).setState(state); } /** * Sets whether or not the cell at (x, y) contains a bomb Assumes valid * coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @param bomb * True if cell contains a bomb */ public void setCellBomb(int x, int y, boolean bomb) { getCell(x, y).setBomb(bomb); } /** * Gets the state of the cell at (x, y) Assumes valid coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @return The state of the cell at (x, y) */ public String getCellState(int x, int y) { return getCell(x, y).getState(); } /** * Returns true if there is a bomb at (x, y); false otherwise Assumes valid * coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @return True if there is a bomb in (x, y); false otherwise */ public boolean cellContainsBomb(int x, int y) { return getCell(x, y).hasBomb(); } /** * Returns a list of the cells representing all the possible neighbours of * the cell at (x, y) within the board * * @param x * X Coordinate * @param y * Y Coordinate * @return List of all neighbours * @throws IllegalArgumentException * if non valid coordinates passed in */ public List<Cell> getNeighbours(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } ArrayList<Cell> neighbours = new ArrayList<Cell>(); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (x + i >= 0 && x + i < size && y + j >= 0 && y + j < size) { if (!(x + i == x && y + j == y)) { neighbours.add(getCell(x + i, y + j)); } } } } return neighbours; } /** * Returns a list containing all of the neighbouring cells whose state is * "untouched" * * @param x * X Coordinate * @param y * Y Coordinate * @return List of all "untouched" neighbours * @throws IllegalArgumentException * if non valid coordinates passed in */ public List<Cell> getUntouchedNeighbours(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } ArrayList<Cell> neighbours = new ArrayList<Cell>(); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (x + i >= 0 && x + i < size && y + j >= 0 && y + j < size) { if (!(x + i == x && y + j == y)) { Cell cell = getCell(x + i, y + j); if (cell.getState() == "untouched") { neighbours.add(cell); } } } } } return neighbours; } /** * Counts the number of neighbouring cells of the cell at (x, y) that * contain bombs * * @param x * X Coordinate * @param y * Y Coordinate * @return The number of neighbouring cells that contain bombs * @throws IllegalArgumentException * if non valid coordinates passed in */ public int countBombs(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } List<Cell> neighbours = getNeighbours(x, y); int count = 0; for (Cell cell : neighbours) { if (cell.hasBomb()) { count++; } } return count; } /** * If none of the neighbours of the cell at (x, y) contain bombs, changes * the state all of the untouched neighbours to "dug". Recurses for each * untouched neighbour of (x, y) * * @assumes (x, y) are valid cell coordinates * @param x * X Coordinate * @param y * Y Coordinate * @modifies If (x, y) has no neighbouring bombs, changes the state of all * the untouched neighbours to "dug" */ public synchronized void halfDig(int x, int y) { if (countBombs(x, y) == 0) { for (Cell cell : getUntouchedNeighbours(x, y)) { cell.setState("dug"); halfDig(cell.getCoordinates()[0], cell.getCoordinates()[1]); } } } /** * Fulfills the obligations of a DIG message being passed in. If either x or * y is less than 0, or either x or y is equal to or greater than the board * size, or square x,y is not in the 'untouched' state, do nothing and * return a BOARD message. If square x,y's state is 'untouched', change * square x,y's state to 'dug'. If square x,y contains a bomb, change it so * that it contains no bomb and send a BOOM message to the user. Then, if * the DEBUG flag is set to 'false', terminate the user's connection If the * square x,y has no neighbor squares with bombs, then for each of x,y's * 'untouched' neighbor squares, change said square to 'dug' and repeat * * @param x * X Coordinate * @param y * Y Coordinate * @modifies If state of (x, y) is "untouched" change it to "dug" * @modifies If (x, y) contains a bomb, it no longer does * @modifies If (x, y) has no neighbouring bombs, changes the state of all * the untouched neighbours to "dug" * @return If no boom message is sent, return a board message, else return * boom */ public synchronized String fullDig(int x, int y) { if (x < 0 || y < 0 || x >= size || y >= size || getCell(x, y).getState() != "untouched") { String board = createBoard(); return board; } else { if (cellContainsBomb(x, y)) { setCellBomb(x, y, false); String boom = createBoom(); // return Boom message - terminate client connection if need be fullDig(x, y); digAfterBoom(x, y); return boom; } else { setCellState(x, y, "dug"); halfDig(x, y); String board = createBoard(); return board; } } } /** * Updates the count of the cell around a 'dug' bomb, expanding the dug cells if they have no neighbouring bombs * @param x X Coordinate * @param y Y Coordinate * @modifies If a neighbouring cell of a bomb location (x,y) now has no surrounding bombs, calls halfDig on it to expand the area of "dug" cells */ public synchronized void digAfterBoom(int x, int y){ for (Cell cell : getNeighbours(x, y)) { if (cell.getState() == "dug"){ if (countBombs(cell.getCoordinates()[0], cell.getCoordinates()[1]) == 0){ halfDig(cell.getCoordinates()[0], cell.getCoordinates()[1]); } } } } /** * Creates and returns a BOARD message representing the board's state * * @return A string representing the board's state */ private synchronized String createBoard() { StringBuilder boardMessage = new StringBuilder(); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { if (getCellState(x, y) == "untouched") { boardMessage.append("-"); } else if (getCellState(x, y) == "flagged") { boardMessage.append("F"); } else if (getCellState(x, y) == "dug") { int count = countBombs(x, y); if (count == 0) { boardMessage.append(" "); } else if (count > 8) { throw new RuntimeException( "uh oh count is doing something weird - returns more bombs then neighbours"); } else { boardMessage.append(count); } } if (y == size - 1) { boardMessage.append("\n"); } else { boardMessage.append(" "); } } } return boardMessage.toString(); } /** * Creates and returns a BOOM message * * @return A string corresponding to a Boom message */ private String createBoom() { String boom = "BOOM!" + "\n"; return boom; } /** * Fulfills the obligations of a LOOK message being passed in. Returns a * BOARD message, a string representation of the board's state. * * @return A string that represents the BOARD Message */ public synchronized String look() { String boardMessage = createBoard(); return boardMessage; } /** * Fulfills the obligations of a FLAG message being passed in. If x and y * are both greater than or equal to 0, and less than the board size, and * square x,y is in the 'untouched' state, change it to be in the 'flagged' * state. Otherwise, do not mutate any state on the server. Return a BOARD * message * * @param x * X Coordinate * @param y * Y Coordinate * @return a String representing a BOARD message */ public synchronized String flag(int x, int y) { String boardMessage; if (x < 0 || y < 0 || x >= size || y >= size || getCell(x, y).getState() != "untouched") { boardMessage = createBoard(); } else { setCellState(x, y, "flagged"); boardMessage = createBoard(); } return boardMessage; } /** * Fulfills the obligations of a DEFLAG message being passed in. If x and y * are both greater than or equal to 0, and less than the board size, and * square x,y is in the 'flagged' state, change it to be in the 'untouched' * state. Otherwise, do not mutate any state on the server. For any DEFLAG * message, return a BOARD message */ public synchronized String deFlag(int x, int y) { String boardMessage; if (x < 0 || y < 0 || x >= size || y >= size || getCell(x, y).getState() != "flagged") { boardMessage = createBoard(); } else { setCellState(x, y, "untouched"); boardMessage = createBoard(); } return boardMessage; } /** * Fulfills the obligations of a HELP_REQ message being passed in. Returns a * HELP message. Does not mutate anything on the server. */ public String help() { String helpMessage = "Valid commands are: look, dig X Y, flag X Y, deflag X Y." + "\n" + "Look returns a message representing the current state of the board " + "where a - indicates a square is untouched, a F indicates a square is flagged, " + "a space indicates a square has been dug and has no neighbours that contain bombs, " + "and a digit between (1-8) indicates a square has been dug and has that number of neighbours that contain bombs. " + "\n" + "Dig is a command allowing you to dig a square at coordinates X,Y. Ensure that the coordinates are valid coordinates " + "- otherwise nothing will happen. X and Y are in the range (0, " + size + "). " + "\n" + "Flag allows you to mark a square with a flag. Deflag allows you to unmark a flagged square." + "\n"; return helpMessage; } /** * Fulfills the obligations of a BYE message being passed in Terminates the * connection with the client */ public void bye() { // terminates the connection } /** * Creates a HELLO message fulfilling the obligations * * @param n * The number of clients connected * @return a String containing the HELLO message */ public static String hello(int n) { String hello = "Welcome to Minesweeper. " + n + " people are playing including you. Type 'help' for help." + "\n"; return hello; } }
UTF-8
Java
19,844
java
Board.java
Java
[]
null
[]
package minesweeper.server; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; // The board data structure is thread safe because: // 1) Each method accessible to a thread that mutates the state of the Board, i.e. fullDig(), halfDig(), flag(), deFlag() // is wrapped in a synchronized wrapper // - therefore, whichever each thread will acquire the lock only after an earlier thread has fully mutated the board // and will release it before any other thread can mutate the board // 2) Only non-mutable objects are returned to the threads - in this case they are Strings. // 3) Each observer method, i.e. look(), that is available to a thread is also wrapped in a synchronized wrapper // - therefore, a thread can only observe the state of a board after an earlier thread has mutated it and before a later thread mutates it. /** * Class that represents a minesweeper board of size N*N */ public class Board { private Cell[][] board; private final int size; public Board(int N, double probability) { size = N; board = new Cell[N][N]; for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) { if (Math.random() < probability) { board[x][y] = new Cell(x, y, true); } else { board[x][y] = new Cell(x, y, false); } } } } public Board(int N) { size = N; board = new Cell[N][N]; for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) { board[x][y] = new Cell(x, y, false); } } } @SuppressWarnings("resource") public Board(File file, boolean debug) { ArrayList<Cell> boardList = new ArrayList<Cell>(); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; int numLines = 0; int x = 0; int y = 0; ArrayList<Integer> lineLengths = new ArrayList<Integer>(); try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); // dis.available() returns 0 if the file does not have more lines. while (dis.available() != 0) { @SuppressWarnings("deprecation") String currentLine = dis.readLine(); y = 0; numLines++; lineLengths.add(currentLine.length()); // Check the first character of the line char c = currentLine.charAt(0); if (c != '0' && c != '1') { throw new RuntimeException( "invalid input - first character not 0 or 1."); } // Loop through all the characters of the line for (int i = 0; i < currentLine.length(); i++) { char currentChar = currentLine.charAt(i); // Check validity of each character if (currentChar != '1' && currentChar != '0' && currentChar != ' ' && currentChar != '\n') { throw new RuntimeException( "invalid input - character is something other than 1, 0 or space"); } else if (currentChar == '1' || currentChar == '0') { if (i + 1 < currentLine.length()) { char next = currentLine.charAt(i + 1); if (next != ' ' && next != '\n') { throw new RuntimeException( "invalid input - something other than a space or new line follows a 1 or 0"); } } if (currentChar == '1') { boardList.add(new Cell(x, y, true)); y++; } else { boardList.add(new Cell(x, y, false)); y++; } } else if (currentChar == ' ') { if (i + 1 < currentLine.length()) { char next = currentLine.charAt(i + 1); if (next != '1' && next != '0') { throw new RuntimeException( "invalid input - a 1 or 0 does not follow a space"); } } } } // moving on to next line - increment x x++; } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Check the dimensions if (x != y) { throw new RuntimeException("invalid input - dimensions differ"); } // Check every line is the same length for (int i = 0; i < lineLengths.size() - 1; i++) { if (lineLengths.get(i) != lineLengths.get(i + 1)) { throw new RuntimeException( "invalid input - line lengths differ"); } } // Everything is fine size = numLines; board = new Cell[size][size]; for (Cell cell : boardList) { board[cell.getCoordinates()[0]][cell.getCoordinates()[1]] = cell; } } /** * @param x * X coordinate * @param y * Y coordinate * @return The cell at (x, y) * @throws IllegalArgumentException * if coordinates are not valid */ private Cell getCell(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } return board[x][y]; } /** * Sets the state of the cell at (x, y) Assumes valid coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @param state * The state to be set */ public void setCellState(int x, int y, String state) { getCell(x, y).setState(state); } /** * Sets whether or not the cell at (x, y) contains a bomb Assumes valid * coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @param bomb * True if cell contains a bomb */ public void setCellBomb(int x, int y, boolean bomb) { getCell(x, y).setBomb(bomb); } /** * Gets the state of the cell at (x, y) Assumes valid coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @return The state of the cell at (x, y) */ public String getCellState(int x, int y) { return getCell(x, y).getState(); } /** * Returns true if there is a bomb at (x, y); false otherwise Assumes valid * coordinates * * @param x * X coordinate of the cell * @param y * Y coordinate of the cell * @return True if there is a bomb in (x, y); false otherwise */ public boolean cellContainsBomb(int x, int y) { return getCell(x, y).hasBomb(); } /** * Returns a list of the cells representing all the possible neighbours of * the cell at (x, y) within the board * * @param x * X Coordinate * @param y * Y Coordinate * @return List of all neighbours * @throws IllegalArgumentException * if non valid coordinates passed in */ public List<Cell> getNeighbours(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } ArrayList<Cell> neighbours = new ArrayList<Cell>(); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (x + i >= 0 && x + i < size && y + j >= 0 && y + j < size) { if (!(x + i == x && y + j == y)) { neighbours.add(getCell(x + i, y + j)); } } } } return neighbours; } /** * Returns a list containing all of the neighbouring cells whose state is * "untouched" * * @param x * X Coordinate * @param y * Y Coordinate * @return List of all "untouched" neighbours * @throws IllegalArgumentException * if non valid coordinates passed in */ public List<Cell> getUntouchedNeighbours(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } ArrayList<Cell> neighbours = new ArrayList<Cell>(); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (x + i >= 0 && x + i < size && y + j >= 0 && y + j < size) { if (!(x + i == x && y + j == y)) { Cell cell = getCell(x + i, y + j); if (cell.getState() == "untouched") { neighbours.add(cell); } } } } } return neighbours; } /** * Counts the number of neighbouring cells of the cell at (x, y) that * contain bombs * * @param x * X Coordinate * @param y * Y Coordinate * @return The number of neighbouring cells that contain bombs * @throws IllegalArgumentException * if non valid coordinates passed in */ public int countBombs(int x, int y) { if (x < 0 || x >= size || y < 0 || y >= size) { throw new IllegalArgumentException( "Non valid coordinates are being accessed"); } List<Cell> neighbours = getNeighbours(x, y); int count = 0; for (Cell cell : neighbours) { if (cell.hasBomb()) { count++; } } return count; } /** * If none of the neighbours of the cell at (x, y) contain bombs, changes * the state all of the untouched neighbours to "dug". Recurses for each * untouched neighbour of (x, y) * * @assumes (x, y) are valid cell coordinates * @param x * X Coordinate * @param y * Y Coordinate * @modifies If (x, y) has no neighbouring bombs, changes the state of all * the untouched neighbours to "dug" */ public synchronized void halfDig(int x, int y) { if (countBombs(x, y) == 0) { for (Cell cell : getUntouchedNeighbours(x, y)) { cell.setState("dug"); halfDig(cell.getCoordinates()[0], cell.getCoordinates()[1]); } } } /** * Fulfills the obligations of a DIG message being passed in. If either x or * y is less than 0, or either x or y is equal to or greater than the board * size, or square x,y is not in the 'untouched' state, do nothing and * return a BOARD message. If square x,y's state is 'untouched', change * square x,y's state to 'dug'. If square x,y contains a bomb, change it so * that it contains no bomb and send a BOOM message to the user. Then, if * the DEBUG flag is set to 'false', terminate the user's connection If the * square x,y has no neighbor squares with bombs, then for each of x,y's * 'untouched' neighbor squares, change said square to 'dug' and repeat * * @param x * X Coordinate * @param y * Y Coordinate * @modifies If state of (x, y) is "untouched" change it to "dug" * @modifies If (x, y) contains a bomb, it no longer does * @modifies If (x, y) has no neighbouring bombs, changes the state of all * the untouched neighbours to "dug" * @return If no boom message is sent, return a board message, else return * boom */ public synchronized String fullDig(int x, int y) { if (x < 0 || y < 0 || x >= size || y >= size || getCell(x, y).getState() != "untouched") { String board = createBoard(); return board; } else { if (cellContainsBomb(x, y)) { setCellBomb(x, y, false); String boom = createBoom(); // return Boom message - terminate client connection if need be fullDig(x, y); digAfterBoom(x, y); return boom; } else { setCellState(x, y, "dug"); halfDig(x, y); String board = createBoard(); return board; } } } /** * Updates the count of the cell around a 'dug' bomb, expanding the dug cells if they have no neighbouring bombs * @param x X Coordinate * @param y Y Coordinate * @modifies If a neighbouring cell of a bomb location (x,y) now has no surrounding bombs, calls halfDig on it to expand the area of "dug" cells */ public synchronized void digAfterBoom(int x, int y){ for (Cell cell : getNeighbours(x, y)) { if (cell.getState() == "dug"){ if (countBombs(cell.getCoordinates()[0], cell.getCoordinates()[1]) == 0){ halfDig(cell.getCoordinates()[0], cell.getCoordinates()[1]); } } } } /** * Creates and returns a BOARD message representing the board's state * * @return A string representing the board's state */ private synchronized String createBoard() { StringBuilder boardMessage = new StringBuilder(); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { if (getCellState(x, y) == "untouched") { boardMessage.append("-"); } else if (getCellState(x, y) == "flagged") { boardMessage.append("F"); } else if (getCellState(x, y) == "dug") { int count = countBombs(x, y); if (count == 0) { boardMessage.append(" "); } else if (count > 8) { throw new RuntimeException( "uh oh count is doing something weird - returns more bombs then neighbours"); } else { boardMessage.append(count); } } if (y == size - 1) { boardMessage.append("\n"); } else { boardMessage.append(" "); } } } return boardMessage.toString(); } /** * Creates and returns a BOOM message * * @return A string corresponding to a Boom message */ private String createBoom() { String boom = "BOOM!" + "\n"; return boom; } /** * Fulfills the obligations of a LOOK message being passed in. Returns a * BOARD message, a string representation of the board's state. * * @return A string that represents the BOARD Message */ public synchronized String look() { String boardMessage = createBoard(); return boardMessage; } /** * Fulfills the obligations of a FLAG message being passed in. If x and y * are both greater than or equal to 0, and less than the board size, and * square x,y is in the 'untouched' state, change it to be in the 'flagged' * state. Otherwise, do not mutate any state on the server. Return a BOARD * message * * @param x * X Coordinate * @param y * Y Coordinate * @return a String representing a BOARD message */ public synchronized String flag(int x, int y) { String boardMessage; if (x < 0 || y < 0 || x >= size || y >= size || getCell(x, y).getState() != "untouched") { boardMessage = createBoard(); } else { setCellState(x, y, "flagged"); boardMessage = createBoard(); } return boardMessage; } /** * Fulfills the obligations of a DEFLAG message being passed in. If x and y * are both greater than or equal to 0, and less than the board size, and * square x,y is in the 'flagged' state, change it to be in the 'untouched' * state. Otherwise, do not mutate any state on the server. For any DEFLAG * message, return a BOARD message */ public synchronized String deFlag(int x, int y) { String boardMessage; if (x < 0 || y < 0 || x >= size || y >= size || getCell(x, y).getState() != "flagged") { boardMessage = createBoard(); } else { setCellState(x, y, "untouched"); boardMessage = createBoard(); } return boardMessage; } /** * Fulfills the obligations of a HELP_REQ message being passed in. Returns a * HELP message. Does not mutate anything on the server. */ public String help() { String helpMessage = "Valid commands are: look, dig X Y, flag X Y, deflag X Y." + "\n" + "Look returns a message representing the current state of the board " + "where a - indicates a square is untouched, a F indicates a square is flagged, " + "a space indicates a square has been dug and has no neighbours that contain bombs, " + "and a digit between (1-8) indicates a square has been dug and has that number of neighbours that contain bombs. " + "\n" + "Dig is a command allowing you to dig a square at coordinates X,Y. Ensure that the coordinates are valid coordinates " + "- otherwise nothing will happen. X and Y are in the range (0, " + size + "). " + "\n" + "Flag allows you to mark a square with a flag. Deflag allows you to unmark a flagged square." + "\n"; return helpMessage; } /** * Fulfills the obligations of a BYE message being passed in Terminates the * connection with the client */ public void bye() { // terminates the connection } /** * Creates a HELLO message fulfilling the obligations * * @param n * The number of clients connected * @return a String containing the HELLO message */ public static String hello(int n) { String hello = "Welcome to Minesweeper. " + n + " people are playing including you. Type 'help' for help." + "\n"; return hello; } }
19,844
0.501965
0.497581
551
35.016335
27.438725
149
false
false
0
0
0
0
0
0
0.584392
false
false
15
217e1f4b96f434d8ad56cf014236658b591abd12
19,834,158,987,823
7de94eb18b8f99891675a52424cc2b50e2acaca1
/src/shotapps/allinone/data/SentenceData.java
b875af3e731081b10ab0643934a194934328d2e4
[]
no_license
shotkento/allinone
https://github.com/shotkento/allinone
4bc9d53015398a9af1fd1e74eb0b3e36fe1eda7f
2041010509f271daa6a576d0c78f06efd8699c0e
refs/heads/master
2016-09-05T17:40:59.841000
2014-10-22T23:26:16
2014-10-22T23:26:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package shotapps.allinone.data; public class SentenceData { private int id; private String engSent; private String jpnSentOrder; private String jpnSentNormal; private int correct; private int count; private int checked; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEngSent() { return engSent; } public void setEngSent(String engSent) { this.engSent = engSent; } public String getJpnSentOrder() { return jpnSentOrder; } public void setJpnSentOrder(String jpnSentOrder) { this.jpnSentOrder = jpnSentOrder; } public String getJpnSentNormal() { return jpnSentNormal; } public void setJpnSentNormal(String jpnSentNormal) { this.jpnSentNormal = jpnSentNormal; } public int getCorrect() { return correct; } public void setCorrect(int correct) { this.correct = correct; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getChecked() { return checked; } public void setChecked(int checked) { this.checked = checked; } }
UTF-8
Java
1,288
java
SentenceData.java
Java
[]
null
[]
package shotapps.allinone.data; public class SentenceData { private int id; private String engSent; private String jpnSentOrder; private String jpnSentNormal; private int correct; private int count; private int checked; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEngSent() { return engSent; } public void setEngSent(String engSent) { this.engSent = engSent; } public String getJpnSentOrder() { return jpnSentOrder; } public void setJpnSentOrder(String jpnSentOrder) { this.jpnSentOrder = jpnSentOrder; } public String getJpnSentNormal() { return jpnSentNormal; } public void setJpnSentNormal(String jpnSentNormal) { this.jpnSentNormal = jpnSentNormal; } public int getCorrect() { return correct; } public void setCorrect(int correct) { this.correct = correct; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getChecked() { return checked; } public void setChecked(int checked) { this.checked = checked; } }
1,288
0.608696
0.608696
68
17.941177
15.8373
56
false
false
0
0
0
0
0
0
0.323529
false
false
15
646d2f55a3cee015b550a5a178db32dae2468be8
10,350,871,203,978
7304d88db36cd6497bc4e498f0d66f9808387099
/atelieoral/src/main/java/com/atelieoral/interfaces/IFotosInicio.java
d1db485fa6c359f7d01e2e17d4564e55d760c3ca
[]
no_license
marciofica/sunyan
https://github.com/marciofica/sunyan
a094e9fe41a0056530695faf5bfbbe54f4c6fd08
4e8ba250b855eee9b37327b8accd8c8192059798
refs/heads/master
2019-07-29T16:11:21.782000
2013-11-22T00:25:06
2013-11-22T00:38:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atelieoral.interfaces; import com.atelieoral.entities.FotosInicio; public interface IFotosInicio extends IGeneric<FotosInicio>{ }
UTF-8
Java
152
java
IFotosInicio.java
Java
[]
null
[]
package com.atelieoral.interfaces; import com.atelieoral.entities.FotosInicio; public interface IFotosInicio extends IGeneric<FotosInicio>{ }
152
0.796053
0.796053
7
19.714285
23.559738
60
false
false
0
0
0
0
0
0
0.285714
false
false
15
53886cc8ee07ebfe3a2a1e1226c3bec0516a3e12
29,394,756,194,242
73e93481f8cdd4fe464d53615e974453aa82cb37
/src/main/java/controllers/jobs/MakeAnimalsAgeJob.java
fec842081af26d24fad5258bddf2737ed31c37a0
[]
no_license
byoan/Zoo
https://github.com/byoan/Zoo
c60b6535d0a211d738559bee7324523f61789220
20e868c457e6dfd833ff66b1ac4596e44030d32e
refs/heads/master
2021-07-17T01:06:42.723000
2017-10-22T21:10:51
2017-10-22T21:10:51
105,978,094
1
1
null
false
2017-10-19T20:59:40
2017-10-06T07:27:27
2017-10-08T17:16:27
2017-10-19T20:59:39
329
1
0
7
Java
null
null
package controllers.jobs; import controllers.zoo.Zoo; import models.animals.Animal; import models.animals.Wolf; import models.enclosures.Enclosure; import views.View; /** * Job that will be executed every 50 turns, which will make the animals older * * @author Yoan Ballesteros * @author Antoine Sirven * @version 1.0 */ public class MakeAnimalsAgeJob implements Runnable { /** * The zoo instance to manipulate in the Job */ private Zoo zoo; /** * The current turn number */ private int turnNb; /** * Constructor for the MakeAnimalsAgeJob job * @param zoo The zoo instance that will be manipulated * @param turnNb The current turn number */ public MakeAnimalsAgeJob(Zoo zoo, int turnNb) { this.zoo = zoo; this.turnNb = turnNb; } /** * Getter for the zoo instance passed during the Job construction * @return The zoo instance */ public Zoo getZoo() { return this.zoo; } /** * Getter for the turn number passed during the Job construction * @return The current turn number */ public int getTurnNb() { return this.turnNb; } /** * Executes the job * Will call the getOlder method for each animal of the zoo * If an animal reaches the age above "Old", which is basically the oldest available, he dies */ @Override public void run() { for (Enclosure<Animal> enclosure : this.getZoo().getEnclosureList()) { // We must proceed this way, as using a foreach on the collection, and removing an item from this collection within the foreach will create an Exception for (int i = 0; i < enclosure.getNbAnimals(); i++) { Animal animal = enclosure.getAnimals().get(i); animal.getOlder(); if (animal.getAge() == 4 && animal.getSpecieName() == "Wolf") { ((Wolf)animal).getPack().remove((Wolf)animal); enclosure.remove(animal); View.displayWarningMessage("A " + animal.getSpecieName() + " died of old age in the " + enclosure.getName() + " enclosure.\n"); // Decrease i to always pick the first of the list i--; } } } } }
UTF-8
Java
2,324
java
MakeAnimalsAgeJob.java
Java
[ { "context": "s, which will make the animals older\n *\n * @author Yoan Ballesteros\n * @author Antoine Sirven\n * @version 1.0\n */\npub", "end": 282, "score": 0.999893844127655, "start": 266, "tag": "NAME", "value": "Yoan Ballesteros" }, { "context": "ls older\n *\n * @author Yoan Ballesteros\n * @author Antoine Sirven\n * @version 1.0\n */\npublic class MakeAnimalsAgeJo", "end": 308, "score": 0.9998967051506042, "start": 294, "tag": "NAME", "value": "Antoine Sirven" } ]
null
[]
package controllers.jobs; import controllers.zoo.Zoo; import models.animals.Animal; import models.animals.Wolf; import models.enclosures.Enclosure; import views.View; /** * Job that will be executed every 50 turns, which will make the animals older * * @author <NAME> * @author <NAME> * @version 1.0 */ public class MakeAnimalsAgeJob implements Runnable { /** * The zoo instance to manipulate in the Job */ private Zoo zoo; /** * The current turn number */ private int turnNb; /** * Constructor for the MakeAnimalsAgeJob job * @param zoo The zoo instance that will be manipulated * @param turnNb The current turn number */ public MakeAnimalsAgeJob(Zoo zoo, int turnNb) { this.zoo = zoo; this.turnNb = turnNb; } /** * Getter for the zoo instance passed during the Job construction * @return The zoo instance */ public Zoo getZoo() { return this.zoo; } /** * Getter for the turn number passed during the Job construction * @return The current turn number */ public int getTurnNb() { return this.turnNb; } /** * Executes the job * Will call the getOlder method for each animal of the zoo * If an animal reaches the age above "Old", which is basically the oldest available, he dies */ @Override public void run() { for (Enclosure<Animal> enclosure : this.getZoo().getEnclosureList()) { // We must proceed this way, as using a foreach on the collection, and removing an item from this collection within the foreach will create an Exception for (int i = 0; i < enclosure.getNbAnimals(); i++) { Animal animal = enclosure.getAnimals().get(i); animal.getOlder(); if (animal.getAge() == 4 && animal.getSpecieName() == "Wolf") { ((Wolf)animal).getPack().remove((Wolf)animal); enclosure.remove(animal); View.displayWarningMessage("A " + animal.getSpecieName() + " died of old age in the " + enclosure.getName() + " enclosure.\n"); // Decrease i to always pick the first of the list i--; } } } } }
2,306
0.598967
0.596386
77
29.181818
31.671089
164
false
false
0
0
0
0
0
0
0.337662
false
false
15
6814275b7e949f1f8d35be10d38fe6701bf1ea78
23,106,924,093,307
feb8e2fab2cb74800f6134f7120edbee5b556bb9
/src/main/java/org/onada/util/CaptureScreenshot.java
58da9c833a5919630acbfbeb30f226c8ae76bf0a
[]
no_license
rkshah/TestAutomation
https://github.com/rkshah/TestAutomation
303f8f9eb0c8f25be975d9577e7178481bd60ba4
67def4be0fd4d41f34fc5673d0eb4a9fe39e58f2
refs/heads/master
2021-03-01T07:47:33.159000
2020-03-08T06:58:57
2020-03-08T06:58:57
245,766,064
0
0
null
false
2020-10-13T20:09:49
2020-03-08T06:46:07
2020-03-08T06:59:02
2020-10-13T20:09:48
10
0
0
1
Java
false
false
package org.onada.util; public class CaptureScreenshot { }
UTF-8
Java
60
java
CaptureScreenshot.java
Java
[]
null
[]
package org.onada.util; public class CaptureScreenshot { }
60
0.783333
0.783333
4
14
13.874437
32
false
false
0
0
0
0
0
0
0.25
false
false
15
1d72b513e406973e342a4cd5fe4692e091a94ba8
3,959,959,896,315
5763e48303dc708107cf013345cb78ce1387c2be
/src/main/java/com/y2sec/blog/controller/HomeController.java
89f556ab533c6db582b2f4eacd8c5e4c7b7024a9
[]
no_license
y2sec/blog
https://github.com/y2sec/blog
f115d0baa92656febb77988d22d132d1b11051e3
3506d55a884f8f4853c02040163b1957222b1e74
refs/heads/master
2023-04-15T23:14:46.919000
2021-04-27T12:34:07
2021-04-27T12:34:07
328,602,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.y2sec.blog.controller; import com.y2sec.blog.domain.Post; import com.y2sec.blog.service.CategoryService; import com.y2sec.blog.service.PostService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller @RequiredArgsConstructor public class HomeController { private final CategoryService categoryService; private final PostService postService; @GetMapping("/") public String home(@RequestParam(name = "page", required = false, defaultValue = "1") long page, Model model) { List<Post> posts = postService.findPosts(); model.addAttribute("categoryList", categoryService.findCategory()); model.addAttribute("pageNumber", page); model.addAttribute("postSize", posts.size()); model.addAttribute("postList", posts.subList((int)Math.min((posts.size() / 10) * 10, (page-1) * 10), (int)Math.min(posts.size(), page * 10))); return "home"; } }
UTF-8
Java
1,209
java
HomeController.java
Java
[]
null
[]
package com.y2sec.blog.controller; import com.y2sec.blog.domain.Post; import com.y2sec.blog.service.CategoryService; import com.y2sec.blog.service.PostService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller @RequiredArgsConstructor public class HomeController { private final CategoryService categoryService; private final PostService postService; @GetMapping("/") public String home(@RequestParam(name = "page", required = false, defaultValue = "1") long page, Model model) { List<Post> posts = postService.findPosts(); model.addAttribute("categoryList", categoryService.findCategory()); model.addAttribute("pageNumber", page); model.addAttribute("postSize", posts.size()); model.addAttribute("postList", posts.subList((int)Math.min((posts.size() / 10) * 10, (page-1) * 10), (int)Math.min(posts.size(), page * 10))); return "home"; } }
1,209
0.742763
0.731183
35
33.542858
33.244843
150
false
false
0
0
0
0
0
0
0.828571
false
false
15
61db36349affa121d1eab2e4fd1b7e7356a5a01a
30,897,994,757,500
15e45de308b29f99dfa7aecbb091daf65cc059b5
/src/main/java/de/mbur/jlua/package-info.java
06f311e4afef1fff43a712d631b43c6f86f290fd
[]
no_license
MBurchard/ESOLuaBeautifier
https://github.com/MBurchard/ESOLuaBeautifier
dba18c827ecdf83769cf7828d75d2e744ba2e7be
a8aa40be5a7c5c53cf45b6791574fc60f9f1184b
refs/heads/master
2021-01-13T07:10:03.246000
2017-08-03T11:03:50
2017-08-03T11:03:50
95,044,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @author Martin Burchard * */ package de.mbur.jlua;
UTF-8
Java
59
java
package-info.java
Java
[ { "context": "/**\n * @author Martin Burchard\n *\n */\npackage de.mbur.jlua;", "end": 30, "score": 0.999875009059906, "start": 15, "tag": "NAME", "value": "Martin Burchard" } ]
null
[]
/** * @author <NAME> * */ package de.mbur.jlua;
50
0.627119
0.627119
5
11
10.334409
26
false
false
0
0
0
0
0
0
0.2
false
false
15
9b514ed0a9b652b34f3c7edfd5be5c1113573c28
13,460,427,547,948
d252d0caa8d2724872fa4ac7553cbb3d9845dc9d
/Linguagem de Programação 3/Projeto/TarvMath/src/BaseMotorDoJogo.java
dbea2df1346c3f0485332f381f6ee34488583fdf
[]
no_license
tarv7/Trabalhos-da-faculdade-UESC
https://github.com/tarv7/Trabalhos-da-faculdade-UESC
81a0ebefbf468a4d15050a60aacd192acd6f272f
40a6487de068b9e12fe0b533d3e626c21de0cbf5
refs/heads/master
2020-04-06T15:32:22.856000
2017-12-10T05:03:10
2017-12-10T05:03:10
45,571,531
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class BaseMotorDoJogo { MotorDoJogo ref; public MotorDoJogo getMotorDoJogo(Jogador jog) { // Escolhendo o modo de jogo a partir do usuario if(jog.modoJogo == 1) ref = new ModoRapido(); else if(jog.modoJogo == 2) ref = new ModoTreino(); else if(jog.modoJogo == 3) ref = new ModoCampanha(); else ref = null; return ref; } }
UTF-8
Java
421
java
BaseMotorDoJogo.java
Java
[]
null
[]
public class BaseMotorDoJogo { MotorDoJogo ref; public MotorDoJogo getMotorDoJogo(Jogador jog) { // Escolhendo o modo de jogo a partir do usuario if(jog.modoJogo == 1) ref = new ModoRapido(); else if(jog.modoJogo == 2) ref = new ModoTreino(); else if(jog.modoJogo == 3) ref = new ModoCampanha(); else ref = null; return ref; } }
421
0.565321
0.558195
18
21.277779
16.092806
53
false
false
0
0
0
0
0
0
1.055556
false
false
15
0ed772287393c6a92bbb1f9e02b0232d1685d7e8
15,633,681,004,004
481c61002354c6eb792f242a9b97206229d14283
/src/linear/Interval.java
bfd7b5d67fad3d336bd185d81a5d1570bfb73122
[]
no_license
Tarlusk/johnny-the-terrible
https://github.com/Tarlusk/johnny-the-terrible
451ff70ca013403d368e8f37d6c4a73d3262e2fa
6f4b95c10ebb0372a3c384cce2ac9089f96cfb92
refs/heads/master
2021-01-10T15:08:19.029000
2013-03-14T22:52:40
2013-03-14T22:52:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package linear; public class Interval { public float min; public float max; public Interval(float min, float max) { this.min = min; this.max = max; } public boolean intersects(Interval inter) { if(this.min > inter.max) { return false; } if (this.max < inter.min) { return false; } return true; } public float getIntersection(Interval inter) { if(this.min >= inter.max || this.max <= inter.min) { return 0; } if(inter.max >= this.max && inter.min >= this.min) { return inter.min - this.max; } else if(this.max <= inter.max && this.min >= inter.min) { return ((inter.max - this.min) < (this.max - inter.min) ? inter.max -this.min : inter.min - this.max); } else if (this.max >= inter.max && this.min <= inter.min) { return ((inter.max - this.min) < (this.max - inter.min) ? inter.max -this.min : inter.min - this.max); } else { return ((this.max < inter.max ? this.max : inter.max) - (this.min > inter.min ? this.min : inter.min)); } } }
UTF-8
Java
1,027
java
Interval.java
Java
[]
null
[]
package linear; public class Interval { public float min; public float max; public Interval(float min, float max) { this.min = min; this.max = max; } public boolean intersects(Interval inter) { if(this.min > inter.max) { return false; } if (this.max < inter.min) { return false; } return true; } public float getIntersection(Interval inter) { if(this.min >= inter.max || this.max <= inter.min) { return 0; } if(inter.max >= this.max && inter.min >= this.min) { return inter.min - this.max; } else if(this.max <= inter.max && this.min >= inter.min) { return ((inter.max - this.min) < (this.max - inter.min) ? inter.max -this.min : inter.min - this.max); } else if (this.max >= inter.max && this.min <= inter.min) { return ((inter.max - this.min) < (this.max - inter.min) ? inter.max -this.min : inter.min - this.max); } else { return ((this.max < inter.max ? this.max : inter.max) - (this.min > inter.min ? this.min : inter.min)); } } }
1,027
0.600779
0.599805
50
19.540001
27.204565
106
false
false
0
0
0
0
0
0
2.02
false
false
15
9f87498e821944ae58066c96458fb08506367ab8
11,381,663,373,727
260f25087f7f07a8eb2b306c37c56493c75ab318
/nos2jdbc-core/src/main/java/org/seasar/extension/dbcp/impl/XADataSourceImpl.java
c9c763099afb7fcb3011bc8230f0d2092fcc13a2
[ "Apache-2.0" ]
permissive
ns2j/nos2jdbc
https://github.com/ns2j/nos2jdbc
6726c5c81cfd080722b36dd66fced5abf1dda0ba
140d995f95da0771afe297f12bf0ef813eae122d
refs/heads/master
2023-08-28T02:25:28.443000
2023-08-22T06:02:55
2023-08-22T06:02:55
101,460,069
7
0
Apache-2.0
false
2023-05-30T06:05:17
2017-08-26T03:32:09
2021-12-28T23:10:46
2023-05-30T06:05:16
2,668
4
0
0
Java
false
false
/* * Copyright 2004-2015 the Seasar Foundation and the Others. * * 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 org.seasar.extension.dbcp.impl; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import javax.sql.XAConnection; import javax.sql.XADataSource; import org.seasar.framework.log.Logger; import org.seasar.framework.util.DriverManagerUtil; import org.seasar.framework.util.StringUtil; /** * {@link XADataSource}の実装です。 * * @author higa * */ public class XADataSourceImpl implements XADataSource { private Logger logger = Logger.getLogger(XADataSourceImpl.class); private String driverClassName; private String url; private String user; private String password; private Properties properties = new Properties(); private int loginTimeout; /** * {@link XADataSourceImpl}を作成します。 */ public XADataSourceImpl() { } /** * ドライバクラス名を返します。 * * @return ドライバクラス名 */ public String getDriverClassName() { return driverClassName; } /** * ドライバクラス名を設定します。 * * @param driverClassName * ドライバクラス名 */ public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; if (driverClassName != null && driverClassName.length() > 0) { DriverManagerUtil.registerDriver(driverClassName); } } /** * URLを返します。 * * @return URL */ public String getURL() { return url; } /** * URLを設定します。 * * @param url * URL */ public void setURL(String url) { this.url = url; } /** * ユーザを返します。 * * @return ユーザ */ public String getUser() { return user; } /** * ユーザを設定します。 * * @param user * ユーザ */ public void setUser(String user) { this.user = user; } /** * パスワードを返します。 * * @return パスワード */ public String getPassword() { return password; } /** * パスワードを設定します。 * * @param password * パスワード */ public void setPassword(String password) { this.password = password; } /** * プロパティを追加します。 * * @param name * プロパティ名 * @param value * 値 */ public void addProperty(String name, String value) { properties.put(name, value); } public XAConnection getXAConnection() throws SQLException { return getXAConnection(user, password); } public XAConnection getXAConnection(String user, String password) throws SQLException { Properties info = new Properties(); info.putAll(properties); if (StringUtil.isNotEmpty(user)) { info.put("user", user); } if (StringUtil.isNotEmpty(password)) { info.put("password", password); } int currentLoginTimeout = DriverManager.getLoginTimeout(); try { DriverManager.setLoginTimeout(loginTimeout); Connection con = DriverManager.getConnection(url, info); return new XAConnectionImpl(con); } finally { try { DriverManager.setLoginTimeout(currentLoginTimeout); } catch (Exception e) { logger.log("ESSR0017", new Object[] { e.toString() }, e); } } } public PrintWriter getLogWriter() throws SQLException { return null; } public void setLogWriter(final PrintWriter logWriter) throws SQLException { } public int getLoginTimeout() throws SQLException { return loginTimeout; } public void setLoginTimeout(final int loginTimeout) throws SQLException { this.loginTimeout = loginTimeout; } public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("getParentLogger()"); } }
UTF-8
Java
5,195
java
XADataSourceImpl.java
Java
[ { "context": "**\r\n * {@link XADataSource}の実装です。\r\n * \r\n * @author higa\r\n * \r\n */\r\npublic class XADataSourceImpl implemen", "end": 1151, "score": 0.9994772672653198, "start": 1147, "tag": "USERNAME", "value": "higa" }, { "context": "ssword(String password) {\r\n this.password = password;\r\n }\r\n\r\n /**\r\n * プロパティを追加します。\r\n * \r", "end": 3040, "score": 0.9719222784042358, "start": 3032, "tag": "PASSWORD", "value": "password" } ]
null
[]
/* * Copyright 2004-2015 the Seasar Foundation and the Others. * * 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 org.seasar.extension.dbcp.impl; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import javax.sql.XAConnection; import javax.sql.XADataSource; import org.seasar.framework.log.Logger; import org.seasar.framework.util.DriverManagerUtil; import org.seasar.framework.util.StringUtil; /** * {@link XADataSource}の実装です。 * * @author higa * */ public class XADataSourceImpl implements XADataSource { private Logger logger = Logger.getLogger(XADataSourceImpl.class); private String driverClassName; private String url; private String user; private String password; private Properties properties = new Properties(); private int loginTimeout; /** * {@link XADataSourceImpl}を作成します。 */ public XADataSourceImpl() { } /** * ドライバクラス名を返します。 * * @return ドライバクラス名 */ public String getDriverClassName() { return driverClassName; } /** * ドライバクラス名を設定します。 * * @param driverClassName * ドライバクラス名 */ public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; if (driverClassName != null && driverClassName.length() > 0) { DriverManagerUtil.registerDriver(driverClassName); } } /** * URLを返します。 * * @return URL */ public String getURL() { return url; } /** * URLを設定します。 * * @param url * URL */ public void setURL(String url) { this.url = url; } /** * ユーザを返します。 * * @return ユーザ */ public String getUser() { return user; } /** * ユーザを設定します。 * * @param user * ユーザ */ public void setUser(String user) { this.user = user; } /** * パスワードを返します。 * * @return パスワード */ public String getPassword() { return password; } /** * パスワードを設定します。 * * @param password * パスワード */ public void setPassword(String password) { this.password = <PASSWORD>; } /** * プロパティを追加します。 * * @param name * プロパティ名 * @param value * 値 */ public void addProperty(String name, String value) { properties.put(name, value); } public XAConnection getXAConnection() throws SQLException { return getXAConnection(user, password); } public XAConnection getXAConnection(String user, String password) throws SQLException { Properties info = new Properties(); info.putAll(properties); if (StringUtil.isNotEmpty(user)) { info.put("user", user); } if (StringUtil.isNotEmpty(password)) { info.put("password", password); } int currentLoginTimeout = DriverManager.getLoginTimeout(); try { DriverManager.setLoginTimeout(loginTimeout); Connection con = DriverManager.getConnection(url, info); return new XAConnectionImpl(con); } finally { try { DriverManager.setLoginTimeout(currentLoginTimeout); } catch (Exception e) { logger.log("ESSR0017", new Object[] { e.toString() }, e); } } } public PrintWriter getLogWriter() throws SQLException { return null; } public void setLogWriter(final PrintWriter logWriter) throws SQLException { } public int getLoginTimeout() throws SQLException { return loginTimeout; } public void setLoginTimeout(final int loginTimeout) throws SQLException { this.loginTimeout = loginTimeout; } public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("getParentLogger()"); } }
5,197
0.587467
0.583997
199
22.61809
21.553366
79
false
false
0
0
0
0
0
0
0.301508
false
false
15
6a3b88b5bed015389735e0a23b1f84f30fe9d99b
34,419,867,940,627
a3e48d629460ee109a1b4b9656d716915ab799c8
/src/main/java/com/lohas/request/LoginRequest.java
1869027f679726fdacf84eb7295716a3c4411974
[]
no_license
zhizhizhii/LOHAS-in-Actions
https://github.com/zhizhizhii/LOHAS-in-Actions
2c31e4fd344c2a5e7ea87082d8642b8276ad967b
1220e1fe1db3509d78a9c7ebf3ce8a23db9b7445
refs/heads/master
2023-04-24T00:17:51.370000
2021-04-18T04:21:12
2021-04-18T04:21:12
353,682,768
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lohas.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class LoginRequest { @ApiModelProperty(value="wechat服务器返回前端的状态码") private String code; }
UTF-8
Java
231
java
LoginRequest.java
Java
[]
null
[]
package com.lohas.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class LoginRequest { @ApiModelProperty(value="wechat服务器返回前端的状态码") private String code; }
231
0.77512
0.77512
12
16.416666
17.433006
48
false
false
0
0
0
0
0
0
0.333333
false
false
15
28e046963d139be3e826b5e5d9d400e8fb311eef
34,419,867,939,404
eeaf1ba24cc20d724b0c8685ae7e4a0092b3b464
/NewOne/src/main/java/com/sunsharing/newone/demo/DemoProperties.java
69c3c26a623a470c5e5dbb28f3468ac16d1620e9
[]
no_license
413889948/GitStore
https://github.com/413889948/GitStore
d790c956a74e286063e281fa956c7173789a72db
062838afa78ea76d3b683d3aeec0428c4f2f0e26
refs/heads/main
2023-03-19T18:04:46.747000
2021-03-22T01:30:42
2021-03-22T01:30:42
325,761,867
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * @(#) DemoProperties * 版权声明 厦门畅享信息技术有限公司, 版权所有 违者必究 * * <br> Copyright: Copyright (c) 2021 * <br> Company:厦门畅享信息技术有限公司 * <br> @author Administrator * <br> 2021-01-11 16:50:09 */ package com.sunsharing.newone.demo; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * @author Administrator */ @ConfigurationProperties(prefix = "demo") @Data public class DemoProperties { //定义各种属性 //private String prop = "prop"; }
UTF-8
Java
575
java
DemoProperties.java
Java
[ { "context": " 2021\n * <br> Company:厦门畅享信息技术有限公司\n * <br> @author Administrator\n * <br> 2021-01-11 16:50:09\n */\n\npackage com.suns", "end": 158, "score": 0.5830259919166565, "start": 145, "tag": "NAME", "value": "Administrator" }, { "context": "onProperties;\n\nimport lombok.Data;\n\n/**\n * @author Administrator\n */\n@ConfigurationProperties(prefix = \"demo\")\n@Da", "end": 355, "score": 0.5593942999839783, "start": 342, "tag": "NAME", "value": "Administrator" } ]
null
[]
/* * @(#) DemoProperties * 版权声明 厦门畅享信息技术有限公司, 版权所有 违者必究 * * <br> Copyright: Copyright (c) 2021 * <br> Company:厦门畅享信息技术有限公司 * <br> @author Administrator * <br> 2021-01-11 16:50:09 */ package com.sunsharing.newone.demo; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * @author Administrator */ @ConfigurationProperties(prefix = "demo") @Data public class DemoProperties { //定义各种属性 //private String prop = "prop"; }
575
0.698574
0.661914
27
17.185184
18.265606
75
false
false
0
0
0
0
0
0
0.185185
false
false
15
1163dfc24438cfe73a88cc8e2e53c66c6f141465
4,105,988,800,495
5c5c79b003822d386f6ee0444f04527026858cbd
/Denso/src/com/exceptionaire/denso/Activities/ActivityInformation.java
a24330d39335447f6ee116ed5e63de567947c486
[]
no_license
pravinkakde003/DENSO_Updated
https://github.com/pravinkakde003/DENSO_Updated
19290f8ee132f25a31d0f3568e550e22ede1218d
474907faaf5d67bfd4825de51897dc3a0d1feef6
refs/heads/master
2016-08-20T10:49:14.121000
2016-08-03T10:05:52
2016-08-03T10:05:52
64,830,731
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.exceptionaire.denso.Activities; import org.apache.http.util.EncodingUtils; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.exceptionaire.denso.R; import com.exceptionaire.denso.Utils.AppConstant; import com.exceptionaire.denso.Utils.AppSharedPreference; import com.exceptionaire.denso.Utils.AppUtils; import com.exceptionaire.denso.Utils.CustomProgressDialog; @SuppressWarnings("deprecation") public class ActivityInformation extends Activity implements OnClickListener { ImageButton btn_back; WebView mwebview; TextView top_bar_title, footer_bar_title; RelativeLayout footer_bar; private AppSharedPreference preference; private ProgressDialog progressDialog; LinearLayout new_footer_bar; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_amw); progressDialog = new CustomProgressDialog(ActivityInformation.this, "Loading..."); intView(); } private void intView() { // TODO Auto-generated method stub preference = new AppSharedPreference(ActivityInformation.this); btn_back = (ImageButton) findViewById(R.id.btn_back); top_bar_title = (TextView) findViewById(R.id.top_bar_title); footer_bar_title = (TextView) findViewById(R.id.footer_bar_title); // top_bar_title.setText("After Market Web"); top_bar_title.setText(""); footer_bar_title.setText("Switch To Product Marketing Kit"); footer_bar = (RelativeLayout) findViewById(R.id.footer_bar); new_footer_bar=(LinearLayout) findViewById(R.id.new_footer_bar); new_footer_bar.setVisibility(View.GONE); footer_bar.setOnClickListener(this); btn_back.setOnClickListener(this); mwebview = (WebView) findViewById(R.id.mwebview); if (AppUtils.isConnectingToInternet(this)) { progressDialog.show(); mwebview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { // webView.loadUrl(url); // return true; return false; } @Override public void onPageStarted(WebView webView, String url, android.graphics.Bitmap favicon) { super.onPageStarted(webView, url, favicon); Log.d("WebBrowser", "page Started"); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); Log.d("WebBrowser", "error : " + description); } @Override public void onPageFinished(WebView webView, String url) { super.onPageFinished(webView, url); Log.d("WebBrowser", "page finished"); webView.clearCache(true); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } }); mwebview.clearCache(true); mwebview.getSettings().setAppCacheMaxSize(1); if (preference.getIsLoggedIn().equalsIgnoreCase("1")) { String userEmail = preference.getUser_email_ID(); String userPassowrd = preference.getUser_password(); String postData = "uemail=" + userEmail + "&pwd=" + userPassowrd + "&cmdLogin=AMW"; System.out.println("Print parameters:- " + postData); mwebview.postUrl(AppConstant.WEBVIEW_URL, EncodingUtils.getBytes(postData, "utf-8")); System.out.println("WebView Post url Get called"); } else { mwebview.loadUrl(AppConstant.WEBVIEW_URL); System.out.println("WebView Load url Get called"); } } else { AppUtils.internet_alertUser(ActivityInformation.this, "Check Internet Connection"); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.footer_bar: // Intent intent = new Intent(ActivityInformation.this, // ActivityLogin.class); // startActivity(intent); finish(); break; case R.id.btn_back: finish(); break; default: break; } } @Override protected void onStop() { super.onStop(); if (mwebview != null) { mwebview.clearHistory(); mwebview.clearCache(true); mwebview.destroyDrawingCache(); // mwebview.destroy(); CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(ActivityInformation.this); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); } } }
UTF-8
Java
4,811
java
ActivityInformation.java
Java
[ { "context": "tring postData = \"uemail=\" + userEmail + \"&pwd=\" + userPassowrd + \"&cmdLogin=AMW\";\n\t\t\t\tSystem.out.println(\"Print ", "end": 3633, "score": 0.9906113743782043, "start": 3621, "tag": "PASSWORD", "value": "userPassowrd" } ]
null
[]
package com.exceptionaire.denso.Activities; import org.apache.http.util.EncodingUtils; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.exceptionaire.denso.R; import com.exceptionaire.denso.Utils.AppConstant; import com.exceptionaire.denso.Utils.AppSharedPreference; import com.exceptionaire.denso.Utils.AppUtils; import com.exceptionaire.denso.Utils.CustomProgressDialog; @SuppressWarnings("deprecation") public class ActivityInformation extends Activity implements OnClickListener { ImageButton btn_back; WebView mwebview; TextView top_bar_title, footer_bar_title; RelativeLayout footer_bar; private AppSharedPreference preference; private ProgressDialog progressDialog; LinearLayout new_footer_bar; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_amw); progressDialog = new CustomProgressDialog(ActivityInformation.this, "Loading..."); intView(); } private void intView() { // TODO Auto-generated method stub preference = new AppSharedPreference(ActivityInformation.this); btn_back = (ImageButton) findViewById(R.id.btn_back); top_bar_title = (TextView) findViewById(R.id.top_bar_title); footer_bar_title = (TextView) findViewById(R.id.footer_bar_title); // top_bar_title.setText("After Market Web"); top_bar_title.setText(""); footer_bar_title.setText("Switch To Product Marketing Kit"); footer_bar = (RelativeLayout) findViewById(R.id.footer_bar); new_footer_bar=(LinearLayout) findViewById(R.id.new_footer_bar); new_footer_bar.setVisibility(View.GONE); footer_bar.setOnClickListener(this); btn_back.setOnClickListener(this); mwebview = (WebView) findViewById(R.id.mwebview); if (AppUtils.isConnectingToInternet(this)) { progressDialog.show(); mwebview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { // webView.loadUrl(url); // return true; return false; } @Override public void onPageStarted(WebView webView, String url, android.graphics.Bitmap favicon) { super.onPageStarted(webView, url, favicon); Log.d("WebBrowser", "page Started"); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); Log.d("WebBrowser", "error : " + description); } @Override public void onPageFinished(WebView webView, String url) { super.onPageFinished(webView, url); Log.d("WebBrowser", "page finished"); webView.clearCache(true); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } }); mwebview.clearCache(true); mwebview.getSettings().setAppCacheMaxSize(1); if (preference.getIsLoggedIn().equalsIgnoreCase("1")) { String userEmail = preference.getUser_email_ID(); String userPassowrd = preference.getUser_password(); String postData = "uemail=" + userEmail + "&pwd=" + <PASSWORD> + "&cmdLogin=AMW"; System.out.println("Print parameters:- " + postData); mwebview.postUrl(AppConstant.WEBVIEW_URL, EncodingUtils.getBytes(postData, "utf-8")); System.out.println("WebView Post url Get called"); } else { mwebview.loadUrl(AppConstant.WEBVIEW_URL); System.out.println("WebView Load url Get called"); } } else { AppUtils.internet_alertUser(ActivityInformation.this, "Check Internet Connection"); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.footer_bar: // Intent intent = new Intent(ActivityInformation.this, // ActivityLogin.class); // startActivity(intent); finish(); break; case R.id.btn_back: finish(); break; default: break; } } @Override protected void onStop() { super.onStop(); if (mwebview != null) { mwebview.clearHistory(); mwebview.clearCache(true); mwebview.destroyDrawingCache(); // mwebview.destroy(); CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(ActivityInformation.this); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); } } }
4,809
0.731657
0.731033
171
27.134502
24.537346
99
false
false
0
0
0
0
0
0
2.660819
false
false
15
930c7c34bda95ce68e31343dcbf8f945a0f3d4c2
23,029,614,644,690
9b2eb20db7c3522edfa4eafd4bb8606b80a19f7d
/subprojects/language-native/src/main/java/dev/nokee/language/nativebase/internal/DefaultHeaderSearchPath.java
7af665555f7fa2d45c9b1c776c0e81104e40d5da
[]
no_license
eskatos/gradle-native
https://github.com/eskatos/gradle-native
1497aba073b1000de81763443dc0335109a320cb
cf52599ff2b40065905a24c099dc9c6d9d0b5bb9
refs/heads/master
2023-08-01T20:37:26.044000
2020-05-30T03:16:22
2020-05-30T03:16:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.nokee.language.nativebase.internal; import dev.nokee.language.nativebase.HeaderSearchPath; import lombok.Value; import java.io.File; @Value public class DefaultHeaderSearchPath implements HeaderSearchPath { File asFile; }
UTF-8
Java
238
java
DefaultHeaderSearchPath.java
Java
[]
null
[]
package dev.nokee.language.nativebase.internal; import dev.nokee.language.nativebase.HeaderSearchPath; import lombok.Value; import java.io.File; @Value public class DefaultHeaderSearchPath implements HeaderSearchPath { File asFile; }
238
0.827731
0.827731
11
20.636364
22.967459
66
false
false
0
0
0
0
0
0
0.545455
false
false
15
9ada2da0cbb48be93c87175bbbed801c82a4a2b6
24,172,075,968,935
9df16d0fe60aa43c0f8ebb2c3d9ebb340202e8a0
/src/main/java/com/codermy/myspringsecurity/service/RoleUserService.java
90ef4c02b4eea9c6355ca4460a350a6aa3c38eb8
[ "Apache-2.0" ]
permissive
Yinging/my-springsecurity
https://github.com/Yinging/my-springsecurity
69112140736b1c39186a6a9d0bb23574ce82223b
414f9675199cf19781fb1372362beb7c36b43b81
refs/heads/master
2022-11-30T00:26:09.392000
2020-07-31T06:19:37
2020-07-31T06:19:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codermy.myspringsecurity.service; import com.codermy.myspringsecurity.utils.Result; /** * @author codermy * @createTime 2020/7/1 */ public interface RoleUserService { Result getTbRoleUserByUserId(Integer userId); }
UTF-8
Java
236
java
RoleUserService.java
Java
[ { "context": "rmy.myspringsecurity.utils.Result;\n\n/**\n * @author codermy\n * @createTime 2020/7/1\n */\npublic interface Role", "end": 120, "score": 0.9996428489685059, "start": 113, "tag": "USERNAME", "value": "codermy" } ]
null
[]
package com.codermy.myspringsecurity.service; import com.codermy.myspringsecurity.utils.Result; /** * @author codermy * @createTime 2020/7/1 */ public interface RoleUserService { Result getTbRoleUserByUserId(Integer userId); }
236
0.771186
0.745763
11
20.454546
19.662441
49
false
false
0
0
0
0
0
0
0.272727
false
false
15
7d1eddbc0822884404c37ad4a04207490fe09e48
7,911,329,761,654
c360ed8b4ef36b8fdbd7e1296c2e38f098f576f2
/base/txpService/src/main/java/gyqx/txp/db/meta/oracle/OracleDbMetaInfo.java
863f221c9ffc7fba98cf8ecb14345ead9ff6280d
[]
no_license
itcmicwl/SC_SPD
https://github.com/itcmicwl/SC_SPD
fb2004fd34fe9a14771bb1a2f8c28e8c9e209cdb
6e08627e527327f3c56fd4ee164ab89b994e2070
refs/heads/master
2020-04-12T03:04:51.683000
2018-12-18T09:23:31
2018-12-18T09:23:31
162,263,058
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package gyqx.txp.db.meta.oracle; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import gyqx.txp.db.meta.DbMetaInfo; import gyqx.txp.db.meta.FieldMeta; import gyqx.txp.db.meta.TableMeta; public class OracleDbMetaInfo extends DbMetaInfo { public OracleDbMetaInfo(DataSource ds) { JdbcTemplate jt = new JdbcTemplate(ds); List<Map<String,Object>> dtTableSchema = jt.queryForList("select ut.TABLE_NAME,utc.COMMENTS as TABLE_COMMENT from user_tables ut left join user_tab_comments utc on ut.TABLE_NAME = utc.TABLE_NAME order by TABLE_NAME"); for(Map<String,Object> row:dtTableSchema) { TableMeta tm = new TableMeta(); tm.setName(row.get("TABLE_NAME").toString()); tm.setRemark(toString(row.get("TABLE_COMMENT"))); tm.setCamelName(toCamelName(tm.getName(),true)); tables.add(tm); map.put(tm.getName().toLowerCase().replace("_", ""), tm); } Pattern pat1 = Pattern.compile("((.)+)(\\s+(.+))?"); String sqlcols = "select " + " col.TABLE_NAME," + " col.COLUMN_NAME," + " col.COLUMN_ID as pos," + " col.DATA_TYPE as dtype, " + " col.CHAR_LENGTH as len," + " au.CONSTRAINT_TYPE as keyflag, " + " col.DATA_PRECISION as prec, " + " col.DATA_SCALE as scale, " + " col.NULLABLE as nullflag, " + " cc.COMMENTS as remark " + " from user_tab_columns col left join user_col_comments cc " + " on col.TABLE_NAME = cc.TABLE_NAME and col.COLUMN_NAME = cc.COLUMN_NAME " + " left join user_cons_columns cu on col.TABLE_NAME = cu.TABLE_NAME and col.COLUMN_NAME = cu.COLUMN_NAME and cu.position is not null" + " left join user_constraints au on cu.constraint_name = au.CONSTRAINT_NAME" + " where au.CONSTRAINT_TYPE is null or au.CONSTRAINT_TYPE = 'P' order by col.column_id"; List<Map<String,Object>> dtTableFieldSchema = jt.queryForList(sqlcols); for(Map<String,Object> row:dtTableFieldSchema) { TableMeta tm = this.get(row.get("TABLE_NAME").toString()); if(tm == null) continue; FieldMeta fm = new FieldMeta(); fm.setName(row.get("COLUMN_NAME").toString()); fm.setSafeDbFieldName("\"" + fm.getName() + "\""); fm.setTable(tm); fm.setRemark(toString(row.get("remark"))); Object v = row.get("pos"); fm.setOrdinal(Integer.parseInt(v.toString())); if(row.get("len")==null || Integer.parseInt(row.get("len").toString()) ==0) { fm.setLength(row.get("prec") ==null?0: Integer.parseInt(row.get("prec").toString())); }else{ fm.setLength(Integer.parseInt(row.get("len").toString())); } fm.setPk("P".equals(row.get("keyflag"))); fm.setEnableNull("Y".equals(row.get("nullflag"))); if(row.get("scale")!= null && Integer.parseInt(row.get("scale").toString()) != 0) { fm.setScale(Integer.parseInt(row.get("scale").toString())); } fm.setCamelName(toCamelName(fm.getName(),false)); String stype = row.get("dtype").toString(); int lidx = stype.indexOf("("); if(lidx >=0) stype = stype.substring(0,lidx); if(stype.equalsIgnoreCase("number")){ if(fm.getScale() ==0) { if(fm.getLength() <=12) { stype = "int"; }else stype = "bigint"; } } if(stype.equalsIgnoreCase("binary_double")) stype = "double"; if(stype.equalsIgnoreCase("nclob")) stype = "clob"; fm.setType(stype); fm.setJavaType(queryBeanType(fm.getType(),fm.isEnableNull())); String remark = fm.getRemark() == null?"":fm.getRemark() ; Matcher mat1 = pat1.matcher(remark); if(mat1.find()) { fm.setCname(mat1.group(1)); }else{ fm.setCname(fm.getName()); } if(tm == null) System.out.println("tm == null"); tm.append(fm); } } private String toString(Object v) { if(v == null) return null; return v.toString(); } @Override public String queryBeanType(String dbType, boolean enableNull) { return dbTypeToJavaType(dbType,enableNull); } public static String dbTypeToJavaType(String dbType,boolean enableNull) { String result = ""; if(dbType.equalsIgnoreCase("char") || dbType.equalsIgnoreCase("varchar") || dbType.equalsIgnoreCase("varchar2") || dbType.equalsIgnoreCase("nvarchar2") || dbType.equalsIgnoreCase("nchar") || dbType.equalsIgnoreCase("nchar2") || dbType.equalsIgnoreCase("clob")|| dbType.equalsIgnoreCase("nclob")) result = "String"; else if(dbType.equalsIgnoreCase("date") || dbType.equalsIgnoreCase("timestamp")) result = "java.util.Date"; else if(dbType.equalsIgnoreCase("decimal") || dbType.equalsIgnoreCase("number")) result = "java.math.BigDecimal"; else if(dbType.equalsIgnoreCase("int") ) result = enableNull?"Integer":"int"; else if(dbType.equalsIgnoreCase("bigint")) result = enableNull?"Long":"long"; else if(dbType.equalsIgnoreCase("BINARY_double")) result = enableNull?"Double":"double"; else if(dbType.equalsIgnoreCase("date")) result = "Date"; else if(dbType.equalsIgnoreCase("blob") || dbType.equalsIgnoreCase("longblob")) result = "byte[]"; else throw new RuntimeException("unknown type!"); return result; } }
UTF-8
Java
5,210
java
OracleDbMetaInfo.java
Java
[]
null
[]
package gyqx.txp.db.meta.oracle; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import gyqx.txp.db.meta.DbMetaInfo; import gyqx.txp.db.meta.FieldMeta; import gyqx.txp.db.meta.TableMeta; public class OracleDbMetaInfo extends DbMetaInfo { public OracleDbMetaInfo(DataSource ds) { JdbcTemplate jt = new JdbcTemplate(ds); List<Map<String,Object>> dtTableSchema = jt.queryForList("select ut.TABLE_NAME,utc.COMMENTS as TABLE_COMMENT from user_tables ut left join user_tab_comments utc on ut.TABLE_NAME = utc.TABLE_NAME order by TABLE_NAME"); for(Map<String,Object> row:dtTableSchema) { TableMeta tm = new TableMeta(); tm.setName(row.get("TABLE_NAME").toString()); tm.setRemark(toString(row.get("TABLE_COMMENT"))); tm.setCamelName(toCamelName(tm.getName(),true)); tables.add(tm); map.put(tm.getName().toLowerCase().replace("_", ""), tm); } Pattern pat1 = Pattern.compile("((.)+)(\\s+(.+))?"); String sqlcols = "select " + " col.TABLE_NAME," + " col.COLUMN_NAME," + " col.COLUMN_ID as pos," + " col.DATA_TYPE as dtype, " + " col.CHAR_LENGTH as len," + " au.CONSTRAINT_TYPE as keyflag, " + " col.DATA_PRECISION as prec, " + " col.DATA_SCALE as scale, " + " col.NULLABLE as nullflag, " + " cc.COMMENTS as remark " + " from user_tab_columns col left join user_col_comments cc " + " on col.TABLE_NAME = cc.TABLE_NAME and col.COLUMN_NAME = cc.COLUMN_NAME " + " left join user_cons_columns cu on col.TABLE_NAME = cu.TABLE_NAME and col.COLUMN_NAME = cu.COLUMN_NAME and cu.position is not null" + " left join user_constraints au on cu.constraint_name = au.CONSTRAINT_NAME" + " where au.CONSTRAINT_TYPE is null or au.CONSTRAINT_TYPE = 'P' order by col.column_id"; List<Map<String,Object>> dtTableFieldSchema = jt.queryForList(sqlcols); for(Map<String,Object> row:dtTableFieldSchema) { TableMeta tm = this.get(row.get("TABLE_NAME").toString()); if(tm == null) continue; FieldMeta fm = new FieldMeta(); fm.setName(row.get("COLUMN_NAME").toString()); fm.setSafeDbFieldName("\"" + fm.getName() + "\""); fm.setTable(tm); fm.setRemark(toString(row.get("remark"))); Object v = row.get("pos"); fm.setOrdinal(Integer.parseInt(v.toString())); if(row.get("len")==null || Integer.parseInt(row.get("len").toString()) ==0) { fm.setLength(row.get("prec") ==null?0: Integer.parseInt(row.get("prec").toString())); }else{ fm.setLength(Integer.parseInt(row.get("len").toString())); } fm.setPk("P".equals(row.get("keyflag"))); fm.setEnableNull("Y".equals(row.get("nullflag"))); if(row.get("scale")!= null && Integer.parseInt(row.get("scale").toString()) != 0) { fm.setScale(Integer.parseInt(row.get("scale").toString())); } fm.setCamelName(toCamelName(fm.getName(),false)); String stype = row.get("dtype").toString(); int lidx = stype.indexOf("("); if(lidx >=0) stype = stype.substring(0,lidx); if(stype.equalsIgnoreCase("number")){ if(fm.getScale() ==0) { if(fm.getLength() <=12) { stype = "int"; }else stype = "bigint"; } } if(stype.equalsIgnoreCase("binary_double")) stype = "double"; if(stype.equalsIgnoreCase("nclob")) stype = "clob"; fm.setType(stype); fm.setJavaType(queryBeanType(fm.getType(),fm.isEnableNull())); String remark = fm.getRemark() == null?"":fm.getRemark() ; Matcher mat1 = pat1.matcher(remark); if(mat1.find()) { fm.setCname(mat1.group(1)); }else{ fm.setCname(fm.getName()); } if(tm == null) System.out.println("tm == null"); tm.append(fm); } } private String toString(Object v) { if(v == null) return null; return v.toString(); } @Override public String queryBeanType(String dbType, boolean enableNull) { return dbTypeToJavaType(dbType,enableNull); } public static String dbTypeToJavaType(String dbType,boolean enableNull) { String result = ""; if(dbType.equalsIgnoreCase("char") || dbType.equalsIgnoreCase("varchar") || dbType.equalsIgnoreCase("varchar2") || dbType.equalsIgnoreCase("nvarchar2") || dbType.equalsIgnoreCase("nchar") || dbType.equalsIgnoreCase("nchar2") || dbType.equalsIgnoreCase("clob")|| dbType.equalsIgnoreCase("nclob")) result = "String"; else if(dbType.equalsIgnoreCase("date") || dbType.equalsIgnoreCase("timestamp")) result = "java.util.Date"; else if(dbType.equalsIgnoreCase("decimal") || dbType.equalsIgnoreCase("number")) result = "java.math.BigDecimal"; else if(dbType.equalsIgnoreCase("int") ) result = enableNull?"Integer":"int"; else if(dbType.equalsIgnoreCase("bigint")) result = enableNull?"Long":"long"; else if(dbType.equalsIgnoreCase("BINARY_double")) result = enableNull?"Double":"double"; else if(dbType.equalsIgnoreCase("date")) result = "Date"; else if(dbType.equalsIgnoreCase("blob") || dbType.equalsIgnoreCase("longblob")) result = "byte[]"; else throw new RuntimeException("unknown type!"); return result; } }
5,210
0.661228
0.657965
156
32.397434
32.46925
219
false
false
0
0
0
0
0
0
3.24359
false
false
15
397e658d8fb50da7bcc38d927ed527ff1fc8fa09
10,703,058,533,908
7c85fba75fd82e77aac75f672f7a71a4b9b46f71
/NBTrain.java
6b7ea8c7518e8f6da71f62604b94a958557abbc4
[]
no_license
Yunni/605StreamingNaiveBayes
https://github.com/Yunni/605StreamingNaiveBayes
188f7721038f70a5d393a829d55398eb86b66202
6952ab2b88612e4b7c5d03faa752d29684b10014
refs/heads/master
2016-05-24T23:13:54.106000
2015-02-15T03:11:17
2015-02-15T03:11:17
30,816,384
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.util.*; public class NBTrain { public static void main(String[] args) { BufferedReader dataReader = new BufferedReader(new InputStreamReader(System.in)); String line; Trainer trainer = new Trainer(); try { while((line = dataReader.readLine())!=null){ Article article = new Article(line); trainer.train(article); } dataReader.close(); } catch (Exception e) { System.out.println("Failed to run the trainer."); e.printStackTrace(); System.exit(1); } trainer.printCounters(); } } class Trainer{ class Counter { Integer count = 1; public void increment() { ++ count; } @Override public String toString() { return count.toString(); } } private Hashtable<String, Counter> counters = new Hashtable<String, Counter>(); private void incrementCounter(String event){ Counter count = counters.get(event); if (count == null) { counters.put(event, new Counter()); } else { count.increment(); } } public void train(Article article) { for(String y: article.getLabels()) { incrementCounter("Y=" + y); incrementCounter("Y=*"); for(String w: article.getWords()) { incrementCounter("Y=" + y + ",W=" + w); incrementCounter("Y=" + y + ",W=*"); } } } public void printCounters() { for(String event: counters.keySet()) System.out.println(event + "\t" + counters.get(event)); } }
UTF-8
Java
1,406
java
NBTrain.java
Java
[]
null
[]
import java.io.*; import java.util.*; public class NBTrain { public static void main(String[] args) { BufferedReader dataReader = new BufferedReader(new InputStreamReader(System.in)); String line; Trainer trainer = new Trainer(); try { while((line = dataReader.readLine())!=null){ Article article = new Article(line); trainer.train(article); } dataReader.close(); } catch (Exception e) { System.out.println("Failed to run the trainer."); e.printStackTrace(); System.exit(1); } trainer.printCounters(); } } class Trainer{ class Counter { Integer count = 1; public void increment() { ++ count; } @Override public String toString() { return count.toString(); } } private Hashtable<String, Counter> counters = new Hashtable<String, Counter>(); private void incrementCounter(String event){ Counter count = counters.get(event); if (count == null) { counters.put(event, new Counter()); } else { count.increment(); } } public void train(Article article) { for(String y: article.getLabels()) { incrementCounter("Y=" + y); incrementCounter("Y=*"); for(String w: article.getWords()) { incrementCounter("Y=" + y + ",W=" + w); incrementCounter("Y=" + y + ",W=*"); } } } public void printCounters() { for(String event: counters.keySet()) System.out.println(event + "\t" + counters.get(event)); } }
1,406
0.644381
0.642959
63
21.333334
19.478111
83
false
false
0
0
0
0
0
0
2.222222
false
false
15
f77d76b310e2936c1fa3859117e727f162457210
17,729,625,002,383
02973a30f7e707784411766ce0317eb2c716a980
/src/pers/imooc/first/类比较/Animal.java
65ce6df8c9525c1afedee7958ae41a31b89f98f1
[]
no_license
zy108830/java-learn
https://github.com/zy108830/java-learn
18e34913f67aebb2f7e58033fc731853b30dfda5
dc3b3ca24129058bf145d39246d97af8308f519f
refs/heads/master
2021-01-11T08:15:11.729000
2017-09-30T12:09:35
2017-09-30T12:09:35
69,802,448
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package pers.imooc.first.类比较; /** * Created by zqq on 10/4/16. */ public class Animal { public String name="肥妹"; protected int age=23; private char sex='男'; public static void main(String[] args) { System.out.println("动物父类"); } public void printName(){ System.out.println("调用父类方法输出:"+this.name); } }
UTF-8
Java
355
java
Animal.java
Java
[ { "context": "package pers.imooc.first.类比较;\n\n/**\n * Created by zqq on 10/4/16.\n */\npublic class Animal {\n\tpublic Str", "end": 52, "score": 0.9996681809425354, "start": 49, "tag": "USERNAME", "value": "zqq" }, { "context": "6.\n */\npublic class Animal {\n\tpublic String name=\"肥妹\";\n\tprotected int age=23;\n\tprivate char sex='男';\n\n", "end": 114, "score": 0.9943142533302307, "start": 112, "tag": "NAME", "value": "肥妹" } ]
null
[]
package pers.imooc.first.类比较; /** * Created by zqq on 10/4/16. */ public class Animal { public String name="肥妹"; protected int age=23; private char sex='男'; public static void main(String[] args) { System.out.println("动物父类"); } public void printName(){ System.out.println("调用父类方法输出:"+this.name); } }
355
0.665615
0.643533
19
15.684211
14.782823
44
false
false
0
0
0
0
0
0
0.894737
false
false
15
271be62528d2cda3d99e6eb882e174e5d0a5eaa3
2,319,282,364,993
5e5896c0c923d93e7d7b4f249244af68ee5e2e46
/src/main/java/com/example/demo/controller/PetPictureController.java
82005200cd4bbe7c61ebfd8eb73469384c999366
[]
no_license
evvhenii/backend_store
https://github.com/evvhenii/backend_store
164594c95fd2b58f9fde30bd0772b66960c85992
32a97ed06c0991fcb8ea15ac86b2ee0af68f0598
refs/heads/main
2023-02-06T04:48:54.785000
2020-12-28T02:00:09
2020-12-28T02:00:09
323,942,290
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.controller; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.example.demo.config.ConfiguredModelMapper; import com.example.demo.dto.PetPictureRequest; import com.example.demo.dto.PetPictureResponse; import com.example.demo.entity.PetPicture; import com.example.demo.exception.ValidationException; import com.example.demo.service.PetPictureService; import lombok.AllArgsConstructor; import lombok.extern.java.Log; @RestController @AllArgsConstructor @Log public class PetPictureController { private final PetPictureService petPictureService; private final ConfiguredModelMapper modelMapper = new ConfiguredModelMapper(); @GetMapping("pet/{id}/pet_pictures") public List<PetPictureResponse> findPetsPictures(@PathVariable int id) { log.info("Handling find pets all pictures request"); List<PetPicture> petPictures = petPictureService.findByUserId(id); petPictures.stream().forEach(System.out::println); List<PetPictureResponse> petPicturesDto = petPictures .stream() .map(petPicture -> modelMapper.map(petPicture, PetPictureResponse.class)) .collect(Collectors.toList()); return petPicturesDto; } @PostMapping("/pet_pictures") public ResponseEntity<String> create(@RequestBody List<PetPictureRequest> petPictureRequest, Principal principal) throws ValidationException { log.info("Handling creating pets pictures request: "); List<PetPicture> petPictures = petPictureRequest .stream() .map(petPicture -> modelMapper.map(petPicture, PetPicture.class)) .collect(Collectors.toList()); boolean wereCreated = petPictureService.savePictures(petPictures, principal); System.out.println(wereCreated); return wereCreated ? ResponseEntity.ok().build() : ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build(); } }
UTF-8
Java
2,418
java
PetPictureController.java
Java
[]
null
[]
package com.example.demo.controller; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.example.demo.config.ConfiguredModelMapper; import com.example.demo.dto.PetPictureRequest; import com.example.demo.dto.PetPictureResponse; import com.example.demo.entity.PetPicture; import com.example.demo.exception.ValidationException; import com.example.demo.service.PetPictureService; import lombok.AllArgsConstructor; import lombok.extern.java.Log; @RestController @AllArgsConstructor @Log public class PetPictureController { private final PetPictureService petPictureService; private final ConfiguredModelMapper modelMapper = new ConfiguredModelMapper(); @GetMapping("pet/{id}/pet_pictures") public List<PetPictureResponse> findPetsPictures(@PathVariable int id) { log.info("Handling find pets all pictures request"); List<PetPicture> petPictures = petPictureService.findByUserId(id); petPictures.stream().forEach(System.out::println); List<PetPictureResponse> petPicturesDto = petPictures .stream() .map(petPicture -> modelMapper.map(petPicture, PetPictureResponse.class)) .collect(Collectors.toList()); return petPicturesDto; } @PostMapping("/pet_pictures") public ResponseEntity<String> create(@RequestBody List<PetPictureRequest> petPictureRequest, Principal principal) throws ValidationException { log.info("Handling creating pets pictures request: "); List<PetPicture> petPictures = petPictureRequest .stream() .map(petPicture -> modelMapper.map(petPicture, PetPicture.class)) .collect(Collectors.toList()); boolean wereCreated = petPictureService.savePictures(petPictures, principal); System.out.println(wereCreated); return wereCreated ? ResponseEntity.ok().build() : ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build(); } }
2,418
0.750207
0.750207
59
39.983051
28.469723
120
false
false
0
0
0
0
0
0
0.932203
false
false
15
4dcbcd007a9c824ff1e59ebfa652af37a322ddbe
1,382,979,476,345
6e5266d063a617f3260e5ddfcb547d425729a58f
/DataPortalCommon/src/main/java/org/inek/dataportal/common/data/KhComparison/entities/StructureInformation.java
34bd7826c71bb8051d9f1932b3bf9836fe053f99
[]
no_license
youaitbella/DP
https://github.com/youaitbella/DP
2fb8a5f2eab587a328b763da3abc430c065d7154
4db0f7c8c138aa0a80783224a8a07a4fe290059b
refs/heads/master
2022-11-26T21:30:53.874000
2020-03-20T16:00:34
2020-03-20T16:00:34
249,408,096
0
0
null
false
2022-11-16T09:43:26
2020-03-23T11:07:50
2020-03-23T11:17:19
2022-11-16T09:43:22
93,894
0
0
6
Java
false
false
package org.inek.dataportal.common.data.KhComparison.entities; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import org.inek.dataportal.common.data.converter.StructureInformationCategorieConverter; import org.inek.dataportal.common.enums.StructureInformationCategorie; /** * * @author lautenti */ @Entity @Table(name = "StructureInformation", schema = "psy") public class StructureInformation implements Serializable { private static final long serialVersionUID = 1L; // <editor-fold defaultstate="collapsed" desc="Property Id"> @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "siId") private int _id; public int getId() { return _id; } public void setId(int id) { _id = id; } // </editor-fold> //<editor-fold defaultstate="collapsed" desc="BaseInformation"> @ManyToOne @JoinColumn(name = "siStructureBaseInformationId") private StructureBaseInformation _baseInformation; @JsonIgnore public StructureBaseInformation getBaseInformation() { return _baseInformation; } @JsonIgnore public void setBaseInformation(StructureBaseInformation baseInformation) { this._baseInformation = baseInformation; } //Using only for JSON Export public int getBaseInformationId() { return _baseInformation.getId(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Property ValidFrom"> @Column(name = "siValidFrom") @Temporal(TemporalType.TIMESTAMP) private Date _validFrom = new Date(); public Date getValidFrom() { return _validFrom; } public void setValidFrom(Date validFrom) { this._validFrom = validFrom; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Property Content"> @Column(name = "siContent") private String _content = ""; public String getContent() { return _content; } public void setContent(String content) { this._content = content; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Property siComment"> @Column(name = "siComment") private String _comment = ""; public String getComment() { return _comment; } public void setComment(String comment) { this._comment = comment; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Property Structur Categorie Categorie"> @Column(name = "siStructureCategorie") @Convert(converter = StructureInformationCategorieConverter.class) private StructureInformationCategorie _structureCategorie; public StructureInformationCategorie getStructureCategorie() { return _structureCategorie; } public void setStructureCategorie(StructureInformationCategorie structureCategorie) { this._structureCategorie = structureCategorie; } // </editor-fold> @Override public int hashCode() { int hash = 7; hash = 29 * hash + this._id; hash = 29 * hash + Objects.hashCode(this._baseInformation); hash = 29 * hash + Objects.hashCode(this._validFrom); hash = 29 * hash + Objects.hashCode(this._content); hash = 29 * hash + Objects.hashCode(this._comment); hash = 29 * hash + Objects.hashCode(this._structureCategorie); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final StructureInformation other = (StructureInformation) obj; if (this._id != other._id) { return false; } if (!Objects.equals(this._content, other._content)) { return false; } if (!Objects.equals(this._comment, other._comment)) { return false; } if (!Objects.equals(this._baseInformation, other._baseInformation)) { return false; } if (!Objects.equals(this._validFrom, other._validFrom)) { return false; } if (this._structureCategorie != other._structureCategorie) { return false; } return true; } }
UTF-8
Java
4,438
java
StructureInformation.java
Java
[ { "context": ".StructureInformationCategorie;\n\n/**\n *\n * @author lautenti\n */\n@Entity\n@Table(name = \"StructureInformation\",", "end": 410, "score": 0.9994685649871826, "start": 402, "tag": "USERNAME", "value": "lautenti" } ]
null
[]
package org.inek.dataportal.common.data.KhComparison.entities; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import org.inek.dataportal.common.data.converter.StructureInformationCategorieConverter; import org.inek.dataportal.common.enums.StructureInformationCategorie; /** * * @author lautenti */ @Entity @Table(name = "StructureInformation", schema = "psy") public class StructureInformation implements Serializable { private static final long serialVersionUID = 1L; // <editor-fold defaultstate="collapsed" desc="Property Id"> @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "siId") private int _id; public int getId() { return _id; } public void setId(int id) { _id = id; } // </editor-fold> //<editor-fold defaultstate="collapsed" desc="BaseInformation"> @ManyToOne @JoinColumn(name = "siStructureBaseInformationId") private StructureBaseInformation _baseInformation; @JsonIgnore public StructureBaseInformation getBaseInformation() { return _baseInformation; } @JsonIgnore public void setBaseInformation(StructureBaseInformation baseInformation) { this._baseInformation = baseInformation; } //Using only for JSON Export public int getBaseInformationId() { return _baseInformation.getId(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Property ValidFrom"> @Column(name = "siValidFrom") @Temporal(TemporalType.TIMESTAMP) private Date _validFrom = new Date(); public Date getValidFrom() { return _validFrom; } public void setValidFrom(Date validFrom) { this._validFrom = validFrom; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Property Content"> @Column(name = "siContent") private String _content = ""; public String getContent() { return _content; } public void setContent(String content) { this._content = content; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Property siComment"> @Column(name = "siComment") private String _comment = ""; public String getComment() { return _comment; } public void setComment(String comment) { this._comment = comment; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Property Structur Categorie Categorie"> @Column(name = "siStructureCategorie") @Convert(converter = StructureInformationCategorieConverter.class) private StructureInformationCategorie _structureCategorie; public StructureInformationCategorie getStructureCategorie() { return _structureCategorie; } public void setStructureCategorie(StructureInformationCategorie structureCategorie) { this._structureCategorie = structureCategorie; } // </editor-fold> @Override public int hashCode() { int hash = 7; hash = 29 * hash + this._id; hash = 29 * hash + Objects.hashCode(this._baseInformation); hash = 29 * hash + Objects.hashCode(this._validFrom); hash = 29 * hash + Objects.hashCode(this._content); hash = 29 * hash + Objects.hashCode(this._comment); hash = 29 * hash + Objects.hashCode(this._structureCategorie); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final StructureInformation other = (StructureInformation) obj; if (this._id != other._id) { return false; } if (!Objects.equals(this._content, other._content)) { return false; } if (!Objects.equals(this._comment, other._comment)) { return false; } if (!Objects.equals(this._baseInformation, other._baseInformation)) { return false; } if (!Objects.equals(this._validFrom, other._validFrom)) { return false; } if (this._structureCategorie != other._structureCategorie) { return false; } return true; } }
4,438
0.637675
0.63452
158
27.088608
24.053837
90
false
false
0
0
0
0
0
0
0.329114
false
false
15
96e4f8655441724b968de52b03e375b8769087ea
4,629,974,770,283
183538ea3e0eaff1bf594773119117ca4883baa0
/api/src/test/java/com/nextgearcapital/ngen/repositories/crm/LeadActivityTypeRepositoryImplTest.java
404cc34f334075ff76065ce529a1857ac8608d14
[]
no_license
gmadala/NG
https://github.com/gmadala/NG
037ff2415b7338078184f955b4aebacb46763cad
bb0c687d7e064752d26e2c79ba797f5e6bb4dbb4
HEAD
2019-07-10T06:00:55.143000
2017-05-10T18:06:07
2017-05-10T18:06:07
91,038,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nextgearcapital.ngen.repositories.crm; import com.nextgearcapital.ngen.api.NGenTest; import com.nextgearcapital.ngen.model.crm.LeadActivityType; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class LeadActivityTypeRepositoryImplTest extends NGenTest { @Autowired private LeadActivityTypeRepository leadActivityTypeRepository; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testCreateLeadActivityType() { Date effective_date = new Date(); LeadActivityType leadActivityType = new LeadActivityType(); leadActivityType.setId(9999); leadActivityType.setName("TYPE_9999"); leadActivityType.setEffectiveDate(effective_date); leadActivityType.setExpirationDate(null); leadActivityTypeRepository.save(leadActivityType); List<LeadActivityType> leadActivityTypes = leadActivityTypeRepository.findByName("TYPE_9999"); assertEquals(1, leadActivityTypes.size()); leadActivityType = leadActivityTypes.get(0); assertEquals(Integer.valueOf(9999), leadActivityType.getId()); assertEquals(effective_date, leadActivityType.getEffectiveDate()); assertEquals(null, leadActivityType.getExpirationDate()); } @Test public void testUpdateLeadActivityType() { LeadActivityType leadActivityType = leadActivityTypeRepository.findOne(0); leadActivityType.setName("TYPE_Z"); leadActivityTypeRepository.save(leadActivityType); leadActivityType = leadActivityTypeRepository.findOne(0); assertEquals("TYPE_Z", leadActivityType.getName()); } @Test public void testDeleteLeadActivityType() { leadActivityTypeRepository.delete(0); assertNull(leadActivityTypeRepository.findOne(0)); } }
UTF-8
Java
2,178
java
LeadActivityTypeRepositoryImplTest.java
Java
[]
null
[]
package com.nextgearcapital.ngen.repositories.crm; import com.nextgearcapital.ngen.api.NGenTest; import com.nextgearcapital.ngen.model.crm.LeadActivityType; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class LeadActivityTypeRepositoryImplTest extends NGenTest { @Autowired private LeadActivityTypeRepository leadActivityTypeRepository; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testCreateLeadActivityType() { Date effective_date = new Date(); LeadActivityType leadActivityType = new LeadActivityType(); leadActivityType.setId(9999); leadActivityType.setName("TYPE_9999"); leadActivityType.setEffectiveDate(effective_date); leadActivityType.setExpirationDate(null); leadActivityTypeRepository.save(leadActivityType); List<LeadActivityType> leadActivityTypes = leadActivityTypeRepository.findByName("TYPE_9999"); assertEquals(1, leadActivityTypes.size()); leadActivityType = leadActivityTypes.get(0); assertEquals(Integer.valueOf(9999), leadActivityType.getId()); assertEquals(effective_date, leadActivityType.getEffectiveDate()); assertEquals(null, leadActivityType.getExpirationDate()); } @Test public void testUpdateLeadActivityType() { LeadActivityType leadActivityType = leadActivityTypeRepository.findOne(0); leadActivityType.setName("TYPE_Z"); leadActivityTypeRepository.save(leadActivityType); leadActivityType = leadActivityTypeRepository.findOne(0); assertEquals("TYPE_Z", leadActivityType.getName()); } @Test public void testDeleteLeadActivityType() { leadActivityTypeRepository.delete(0); assertNull(leadActivityTypeRepository.findOne(0)); } }
2,178
0.742424
0.732323
66
32
26.643551
102
false
false
0
0
0
0
0
0
0.590909
false
false
15
dcebd95e7ec243a09b27fd4f1e1b49ca757194b9
33,182,917,350,230
590ada3617ce73ab663e614019df2472f179c9e5
/NoFaceLab.java
86db25669ccf5a8f4eb2027d830d6d84e3b8523d
[]
no_license
stacytao/StudioGhibli
https://github.com/stacytao/StudioGhibli
bbe4c2d2986c913ced139ea8e24b758cb6595017
3b18fdfff95d58db937452cd34f33fce47c3a232
refs/heads/master
2020-04-29T09:11:58.930000
2015-10-11T14:52:18
2015-10-11T14:52:18
44,036,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.imageio.*; import java.io.*; import java.awt.*; public class NoFaceLab { public static void main(String...args) { JFrame j = new JFrame(); //JFrame is the window; window is a depricated class NFPanel nf = new NFPanel(); j.setSize(nf.getSize()); j.add(nf); //adds the panel to the frame so that the picture will be drawn //use setContentPane() sometimes works better then just add b/c of greater efficiency. j.setVisible(true); //allows the frame to be shown. j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes the dialog box exit when you click the "x" button. } } class NFPanel extends JPanel implements ActionListener { private Timer time; private int x,y; private int addx,addy; NFPanel() { time = new Timer(15, this); //sets delay to 15 millis and calls the actionPerformed of this class. setSize(2000, 1500); setOpaque(false); setVisible(true); //it's like calling the repaint method. time.start(); addx=addy=1; x=y=1; } public void paintComponent(Graphics g) { drawNoFace(g,x,y); drawSpeech(g); displayName(g,"Studio Ghibli Tribute"); displayName2(g,"Use arrow keys to control White Totoro."); displayName3(g,"Click the bubble to transform Ponyo!"); } public void drawNoFace(Graphics g, int x, int y) { g.setColor(new Color(13,22,24)); Polygon b = new Polygon(); b.addPoint(700+x+ 496, 0+y+ 73); b.addPoint(700+x+ 580, 0+y+ 77); b.addPoint(700+x+ 600, 0+y+ 114); b.addPoint(700+x+ 605, 0+y+ 135); b.addPoint(700+x+ 624, 0+y+ 175); b.addPoint(700+x+ 627, 0+y+ 194); b.addPoint(700+x+ 633, 0+y+ 248); b.addPoint(700+x+ 646, 0+y+ 416); b.addPoint(700+x+ 652, 0+y+ 677); b.addPoint(700+x+ 466, 0+y+ 677); b.addPoint(700+x+ 465, 0+y+ 355); b.addPoint(700+x+ 474, 0+y+ 221); b.addPoint(700+x+ 479, 0+y+ 120); b.addPoint(700+x+ 482, 0+y+ 103); b.addPoint(700+x+ 485, 0+y+ 90); b.addPoint(700+x+ 489, 0+y+ 84); b.addPoint(700+x+ 496, 0+y+ 73); // g.fillPolygon(b); Graphics2D g2= (Graphics2D) g; GradientPaint whateveriwant=new GradientPaint(700+x+461,0+y+30,new Color(13,22,24),700+x+655,1000,new Color(13,22,24,0)); g2.setPaint(whateveriwant); g2.fill(b); g.setColor(new Color(235,235,219)); Polygon a = new Polygon(); a.addPoint(700+x+ 496, 0+y+ 73); a.addPoint(700+x+ 504, 0+y+ 57); a.addPoint(700+x+ 521, 0+y+ 45); a.addPoint(700+x+ 549, 0+y+ 45); a.addPoint(700+x+ 561, 0+y+ 50); a.addPoint(700+x+ 571, 0+y+ 57); a.addPoint(700+x+ 575, 0+y+ 64); a.addPoint(700+x+ 580, 0+y+ 77); a.addPoint(700+x+ 582, 0+y+ 126); a.addPoint(700+x+ 580, 0+y+ 146); a.addPoint(700+x+ 574, 0+y+ 171); a.addPoint(700+x+ 569, 0+y+ 187); a.addPoint(700+x+ 563, 0+y+ 197); a.addPoint(700+x+ 555, 0+y+ 202); a.addPoint(700+x+ 547, 0+y+ 207); a.addPoint(700+x+ 523, 0+y+ 205); a.addPoint(700+x+ 514, 0+y+ 201); a.addPoint(700+x+ 508, 0+y+ 197); a.addPoint(700+x+ 502, 0+y+ 179); a.addPoint(700+x+ 496, y+ 144); a.addPoint(700+x+ 493, 0+y+ 111); a.addPoint(700+x+ 494, 0+y+ 82); a.addPoint(700+x+ 496, 0+y+ 73); g.fillPolygon(a); g.setColor(new Color(13,22,24)); g.fillOval(700+x+ 500, 0+y+ 104,22,9); g.fillOval(700+x+ 554, 0+y+ 104,22,9); g.setColor(new Color(140,128,152)); g.fillOval(700+x+512, 0+y+ 77, 10, 17); g.fillOval(700+x+555, 0+y+ 77, 10, 17); g.drawLine(700+x+506,0+y+117,700+x+517,0+y+117); g.drawLine(700+x+559,0+y+117,700+x+569,0+y+117); Polygon c = new Polygon(); c.addPoint(700+x+ 508, 0+y+ 122); c.addPoint(700+x+ 513, 0+y+ 122); c.addPoint(700+x+ 515, 0+y+ 124); c.addPoint(700+x+ 513, 0+y+ 139); c.addPoint(700+x+ 511, 0+y+ 149); c.addPoint(700+x+ 510, 0+y+ 149); c.addPoint(700+x+ 508, 0+y+ 139); c.addPoint(700+x+ 506, 0+y+ 124); g.fillPolygon(c); Polygon d = new Polygon(); d.addPoint(700+x+ 564, 0+y+ 122); d.addPoint(700+x+ 569, 0+y+ 122); d.addPoint(700+x+ 571, 0+y+ 124); d.addPoint(700+x+ 569, 0+y+ 139); d.addPoint(700+x+ 567, 0+y+ 149); d.addPoint(700+x+ 566, 0+y+ 149); d.addPoint(700+x+ 564, 0+y+ 139); d.addPoint(700+x+ 562, 0+y+ 124); g.fillPolygon(d); g.setColor(Color.BLACK); g.fillArc(700+x+ 514,0+y+ 177,47,6,0,180); g.fillArc(700+x+ 514,0+y+ 174,47,12,0,-180); g.drawLine(700+x+ 530,0+y+ 190,700+x+545,0+y+ 190); } public void drawSpeech (Graphics g) { g.setColor(Color.WHITE); g.fillRect(10,470,390,100); g.setColor(Color.BLACK); g.drawRect(10,470,390,100); } public void displayName(Graphics g, String r) { g.setColor(Color.BLACK); g.setFont(new Font ("Monospaced", Font.BOLD, 20)); g.drawString(r, 30, 500); } public void displayName2(Graphics g, String r) { g.setColor(Color.BLACK); g.setFont(new Font ("Monospaced", Font.BOLD, 15)); g.drawString(r, 30, 530); } public void displayName3(Graphics g, String r) { g.setColor(Color.BLACK); g.setFont(new Font ("Monospaced", Font.BOLD, 15)); g.drawString(r, 30, 550); } public void actionPerformed(ActionEvent e) { if (x >=1800) x=1; x+=addx; if(x==0 || x==200) addx*=-1; repaint(); } }
UTF-8
Java
5,147
java
NoFaceLab.java
Java
[]
null
[]
import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.imageio.*; import java.io.*; import java.awt.*; public class NoFaceLab { public static void main(String...args) { JFrame j = new JFrame(); //JFrame is the window; window is a depricated class NFPanel nf = new NFPanel(); j.setSize(nf.getSize()); j.add(nf); //adds the panel to the frame so that the picture will be drawn //use setContentPane() sometimes works better then just add b/c of greater efficiency. j.setVisible(true); //allows the frame to be shown. j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes the dialog box exit when you click the "x" button. } } class NFPanel extends JPanel implements ActionListener { private Timer time; private int x,y; private int addx,addy; NFPanel() { time = new Timer(15, this); //sets delay to 15 millis and calls the actionPerformed of this class. setSize(2000, 1500); setOpaque(false); setVisible(true); //it's like calling the repaint method. time.start(); addx=addy=1; x=y=1; } public void paintComponent(Graphics g) { drawNoFace(g,x,y); drawSpeech(g); displayName(g,"Studio Ghibli Tribute"); displayName2(g,"Use arrow keys to control White Totoro."); displayName3(g,"Click the bubble to transform Ponyo!"); } public void drawNoFace(Graphics g, int x, int y) { g.setColor(new Color(13,22,24)); Polygon b = new Polygon(); b.addPoint(700+x+ 496, 0+y+ 73); b.addPoint(700+x+ 580, 0+y+ 77); b.addPoint(700+x+ 600, 0+y+ 114); b.addPoint(700+x+ 605, 0+y+ 135); b.addPoint(700+x+ 624, 0+y+ 175); b.addPoint(700+x+ 627, 0+y+ 194); b.addPoint(700+x+ 633, 0+y+ 248); b.addPoint(700+x+ 646, 0+y+ 416); b.addPoint(700+x+ 652, 0+y+ 677); b.addPoint(700+x+ 466, 0+y+ 677); b.addPoint(700+x+ 465, 0+y+ 355); b.addPoint(700+x+ 474, 0+y+ 221); b.addPoint(700+x+ 479, 0+y+ 120); b.addPoint(700+x+ 482, 0+y+ 103); b.addPoint(700+x+ 485, 0+y+ 90); b.addPoint(700+x+ 489, 0+y+ 84); b.addPoint(700+x+ 496, 0+y+ 73); // g.fillPolygon(b); Graphics2D g2= (Graphics2D) g; GradientPaint whateveriwant=new GradientPaint(700+x+461,0+y+30,new Color(13,22,24),700+x+655,1000,new Color(13,22,24,0)); g2.setPaint(whateveriwant); g2.fill(b); g.setColor(new Color(235,235,219)); Polygon a = new Polygon(); a.addPoint(700+x+ 496, 0+y+ 73); a.addPoint(700+x+ 504, 0+y+ 57); a.addPoint(700+x+ 521, 0+y+ 45); a.addPoint(700+x+ 549, 0+y+ 45); a.addPoint(700+x+ 561, 0+y+ 50); a.addPoint(700+x+ 571, 0+y+ 57); a.addPoint(700+x+ 575, 0+y+ 64); a.addPoint(700+x+ 580, 0+y+ 77); a.addPoint(700+x+ 582, 0+y+ 126); a.addPoint(700+x+ 580, 0+y+ 146); a.addPoint(700+x+ 574, 0+y+ 171); a.addPoint(700+x+ 569, 0+y+ 187); a.addPoint(700+x+ 563, 0+y+ 197); a.addPoint(700+x+ 555, 0+y+ 202); a.addPoint(700+x+ 547, 0+y+ 207); a.addPoint(700+x+ 523, 0+y+ 205); a.addPoint(700+x+ 514, 0+y+ 201); a.addPoint(700+x+ 508, 0+y+ 197); a.addPoint(700+x+ 502, 0+y+ 179); a.addPoint(700+x+ 496, y+ 144); a.addPoint(700+x+ 493, 0+y+ 111); a.addPoint(700+x+ 494, 0+y+ 82); a.addPoint(700+x+ 496, 0+y+ 73); g.fillPolygon(a); g.setColor(new Color(13,22,24)); g.fillOval(700+x+ 500, 0+y+ 104,22,9); g.fillOval(700+x+ 554, 0+y+ 104,22,9); g.setColor(new Color(140,128,152)); g.fillOval(700+x+512, 0+y+ 77, 10, 17); g.fillOval(700+x+555, 0+y+ 77, 10, 17); g.drawLine(700+x+506,0+y+117,700+x+517,0+y+117); g.drawLine(700+x+559,0+y+117,700+x+569,0+y+117); Polygon c = new Polygon(); c.addPoint(700+x+ 508, 0+y+ 122); c.addPoint(700+x+ 513, 0+y+ 122); c.addPoint(700+x+ 515, 0+y+ 124); c.addPoint(700+x+ 513, 0+y+ 139); c.addPoint(700+x+ 511, 0+y+ 149); c.addPoint(700+x+ 510, 0+y+ 149); c.addPoint(700+x+ 508, 0+y+ 139); c.addPoint(700+x+ 506, 0+y+ 124); g.fillPolygon(c); Polygon d = new Polygon(); d.addPoint(700+x+ 564, 0+y+ 122); d.addPoint(700+x+ 569, 0+y+ 122); d.addPoint(700+x+ 571, 0+y+ 124); d.addPoint(700+x+ 569, 0+y+ 139); d.addPoint(700+x+ 567, 0+y+ 149); d.addPoint(700+x+ 566, 0+y+ 149); d.addPoint(700+x+ 564, 0+y+ 139); d.addPoint(700+x+ 562, 0+y+ 124); g.fillPolygon(d); g.setColor(Color.BLACK); g.fillArc(700+x+ 514,0+y+ 177,47,6,0,180); g.fillArc(700+x+ 514,0+y+ 174,47,12,0,-180); g.drawLine(700+x+ 530,0+y+ 190,700+x+545,0+y+ 190); } public void drawSpeech (Graphics g) { g.setColor(Color.WHITE); g.fillRect(10,470,390,100); g.setColor(Color.BLACK); g.drawRect(10,470,390,100); } public void displayName(Graphics g, String r) { g.setColor(Color.BLACK); g.setFont(new Font ("Monospaced", Font.BOLD, 20)); g.drawString(r, 30, 500); } public void displayName2(Graphics g, String r) { g.setColor(Color.BLACK); g.setFont(new Font ("Monospaced", Font.BOLD, 15)); g.drawString(r, 30, 530); } public void displayName3(Graphics g, String r) { g.setColor(Color.BLACK); g.setFont(new Font ("Monospaced", Font.BOLD, 15)); g.drawString(r, 30, 550); } public void actionPerformed(ActionEvent e) { if (x >=1800) x=1; x+=addx; if(x==0 || x==200) addx*=-1; repaint(); } }
5,147
0.634156
0.473091
189
26.227512
21.061415
123
false
false
0
0
0
0
0
0
2.851852
false
false
15
46c836d063b358c792100dd857e6bd04a6b6a13d
26,809,185,870,835
a1a473ca964b308a1a1b813ab849bda50aafa1d1
/src/main/java/com/wf/ew/EasyWebApplication.java
e32880f88a3e67068796e1a00af00f0dcd55600a
[]
no_license
cloudgoon/buyivip
https://github.com/cloudgoon/buyivip
e00a0cff84ae98f1187e9fd7654cf3e9d6fda533
1eb01a71f88258c9521e849f2d736073c26db10e
refs/heads/master
2021-03-17T18:19:57.541000
2019-06-14T09:40:08
2019-06-14T09:40:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wf.ew; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.wf.jwtp.configuration.EnableJwtPermission; @EnableJwtPermission @SpringBootApplication public class EasyWebApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(EasyWebApplication.class, args); } /** * 若需要打成 war 包,则需要写一个类继承 {@link SpringBootServletInitializer} 并重写 {@link SpringBootServletInitializer#configure(SpringApplicationBuilder)} */ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(EasyWebApplication.class); } }
UTF-8
Java
944
java
EasyWebApplication.java
Java
[]
null
[]
package com.wf.ew; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.wf.jwtp.configuration.EnableJwtPermission; @EnableJwtPermission @SpringBootApplication public class EasyWebApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(EasyWebApplication.class, args); } /** * 若需要打成 war 包,则需要写一个类继承 {@link SpringBootServletInitializer} 并重写 {@link SpringBootServletInitializer#configure(SpringApplicationBuilder)} */ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(EasyWebApplication.class); } }
944
0.806843
0.806843
24
36.75
36.59491
142
false
false
0
0
0
0
0
0
0.375
false
false
15
b947685c0a5323870795d1a995c0c10f0f997fc4
27,693,949,194,601
5f5b52e19d6911a3139616aeec21d2fdad5220c4
/src/main/java/com/liornegri/unbound/ms/service/crypto/RSACryptoService.java
e4c448e77423c54645dd6e52f6790425101ee745
[ "Apache-2.0" ]
permissive
lior-negri/unbound-crypto-ms
https://github.com/lior-negri/unbound-crypto-ms
7798ba4a6abe9cf0c19f27a22632b1795138d022
354ffb5809daece14bad8334fa3d5de41dec93bb
refs/heads/main
2023-01-23T02:59:30.505000
2020-11-28T18:44:49
2020-11-28T18:44:49
316,782,768
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liornegri.unbound.ms.service.crypto; import com.liornegri.unbound.ms.data.model.crypto.exception.CryptoException; import com.liornegri.unbound.ms.util.crypto.CryptoUtil; import com.liornegri.unbound.ms.data.dao.crypto.CryptoDataAccess; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import java.security.KeyPair; import java.util.*; @Service public class RSACryptoService implements CryptoService { private final CryptoDataAccess<KeyPair> rsaDataAccess; private final CryptoUtil<KeyPair> rsaCryptoUtil; @Autowired public RSACryptoService(final CryptoDataAccess<KeyPair> cryptoDataAccess, final CryptoUtil<KeyPair> cryptoUtil) { rsaDataAccess = cryptoDataAccess; rsaCryptoUtil = cryptoUtil; } @Override public String generateKey() { KeyPair kp = rsaCryptoUtil.generateKey(); return rsaDataAccess.addKey(kp); } @Override public void deleteKey(final String id) { if (!rsaDataAccess.contains(id)) { throw new HttpClientErrorException(HttpStatus.NOT_FOUND, String.format("Could not find KeyPair for id: %s", id)); } rsaDataAccess.removeKey(id); } @Override public List<String> getIds() { return rsaDataAccess.getIds(); } @Override public byte[] sign(final String id, final byte[] data) { KeyPair keyPair = getKeyPair(id); return rsaCryptoUtil.sign(keyPair, data); } @Override public boolean verify(final String id, final byte[] data, final String signature) { KeyPair keyPair = getKeyPair(id); return rsaCryptoUtil.verify(keyPair, data, signature); } private KeyPair getKeyPair(final String id) { KeyPair keyPair = rsaDataAccess.getKey(id); if (keyPair == null) { throw new HttpClientErrorException(HttpStatus.NOT_FOUND, String.format("Could not find KeyPair for id: %s", id)); } return keyPair; } }
UTF-8
Java
2,222
java
RSACryptoService.java
Java
[]
null
[]
package com.liornegri.unbound.ms.service.crypto; import com.liornegri.unbound.ms.data.model.crypto.exception.CryptoException; import com.liornegri.unbound.ms.util.crypto.CryptoUtil; import com.liornegri.unbound.ms.data.dao.crypto.CryptoDataAccess; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import java.security.KeyPair; import java.util.*; @Service public class RSACryptoService implements CryptoService { private final CryptoDataAccess<KeyPair> rsaDataAccess; private final CryptoUtil<KeyPair> rsaCryptoUtil; @Autowired public RSACryptoService(final CryptoDataAccess<KeyPair> cryptoDataAccess, final CryptoUtil<KeyPair> cryptoUtil) { rsaDataAccess = cryptoDataAccess; rsaCryptoUtil = cryptoUtil; } @Override public String generateKey() { KeyPair kp = rsaCryptoUtil.generateKey(); return rsaDataAccess.addKey(kp); } @Override public void deleteKey(final String id) { if (!rsaDataAccess.contains(id)) { throw new HttpClientErrorException(HttpStatus.NOT_FOUND, String.format("Could not find KeyPair for id: %s", id)); } rsaDataAccess.removeKey(id); } @Override public List<String> getIds() { return rsaDataAccess.getIds(); } @Override public byte[] sign(final String id, final byte[] data) { KeyPair keyPair = getKeyPair(id); return rsaCryptoUtil.sign(keyPair, data); } @Override public boolean verify(final String id, final byte[] data, final String signature) { KeyPair keyPair = getKeyPair(id); return rsaCryptoUtil.verify(keyPair, data, signature); } private KeyPair getKeyPair(final String id) { KeyPair keyPair = rsaDataAccess.getKey(id); if (keyPair == null) { throw new HttpClientErrorException(HttpStatus.NOT_FOUND, String.format("Could not find KeyPair for id: %s", id)); } return keyPair; } }
2,222
0.679118
0.679118
65
32.184616
29.376543
125
false
false
0
0
0
0
0
0
0.569231
false
false
15
5d42be565480878ed52a71c1d4544fef7522a430
25,486,335,940,932
c66ba89b7aef568631bbda940aaa1b3fde602f58
/dynamicProgramming/dynasixmicProgramming.java
89ba06310b24cd07a21807d405b1d32c05dd04cc
[]
no_license
deepwaterooo/MyAlgorithms
https://github.com/deepwaterooo/MyAlgorithms
abba947e428c7a69796846a37ede3bc0a589d296
b9d40e8a2222905ecc10dccebb7f86624023d2d8
refs/heads/master
2022-08-23T09:56:15.685000
2022-08-14T03:50:42
2022-08-14T03:50:42
28,279,600
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
mport com.TreeNode; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.*; import java.util.stream.*; import java.util.stream.Collectors; import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptException; import static java.util.stream.Collectors.toMap; public class dynasixmicProgramming { public static class Solution { // public int combinationSum4(int[] nums, int target) { // int n = nums.length; // if (n == 1 && target < nums[0] || nums[0] != 0 && target % nums[0] != 0) return 0; // // int [] dp = new int [n]; // // int [] dp = new int [target + 1]; // // dp[nums[0]] = target % nums[0] == 0 ? 1 : 0; // // for (int i = 1; i < n; i++) { // } // private void helper(int [] arr, int i, int j) { // if (i == j) return dp[i][j] = arr[i]; // if (j == i+1) return Math.abs(arr[i] - arr[j]); // if (dp[i][j] > 0) return dp[i][j]; // } // 还木有认出这个题到底是在考什么 // int [][] dp; // int n; // public int lastStoneWeightII(int[] stones) { // n = stones.length; // if (n == 1) return stones[0]; // if (n == 2) return Math.abs(stones[0] - stones[1]); // dp = new int [n][n]; // return dfs(stones, 0, n-1); // } // public int findMaxForm(String[] strs, int m, int n) { // int [][] dp = new int [m+1][n+1]; // dp[0][0] = 0; // for (String s : strs) { // int one = 0, zoo = 0; // for (int i = 0; i < s.length(); i++) { // if (s.charAt(i) == '0') ++ zoo; // else ++one; // } // for (int i = m; i >= zoo; i--) // for (int j = n; j >= one; j--) // dp[i][j] = Math.max(dp[i][j], dp[i-zoo][j-one] + 1); // } // return dp[m][n]; // } // public String optimalDivision(int[] nums) { // int n = nums.length; // if (n == 0) return ""; // String res = String.valueOf(nums[0]); // if (n == 1) return res; // if (n == 2) return res + "/" + nums[1]; // res += "/(" + nums[1]; // for (int i = 2; i < n; i++) // res += "/" + nums[i]; // return res + ")"; // } // private int dfs(int [] arr, int target) { // if (dp[target] != -1) return dp[target]; // int res = 0; // for (int i = 0; i < n; i++) { // if (target >= arr[i]) // res += dfs(arr, target - arr[i]); // } // return dp[target] = res; // } // int [] dp; // int n; // public int combinationSum4(int[] nums, int target) { // n = nums.length; // dp = new int [target +1 ]; // Arrays.fill(dp, -1); // dp [0] = 1; // return dfs(nums, target); // } // public int combinationSum4(int[] nums, int target) { // int n = nums.length; // int [] dp = new int [target +1 ]; // dp [0] = 1; // for (int i = 1; i <= target; i++) { // for (int j = 0; j < n; j++) { // if (i - nums[j] >= 0) // dp[i] += dp[i-nums[j]]; // } // } // return dp[target]; // } // // 找出数组中等于target的最小非重叠区间的长度,用dp[i]表示当前i以及i之前的满足条件的最小区间长度,状态更新规则为 // // dp[i]=min(dp[i-1],i-j+1) if sum[j,i]=target // // 答案更新规则 // // res=min(res,dp[j−1]+i−j+1) // public int minSumOfLengths(int[] arr, int target) { // int n = arr.length; // int [] dp = new int [n]; // Arrays.fill(dp, Integer.MAX_VALUE); // int cur = 0, s = 0; // int res = Integer.MAX_VALUE, minLen = Integer.MAX_VALUE; // for (int i = 0; i < n; i++) { // cur += arr[i]; // while (cur > target) { // cur -= arr[s]; // s += 1; // } // if (cur == target) { // int curLen = i - s + 1; // if (s > 0 && dp[s-1] != Integer.MAX_VALUE) // res = Math.min(res, curLen + dp[s-1]); // minLen = Math.min(minLen, curLen); // } // dp[i] = minLen; // } // return res == Integer.MAX_VALUE ? -1 : res; // } // class Node { // private int val; // private int back; // public Node(int val, int back) { // this.val = val; // this.back = back; // 记住了每一跳是否是往反跳 // } // } // // 给出坐标 x ,可以往前跳的步长 a,往后跳的步长 b。要求输出能跳回家的最少跳跃次数。 // // 求最少跳跃次数,思路用 BFS 求解,最先到达坐标 x 的方案即是最少跳跃次数。 // // 对forbidden 的处理是把记忆化数组里面把他们标记为 true。 // // 禁止连续往后跳 2 次的限制,要求我们在 BFS 入队的时候再记录一下跳跃方向,每次往后跳的时候判断前一跳是否是往后跳,如果是往后跳,此次就不能往后跳了。 // public int minimumJumps(int[] forbidden, int a, int b, int x) { // final int MAX = 100050; // boolean [] take = new boolean [MAX]; // for (int fob: forbidden) // 标记不能跳的点 // take[fob] = true; // int[][] dist = new int[MAX][2]; // 用于记录往前跳与往后跳的次数 // for(int i = 0; i < MAX; i++) // 进行初始化 // Arrays.fill(dist[i], -1); // dist[0][0] = 0; // Queue<Node> q = new LinkedList<>(); // 创造队列 // q.offer(new Node(0, 0)); // Node cur = null; // while (!q.isEmpty()) { // bfs 思路 // cur = q.poll(); // if(cur.val + a < MAX && !take[cur.val + a] && dist[cur.val + a][0] == -1){ // 往前跳 // dist[cur.val + a][0] = dist[cur.val][cur.back] + 1; // q.offer(new Node(cur.val + a, 0)); // forward: 0 // } // if(cur.back != 1 && cur.val - b >= 0 && !take[cur.val - b] && dist[cur.val - b][1] == -1){ // 往后跳 // dist[cur.val - b][1] = dist[cur.val][cur.back] + 1; // q.offer(new Node(cur.val - b, 1)); // backward: 1 // } // } // int ans = Math.min((dist[x][0] == -1 ? Integer.MAX_VALUE : dist[x][0]), (dist[x][1] == -1 ? Integer.MAX_VALUE : dist[x][1])); // return ans == Integer.MAX_VALUE ? -1 : ans; // } // private int dfs(int i, int j) { // } // // To make the computation of each state in constant time, // // we could add another flag to the state that // // indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). // // use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. // int [][][] dp; // public int numberOfSets(int n, int k) { // dp = new int [n][k+1][2]; // } // private int getMinCnt(String s) { // int n = s.length(); // if (n == 1) return 0; // if (n == 2) return s.charAt(0) == s.charAt(1) ? 0 : 1; // int i = 0, j = n-1, cnt = 0; // while (i <= j) { // if (s.charAt(i) != s.charAt(j)) ++ cnt; // ++i; // --j; // } // return cnt; // } // private int dfs(String s, int k, int idx, int v) { // if (idx >= n) return 0; // if (dp[idx][v] <= n) return dp[idx][v]; // if (v == 1) // return dp[idx][v] = m.get(s.substring(idx)); // if (idx == n-v) // return dp[idx][v] = 0; // int min = n+1; // for (int i = idx; i <= n-v; i++) // min = Math.min(min, m.get(s.substring(idx, i+1)) + dfs(s, k, i+1, v-1)); // return dp[idx][v] = min; // } // Map<String, Integer> m = new HashMap<>(); // int [][] dp; // int n; // public int palindromePartition(String s, int k) { // n = s.length(); // if (n == 1 || n == k) return 0; // for (int i = 0; i < n; i++) // for (int j = i; j < n; j++) // m.put(s.substring(i, j+1), getMinCnt(s.substring(i, j+1))); // dp = new int [n][k+1]; // for (int i = 0; i < n; i++) // Arrays.fill(dp[i], n+1); // return dfs(s, k, 0, k); // } // public boolean checkPartitioning(String s) { // int n = s.length(); // if (n == 3) return true; // boolean [][] p = new boolean[n][n]; // for (int i = n-1; i >= 0; i--) // for (int j = i; j < n; j++) // if (s.charAt(i) == s.charAt(j) && (j-i < 2 || p[i+1][j-1])) // p[i][j] = true; // for (int i = 0; i < n-2; i++) { // for (int j = i+1; j < n-1; j++) { // if (p[0][i] && p[i+1][j] && p[j+1][n-1]) return true; // } // } // return false; // } // public int longestPalindrome(String s, String t) { // 这个题目没有懂,需要再好好看一下 // int m = s.length(); // int n = t.length(); // int mn = m + n; // String st = s + t; // int [][] dp = new int [mn][mn]; // for (int i = 0; i < mn; i++) // dp[i][i] = 1; // for (int l = 2; l <= mn; l++) { // for (int i = 0, j = i+l-1; j < mn; i++,j++) { // // if (st.charAt(i) == st.charAt(j)) // dp[i][j] = dp[i+1][j-1] + 2; // else dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]); // } // } // int ans = 0; // for (int i = 0; i < m; i++) { // for (int j = 0; j < n; j++) { // if (s.charAt(i) == t.charAt(j)) // ans = Math.max(ans, dp[i][m+j]); // // } // } // return ans; // } // private List<Integer> findCommonElements(int [] a, int [] b) { // Set<Integer> sa = new HashSet<>(); // Set<Integer> sb = new HashSet<>(); // for (int v : a) // sa.add(v); // for (int v : b) // sb.add(v); // sa.retainAll(sb); // List<Integer> l = new ArrayList<>(); // for (Integer v : sa) // l.add(v); // Collections.sort(l); // return l; // } // private int binarySearch(int [] arr, int v, int l, int r) { // if (l == r) return arr[l] == v ? l : -1; // if (l == r-1) return arr[l] == v ? l : (arr[r] == v ? r : -1); // int m = l + (r-l)/2; // if (arr[m] == v) return m; // if (arr[m] < v) return binarySearch(arr, v, m+1, r); // return binarySearch(arr, v, l, m-1); // } // public int maxSum(int[] a, int[] b) { // int m = a.length; // int n = b.length; // int mod = 1_000_000_007; // if (a[m-1] <= b[0] || a[0] >= b[n-1]) // return (int)((a[m-1] <= b[0] ? Arrays.stream(b).sum() : Arrays.stream(a).sum()) % mod); // long [] pa = new long [m+1]; // long [] pb = new long [n+1]; // for (int i = 1; i <= m; i++) // pa[i] = pa[i-1] + a[i-1]; // for (int i = 1; i <= n; i++) // pb[i] = pb[i-1] + b[i-1]; // List<Integer> s = findCommonElements(a, b); // if (s.size() == 0) return (int)(Math.max(pa[m], pb[n]) % mod); // long res = 0; // int i = 0, j = 0, pi = 0, pj = 0, v = 0; // for (int x = 0; x < s.size(); x++) { // v = s.get(x); // i = binarySearch(a, v, pi, m-1); // j = binarySearch(b, v, pj, n-1); // res = (res + Math.max(pa[i+1]-(pi == 0 ? 0 : pa[pi]), pb[j+1]-(pj == 0 ? 0 : pb[pj]))) % mod; // pi = i+1; // pj = j + 1; // } // if (i != pi || j != pj) { // if (i != pi && j != pj) // res = (res + Math.max(pa[m]-pa[pi], pb[n]-pb[pj])) % mod; // else if (i != pi) // res = (res + pa[m]-pa[pi]) % mod; // else res = (res + pb[n]-pb[pj]) % mod; // } // return (int)res; // } // public int[] pathsWithMaxScore(List<String> board) { // int m = board.size(); // int n = board.get(0).length(); // int [][] max = new int[m][n]; // long [][] cnt = new long [m][n]; // int mod = 1_000_000_007; // cnt[m-1][n-1] = 1; // for (int i = m-2; i >= 0; i--) // if (board.get(i).charAt(n-1) != 'X') { // max[i][n-1] = max[i+1][n-1] + board.get(i).charAt(n-1)-'0'; // cnt[i][n-1] = cnt[i+1][n-1]; // } else { // max[i][n-1] = Integer.MIN_VALUE; // cnt[i][n-1] = Integer.MIN_VALUE; // } // for (int j = n-2; j >= 0; j--) // if (board.get(m-1).charAt(j) != 'X') { // max[m-1][j] = max[m-1][j+1] + board.get(m-1).charAt(j)-'0'; // cnt[m-1][j] = cnt[m-1][j+1]; // } else { // max[m-1][j] = Integer.MIN_VALUE; // cnt[m-1][j] = Integer.MIN_VALUE; // } // int tmp = 0; // for (int i = m-2; i >= 0; i--) { // for (int j = n-2; j >= 0; j--) { // if (board.get(i).charAt(j) == 'X') { // max[i][j] = Integer.MIN_VALUE; // cnt[i][j] = Integer.MIN_VALUE; // continue; // } // tmp = Math.max(max[i+1][j], max[i][j+1]); // tmp = Math.max(tmp, max[i+1][j+1]) + (board.get(i).charAt(j) == 'E' ? 0 : board.get(i).charAt(j) - '0'); // max[i][j]= tmp; // if (tmp == max[i+1][j+1] + (board.get(i).charAt(j) == 'E' ? 0 : board.get(i).charAt(j) - '0')) // cnt[i][j] = cnt[i+1][j+1]; // else { // if (max[i+1][j] == max[i][j+1]) cnt[i][j] = cnt[i+1][j] + cnt[i][j+1]; // else cnt[i][j] = (tmp == max[i+1][j] + (board.get(i).charAt(j) == 'E' ? 0 : board.get(i).charAt(j) - '0') ? cnt[i+1][j] : cnt[i][j+1]); // } // cnt[i][j] %= mod; // } // } // return new int[] {max[0][0] > 0 ? max[0][0] : 0, (int)cnt[0][0] > 0 ? (int)cnt[0][0] : 0}; // } // public int firstDayBeenInAllRooms(int[] nextVisit) { // int n = nextVisit.length; // int [] dp = new int [n]; // int cnt = 0; // dp[0] = 0; // for (int i = 0; i < n; i++) { // } // } // private boolean dfs(char [] s, int i, int cnt) { // cnt of left ( // if (cnt < 0) return false; // if (i == s.length) return cnt == 0; // if (dp[i][cnt] != null) return dp[i][cnt]; // char c = s[i]; // boolean res = false; // if (c == '(') res = dfs(s, i+1, cnt+1); // else if (c == ')') res = dfs(s, i+1, cnt-1); // else res = dfs(s, i+1, cnt) || dfs(s, i+1, cnt+1) || dfs(s, i+1, cnt-1); // return dp[i][cnt] = res; // } // Boolean [][] dp; // int n; // public boolean checkValidString(String s) { // n = s.length(); // dp = new Boolean [n][n]; // return dfs(s.toCharArray(), 0, 0); // } // public int[] maxSumOfThreeSubarrays(int[] nums, int k) { // int n = nums.length; // int [] pre = new int [n+1]; // for (int i = 1; i <= n; i++) // pre[i] = pre[i-1] + nums[i-1]; // // left[i]表示在区间[0, i]范围内长度为k且和最大的子数组的起始位置 // // right[i]表示在区间[i, n - 1]范围内长度为k且和最大的子数组的起始位置 // int [] left = new int [n]; // int [] right = new int [n]; // int [] res = new int [3]; // Arrays.fill(right, n-k); // for (int i = k, total = pre[k]-pre[0]; i < n; i++) { // if (pre[i+1] - pre[i+1-k] > total) { // left[i]= i+1-k; // total = pre[i+1] - pre[i+1-k]; // } else left[i] = left[i-1]; // } // for (int i = n-1-k, total = pre[n]-pre[n-k]; i >= 0; i--) { // if (pre[i+k] - pre[i] >= total) { // right[i] = i; // total = pre[i+k] - pre[i]; // } else right[i] = right[i+1]; // } // int max = Integer.MIN_VALUE; // for (int i = k; i <= n-2*k; i++) { // int l = left[i-1]; // int r = right[i+k]; // int total = (pre[i+k]-pre[i]) + (pre[k+l]-pre[l]) + (pre[r+k] - pre[r]); // if (max < total) { // max = total; // res = new int [] {l, i, r}; // } // } // return res; // } // public int maxDotProduct(int[] a, int[] b) { // int m = a.length; // int n = b.length; // int [][] dp = new int [m][n]; // dp[m-1][n-1] = a[m-1]*b[n-1]; // for (int i = m-2; i >= 0; i--) // dp[i][n-1] = Math.max(a[i] * b[n-1], dp[i+1][n-1]); // for (int j = n-2; j >= 0; j--) // dp[m-1][j] = Math.max(a[m-1]*b[j], dp[m-1][j+1]); // int cur = 0, tmp = 0; // int right = 0, down = 0, dr = 0; // for (int i = m-2; i >= 0; i--) { // for (int j = n-2; j >= 0; j--) { // cur = a[i] * b[j]; // tmp = Math.max(dp[i+1][j], dp[i][j+1]); // tmp = Math.max(tmp, cur); // if (dp[i+1][j+1] > 0 && cur > 0) tmp = Math.max(tmp, dp[i+1][j+1] + cur); // dp[i][j] = tmp; // } // } // return dp[0][0]; // } // private int dfs(int steps, int n, int i) { // if (steps < i) return 0; // 裁枝: 如果剩余步数小于index,说明已无法返回起点 // if (i < 0 || i >= n) return 0; // if (steps == 0 && i == 0) return 1; // if (dp[steps][i] > 0) return dp[steps][i]; // long res = dfs(steps-1, n, i-1) % mod; // res = (res + dfs(steps-1, n, i+1)) % mod; // res = (res + dfs(steps-1, n, i)) % mod; // return dp[steps][i] = (int)res; // } // int mod = 1_000_000_007; // // memo[i][j]代表,还剩下i步时,从下标j返回下标0的方案数 // // 由于能够到达的最远index一定不能超过步数的一半, // // j的最大值为steps/2+1 // int [][] dp; // public int numWays(int steps, int arrLen) { // dp = new int [steps + 1][steps/2 + 1]; // return dfs(steps, arrLen, 0); // } // public int numWays(int steps, int arrLen) { // int maxPos = Math.min(steps/2+1, arrLen); // long[][] dp = new long[steps + 1][maxPos + 1]; // int mod = 1_000_000_007; // dp[1][0] = 1; // dp[1][1] = 1; // for (int i = 2; i <= steps; i++) // for (int j = 0; j < maxPos; j++) // dp[i][j] = (dp[i-1][j] + dp[i-1][j+1] + (j > 0 ? dp[i-1][j-1] : 0)) % mod; // return (int)(dp[steps][0] % mod); // } // public int maxSumSubmatrix(int[][] mat, int k) { // int m = mat.length; // int n = mat[0].length; // if (m == 1 && n == 1) return mat[0][0]; // int [][] pre = new int [m][n]; // int res = Integer.MIN_VALUE; // for (int i = 0; i < m; i++) { // for (int j = 0; j < n; j++) { // int t = mat[i][j]; // if (i > 0) t += pre[i-1][j]; // if (j > 0) t += pre[i][j-1]; // if (i > 0 && j > 0) t -= pre[i-1][j-1]; // pre[i][j] = t; // for (int r = 0; r <= i; r++) { // for (int c = 0; c <= j; c++) { // int d = pre[i][j]; // if (r > 0) d -= pre[r-1][j]; // if (c > 0) d -= pre[i][c-1]; // if (r > 0 && c > 0) d += pre[r-1][c-1]; // if (d <= k) res = Math.max(res, d); // } // } // } // } // return res; // } // // 把二维数组按行或列拆成多个一维数组,然后利用一维数组的累加和来找符合要求的数字, // // 这里用了 lower_bound 来加快的搜索速度,也可以使用二分搜索法来替代。 // public int maxSumSubmatrix(int[][] mat, int target) { // int row = mat.length; // int col = mat[0].length; // int res = Integer.MIN_VALUE; // boolean key = col > row ? false : true; // int m = Math.min(row, col); // int n = Math.max(row, col); // int [] pre = new int [n]; // TreeSet<Integer> ts = new TreeSet<>(); //用来保存当前高度下,长度为从0开始到k位置的矩形的结果。理解set的含义是解决此题的关键。 // Integer tmp = 0; // for (int i = 0; i < m; i++) { // 找从第i行开始一直到第0行这i+1行的可能组成的矩形长度 // Arrays.fill(pre, 0); // for (int j = i; j >= 0; j--) { // ts.clear(); // ts.add(0); // int curSum = 0; // for (int k = 0; k < n; k++) { // if (key) // pre[k] += mat[k][j]; // else pre[k] += mat[j][k]; // curSum += pre[k]; // // * 因为要满足 (sum-set中的元素)<=target, // // * 而且sum-set中的元素的值要尽可能的大, // // * 所以也就是再求小于等于sum-target中满足条件的元素的最小的一个 // // * 正好TreeSet中提供了这个方法ceil(),可以很方便的找出这个元素 // tmp = ts.ceiling(curSum - target); // if (tmp != null) res = Math.max(res, curSum - tmp); // ts.add(curSum); // } // } // } // return res; // } // int [][] dp; // public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { // dp = new int [m][n]; // } // public String largestMultipleOfThree(int[] digits) { // int n = digits.length; // Arrays.sort(digits); // int [] dg = IntStream.rangeClosed(0, n-1).map(z->digits[n-1-z]).toArray(); // System.out.println("dg.length: " + dg.length); // for (int z = 0; z < dg.length; ++z) // System.out.print(dg[z] + ", "); // System.out.println(""); // // find the longest subsequece of sum % 3 == 0 // return ""; // } // // DP + BitSet : 这里面有个小问题需要挑出来 // // 使用一个DP数组存下当前行和之前行每行选一个数可能构成的和, // // 在本题中,可以使用BitSet(简介)来存储之前行可以组成的和(由于所有数的最大值为70,而行数最大也为70,故BitSet最大的位数即为4900)。 // // 对于当前行,遍历BitSet已经set过的位(即代表之前行可能组成的和),然后加上当前数,set新的和 // // 最后遍历BitSet,求出当前位与target的最小值 // public int minimizeTheDifference(int[][] mat, int target) { // int m = mat.length; // int n = mat[0].length; // BitSet sum = new BitSet(); // 遍历每一行,存下当前行和之前行可能组成的和 // for (int i = 0; i < n; i++) // 初始时存下第一行 // sum.set(mat[0][i]); // for (int i = 1; i < m; i++) { // BitSet newSum = new BitSet(); // 用来存新的和 // for (int j = 0; j < n; j++) { // // 注意:要遍历BitSet中的真实位,请使用以下循环:previousSetBit()方法 用于查找在指定的起始索引上或之前是否存在任何真位 // // for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) { // // // operate on index i here // // } // for (int k = sum.length(); (k = sum.previousSetBit(k-1)) >= 0; ) { // newSum.set(k+mat[i][j]); // } // } // sum = newSum; // } // int ans = 4900; // for (int k = sum.length(); (k = sum.previousSetBit(k-1)) >= 0;) { // int diff = Math.abs(k - target); // ans = Math.min(ans, diff); // } // return ans; // } // public int minimizeTheDifference(int[][] mat, int target) { // int m = mat.length; // int n = mat[0].length; // int diff = Integer.MAX_VALUE, limit = 4900; // int [] dp = new int[limit]; // for (int i = 0; i < n; i++) // 相当于是手工实现java BitSet // dp[mat[0][i]] = 1; // for (int i = 1; i < m; i++) { // int [] tmp = new int [limit]; // for (int v = limit-1; v >= 0; v--) { // if (dp[v] == 0) continue; // for (int j = 0; j < n; j++) { // if (v + mat[i][j] < limit) // tmp[v+mat[i][j]] = 1; // } // } // System.arraycopy(tmp, 0, dp, 0, dp.length); // } // for (int i = 0; i < limit; i++) // if (dp[i] > 0) diff = Math.min(diff, Math.abs(i-target)); // return diff; // min difference // } // public boolean splitArraySameAverage(int[] nums) { // int n = nums.length; // int m = n / 2; // int sum = Arrays.stream(nums).sum(); // boolean poss = false; // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0) { // poss = true; // break; // } // } // if (!poss) return false; // BitSet [] bits = new BitSet [m+1]; // // bitset<300001> bits[m + 1] = {1}; // c++ 这里不知道该怎么改写了 // // for (int num : A) { // // for (int i = m; i >= 1; --i) { // // bits[i] |= bits[i - 1] << num; // // } // // } // for (int i = 0; i <= m; i++) // bits[i] = new BitSet(1); // for (int v : nums) { // for (int i = m; i >= 1; i--) // bits[i] |= bits[i-1] << v; // } // for (int i = 1; i <= m; i++) { // // if (sum * i % n == 0 && bits[i][]) // } // return false; // } // private boolean helper(int [] arr, int curSum, int cur, int start) { // if (cur == 0) return curSum == 0; // if (arr[start] > curSum / cur) return false; // for (int i = start; i < arr.length - cur + 1; i++) { // if (i > start && arr[i] == arr[i-1]) continue; // if (helper(arr, curSum - arr[i], cur-1, i+1)) return true; // } // return false; // } // public boolean splitArraySameAverage(int[] nums) { // int n = nums.length; // int m = n / 2; // int sum = Arrays.stream(nums).sum(); // boolean poss = false; // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0) { // poss = true; // break; // } // } // if (!poss) return false; // Arrays.sort(nums); // for (int i = 1; i <= m; i++) // if (sum * i % n == 0 && helper(nums, sum * i / n, i, 0)) return true; // return false; // } // bool splitArraySameAverage(vector<int>& A) { // https://www.cnblogs.com/grandyang/p/10285531.html // int n = A.size(), m = n / 2, sum = accumulate(A.begin(), A.end(), 0); // bool possible = false; // for (int i = 1; i <= m && !possible; ++i) { // if (sum * i % n == 0) possible = true; // } // if (!possible) return false; // bitset<300001> bits[m + 1] = {1}; // for (int num : A) { // for (int i = m; i >= 1; --i) { // bits[i] |= bits[i - 1] << num; // } // } // for (int i = 1; i <= m; ++i) { // if (sum * i % n == 0 && bits[i][sum * i / n]) return true; // } // return false; // } // 1)如果一个长度为n的数组可以被划分为A和B两个数组,我们假设A的长度小于B并且A的大小是k,那么:total_sum / n == A_sum / k == B_sum / (n - k),其中1 <= k <= n / 2。那么可以知道:A_sum = total_sum * k / n。由于A_sum一定是个整数,所以我们可以推导出total_sum * k % n == 0,那就是说,对于特定的total_sum和n而言,符合条件的k不会太多。这样我们在第一步中就首先验证是否存在符合条件的k,如果不存在就可以提前返回false。 // 2)如果经过第一步的验证,发现确实有符合条件的k,那么我们在第二步中,就试图产生k个子元素的所有组合,并且计算他们的和。这里的思路就有点类似于背包问题了,vector<unordered_set<int>> sums,其中sums[i][j]表示A[0, i]这个子数组中的任意j个元素的所有可能和。可以得到递推公式是:sums[i][j] = sums[i - 1][j] "join" (sums[i][j - 1] + A[i]),其中等式右边的第一项表示这j个元素中不包含A[i],而第二项表示这j个元素包含A[i]。这样就可以采用动态规划的思路得到sums[n - 1][k]了(1 <= k <= n / 2)。 // 3)有了sums[n - 1][k],我们就检查sums[n - 1][k]中是否包含(total_sum * k / n)。一旦发现符合条件的k,就返回true,否则就返回false。 // 在递推公式中我们发现,sums[i][j]仅仅和sums[i - 1][j],sums[i][j - 1]有关,所以可以进一步将空间复杂度从O(n^2*M)降低到O(n*M),其中M是n中的所有元素的组合数(可能高达O(2^n))。时间复杂度为O(n^3*M)。 // public boolean splitArraySameAverage(int[] nums) { // int n = nums.length; // int m = n / 2; // int sum = Arrays.stream(nums).sum(); // boolean poss = false; // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0) { // poss = true; // break; // } // } // if (!poss) return false; // List<Set<Integer>> ls = new ArrayList<>(); // for (int i = 0; i <= m; i++) // ls.add(new HashSet<Integer>()); // ls.get(0).add(0); // 这种构建子序列和的方法,要学习一下 // for (int v : nums) { // for each element in A, we try to add it to sums[i] by joining sums[i - 1] // for (int i = m; i >= 1; i--) // for (int t : ls.get(i-1)) // ls.get(i).add(t + v); // } // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0 && ls.get(i).contains(sum * i / n)) // return true; // } // return false; // } // public int numSquares(int n) { // int [] dp = new int [n+1]; // Arrays.fill(dp, n+1); // dp[0] = 0; // for (int i = 1; i <= n; i++) { // for (int j = 1; j*j <= n; j++) // if (i - j*j >= 0) dp[i] = Math.min(dp[i], dp[i-j*j] + 1); // } // return dp[n]; // } // public int coinChange(int[] coins, int amount) { // if (amount == 0) return 0; // int n = coins.length; // int [] dp = new int [amount + 1]; // Arrays.sort(coins); // Arrays.fill(dp, amount + 1); // dp[0] = 0; // for (int i = 0; i <= amount; i++) { // for (int v : coins) { // if (i - v < 0) continue; // dp[i] = Math.min(dp[i], dp[i-v] + 1); // } // } // return dp[amount] == amount + 1 ? -1 : dp[amount]; // } // public int change(int target, int[] nums) { // int[] dp = new int[target + 1]; // // 初始化dp[0]为1 // dp[0] = 1; // // 循环数组中所有数字 // for (int val : nums) { // for (int i = 0; i <= target - val; i++) { // // dp[i]大于0说明,存在dp[i]种组合,其和为i的可能性 // if (dp[i] > 0) { // // 既然存在和为i的可能,那么i加上当前数字的和也是存在的 // dp[i + val] += dp[i]; // } // } // } // return dp[target]; // } // public int backPackIII(int[] A, int[] V, int m) { // int n = A.length; // int [] dp = new int[m+1]; // for (int i = 1; i <= m; i++) { // for (int j = 0; j < n; j++) { // if (i - A[j] >= 0) // dp[i] = Math.max(dp[i], dp[i-A[j]] + V[j]); // } // } // return dp[m]; // } // public int lastStoneWeightII(int[] stones) { // int n = stones.length; // int sum = Arrays.stream(stones).sum(); // boolean[] dp = new boolean[sum+1]; // dp[0] = true; // sum = 0; // for (int v : stones) { // sum += v; // for (int i = sum; i >= v; i--) // if (dp[i-v]) dp[i] = true; // } // for (int i = sum/2; i >= 0; i--) // if (dp[i]) return sum - i * 2; // return 0; // } // public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { // int m = baseCosts.length; // 还有bug, 暂时不想再改这个题目了 // int n = toppingCosts.length; // if (m == 1 && target < baseCosts[0]) return baseCosts[0]; // 不喜欢处理这种特殊情况 // Arrays.sort(toppingCosts); // int [] des = IntStream.rangeClosed(0, n-1).map(z->toppingCosts[n-1-z]).toArray(); // boolean [] dp = new boolean [target + 1]; // int cur = 0; // dp[0] = true; // for (int i = 0; i < m; i++) { // cur = baseCosts[i]; // if (cur <= target) // dp[cur] = true; // } // for (int i = 0; i < n; i++) { // int v = toppingCosts[i]; // for (int j = target; j > 0; j--) { // if (!dp[j]) continue; // if (j + v + v <= target) // dp[j+v+v] = true; // if (j + v <= target) // dp[j+v] = true; // } // } // for (int i = target; i > 0; i--) // if (dp[i]) return i; // return -1; // } // private void helper(int [] arr, int target, int cur, int idx) { // if (Math.abs(cur - target) < Math.abs(res - target) || Math.abs(cur - target) == Math.abs(res - target) && cur < res) // res = cur; // if (idx == arr.length) return; // helper(arr, target, cur, idx+1); // helper(arr, target, cur + arr[idx], idx+1); // helper(arr, target, cur + arr[idx]*2, idx+1); // } // int res = Integer.MAX_VALUE; // public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { // for (int v : baseCosts) // helper(toppingCosts, target, v, 0); // return res; // } // private int dfs(int [] arr, int [] mi, int i, int j, int cnt) { // if (cnt >= mi.length) return 0; // if (cache.containsKey(i) && cache.get(i).containsKey(j)) return cache.get(i).get(j); // int res = Math.max( // mi[cnt] * arr[i] + dfs(arr, mi, i+1, j, cnt+1), // mi[cnt] * arr[j] + dfs(arr, mi, i, j-1, cnt+1)); // if (!cache.containsKey(i)) cache.put(i, new HashMap<Integer, Integer>()); // cache.get(i).put(j, res); // return res; // } // Map<Integer, Map<Integer, Integer>> cache = new HashMap<>(); // public int maximumScore(int[] nums, int[] multipliers) { // return dfs(nums, multipliers, 0, nums.length-1, 0); // } // public int maximumScore(int[] arr, int[] multipliers) { // int n = arr.length; // int m = multipliers.length; // if (n == 1) return arr[0] * multipliers[0]; // int [] dp = new int [n]; // the max product if get i vals from left side // Arrays.fill(dp, Integer.MIN_VALUE); // dp[0] = arr[n-1] * multipliers[0]; // dp[1] = arr[0] * multipliers[0]; // for (int o = 1; o < m; o++) { // if (o + 1 < n) // dp[o+1] = dp[o] + arr[o] * multipliers[o]; // for (int i = o; i > 0; i--) // dp[i] = Math.max(dp[i-1] + arr[i-1] * multipliers[o], dp[i] + arr[n-(o-i)-1] * multipliers[o]); // dp[0] = dp[0] + arr[n - o - 1] * multipliers[o]; // } // int max = Integer.MIN_VALUE; // for (int i = 0; i < n; i++) // max = Math.max(dp[i], max); // return max; // } // 定义二维数组dp[m + 1][m + 1]。dp[i][j]:表示nums数组中前i个数和后j个数组成的最大分数。 // base case: // dp[0][0] = 0; // dp[i][0]:此状态表示nums数组中前i个数和后0个数组成的最大分数,此状态只可能由dp[i - 1][0]转移得到。 // dp[0][j]:此状态表示nums数组中前0个数和后j个数组成的最大分数,此状态只可能由dp[0][j - 1]转移得到。 // dp[i][j]:该状态表示nums数组中前i个数和后j个数组成的最大分数,可能由状态 // dp[i - 1][j]和状态dp[i][j - 1]转移得到,取其中得分最大的一个。 // 遍历所有可能的组合(满足i + j = m)获得最大得分。 // public int maximumScore(int[] arr, int[] multipliers) { // 这里有个bug暂时不想改了,但思路清晰 // int n = arr.length; // int m = multipliers.length; // if (n == 1) return arr[0] * multipliers[0]; // int [][] dp = new int [m+1][m+1]; // for (int i = 1; i <= m; i++) // dp[i][0] = dp[i-1][0] + arr[i-1]*multipliers[i-1]; // for (int i = 1; i <= m; i++) // dp[0][i] = dp[i-1][0] + arr[n-i]*multipliers[i-1]; // for (int i = 1; i <= m; i++) // for (int j = 1; j <= m; j++) // if (i + j <= m) // dp[i][j] = Math.max(dp[i-1][j] + arr[i-1]*multipliers[i+j-1], dp[i][j-1] + arr[n-j]*multipliers[i+j-1]); // int max = Integer.MIN_VALUE; // for (int i = 0; i <= m; i++) // max = Math.max(max, dp[i][m-i]); // return max; // } // // https://blog.csdn.net/luke2834/article/details/89457888 // 这个题目要多写几遍 // public int tallestBillboard(int[] rods) { // 写得好神奇呀 // int n = rods.length; // int sum = Arrays.stream(rods).sum(); // System.out.println("sum: " + sum); // int [][] dp = new int [2][(sum + 1) << 1]; // (sum + 1) * 2 // for (int i = 0; i < 2; i++) // Arrays.fill(dp[i], -1); // dp[0][sum] = 0; // for (int i = 0; i < n; i++) { // int cur = i & 1, next = (i & 1) ^ 1; // 相当于是滚动数组: [0, 1] // for (int j = 0; j < dp[cur].length; j++) { // if (dp[cur][j] == -1) continue; // dp[next][j] = Math.max(dp[cur][j], dp[next][j]); // update to max // dp[next][j+rods[i]] = Math.max(dp[next][j+rods[i]], dp[cur][j] + rods[i]); // dp[next][j-rods[i]] = Math.max(dp[next][j-rods[i]], dp[cur][j] + rods[i]); // } // } // return dp[rods.length & 1][sum] >> 1; // dp[n&1][sum] / 2 // } // // 1. 所有的状态全集:dp[len][sum+1], len = length of array, sum = sum of the array,代表两边共有的高度 // // 2. state transfer: // // a. 忽略当前 dp[i][j] = max(dp[i-1][j], dp[i][j]) // // b. 加入到higher一侧 dp[i][j+h] = max(dp[i][j+h], dp[i-1][j]) // // c. 加入到lower一侧 lower = abs(j-h); dp[i][lower] = max(dp[i][lower], dp[i][j] + min(j, h)); 其中min(j,h)为新增高度 // private void dfs(int [] arr, int idx) { // int cur = arr[idx]; // if (dp[idx][cur] != -1) return; // if (idx == 0) { // dp[idx][cur] = 0; // add // dp[idx][0] = 0; // ignore // return; // } // dfs(arr, idx-1); // int lower = 0; // for (int i = 0; i < dp[idx].length-cur; i++) { // if (dp[idx-1][i] < 0) continue; // dp[idx][i] = Math.max(dp[idx][i], dp[idx-1][i]); // 1: ignore // dp[idx][i+cur] = Math.max(dp[idx][i+cur], dp[idx-1][i]); // 2: add to higher // lower = Math.abs(i - cur); //3. add to lower // dp[idx][lower] = Math.max(dp[idx][lower], dp[idx-1][i] + Math.min(i, cur)); // } // } // int [][] dp; // int n; // public int tallestBillboard(int[] rods) { // int n = rods.length; // int sum = Arrays.stream(rods).sum(); // dp = new int [n][sum+1]; // for (int i = 0; i < n; i++) // Arrays.fill(dp[i], -1); // dfs(rods, n-1); // return dp[n-1][0]; // } // 定义一个数对键值:(i,j):i表示两个子序列的累加和差值的绝对值,j表示这个差值下,子序列中累加和的最大值,定义一个dp的map存放前m个数的所有子序列的累加和之差和对应的累加和最大值:比如:[1,2,3,4,5], 累加和为15,[7,8,9],累加和为24,两者差值为9,那么用(9,24) // 新建一个HashMap temp用于存放第m个数对之前子序列累加和只差的状态转移结果 // 对于新到来的rod,只能够有3中情况: // 1.rod不加入任何列表: // 从dp中拿出每个子序列的差值k的累加和最大值v1,每个结果与temp中相应k的累加和最大值v2比较,如果v1>v2,那么更新temp中k对应的最大累加和为v1 // 2.rod加入累加和较大的序列 // 从dp中拿出每个子序列的差值k的累加和最大值v1,并加上rod,这时差值变成k + rod,累加和最大值变成v1+ rod, 每个结果与temp中相应k + rod的累加和最大值v2比较,如果v1 + rod > v2,那么更新temp中k对应的最大累加和为v1+rod // 3.rod加入累加和较小的序列 // 从dp中拿出每个子序列的差值k的累加和最大值v1,累加和较小的子序列加上了rod,那么和累加和较大的子序列之差为k-rod,k-rod为负数时,说明累加和较小数组超越了累加和较大的数组,为非负数时,说明较大累加和的数组不变,因此当前累加和最大值为x = Max(v, v - (k - rod)), 然后再和temp中序列差为abs(k-rod)的最大累加和v2比较,如果x>v2则更新temp中abs(k-rod)为x; // public int tallestBillboard(int[] rods) { // int n = rods.length; // Map<Integer, Integer> dp = new HashMap<>(); // dp.put(0, 0); // for (int rod : rods) { // System.out.println("\nrod: " + rod); // Map<Integer, Integer> tmp = new HashMap<>(); // dp.forEach((k, v) -> { // if (tmp.getOrDefault(k, -1) < v) tmp.put(k, v); // if (tmp.getOrDefault(k+rod, -1) < v+rod) tmp.put(k + rod, v+rod); // int dis = k - rod; // int larger = Math.max(v, v-dis); // dis = Math.abs(dis); // if (tmp.getOrDefault(dis, -1) < larger) tmp.put(dis, larger); // }); // dp = tmp; // } // return dp.get(0); // } } public static void main(String[] args) { Solution s = new Solution(); int [] a = new int [] {1, 2, 3}; int r = s.tallestBillboard(a); System.out.println("r: " + r); } }
UTF-8
Java
48,290
java
dynasixmicProgramming.java
Java
[ { "context": "age(vector<int>& A) { // https://www.cnblogs.com/grandyang/p/10285531.html\n // int n = A.size(), ", "end": 29016, "score": 0.999636709690094, "start": 29007, "tag": "USERNAME", "value": "grandyang" }, { "context": "ax;\n // }\n\n // // https://blog.csdn.net/luke2834/article/details/89457888 // 这个题目要多写几遍\n // ", "end": 39528, "score": 0.9995467066764832, "start": 39520, "tag": "USERNAME", "value": "luke2834" } ]
null
[]
mport com.TreeNode; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.*; import java.util.stream.*; import java.util.stream.Collectors; import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptException; import static java.util.stream.Collectors.toMap; public class dynasixmicProgramming { public static class Solution { // public int combinationSum4(int[] nums, int target) { // int n = nums.length; // if (n == 1 && target < nums[0] || nums[0] != 0 && target % nums[0] != 0) return 0; // // int [] dp = new int [n]; // // int [] dp = new int [target + 1]; // // dp[nums[0]] = target % nums[0] == 0 ? 1 : 0; // // for (int i = 1; i < n; i++) { // } // private void helper(int [] arr, int i, int j) { // if (i == j) return dp[i][j] = arr[i]; // if (j == i+1) return Math.abs(arr[i] - arr[j]); // if (dp[i][j] > 0) return dp[i][j]; // } // 还木有认出这个题到底是在考什么 // int [][] dp; // int n; // public int lastStoneWeightII(int[] stones) { // n = stones.length; // if (n == 1) return stones[0]; // if (n == 2) return Math.abs(stones[0] - stones[1]); // dp = new int [n][n]; // return dfs(stones, 0, n-1); // } // public int findMaxForm(String[] strs, int m, int n) { // int [][] dp = new int [m+1][n+1]; // dp[0][0] = 0; // for (String s : strs) { // int one = 0, zoo = 0; // for (int i = 0; i < s.length(); i++) { // if (s.charAt(i) == '0') ++ zoo; // else ++one; // } // for (int i = m; i >= zoo; i--) // for (int j = n; j >= one; j--) // dp[i][j] = Math.max(dp[i][j], dp[i-zoo][j-one] + 1); // } // return dp[m][n]; // } // public String optimalDivision(int[] nums) { // int n = nums.length; // if (n == 0) return ""; // String res = String.valueOf(nums[0]); // if (n == 1) return res; // if (n == 2) return res + "/" + nums[1]; // res += "/(" + nums[1]; // for (int i = 2; i < n; i++) // res += "/" + nums[i]; // return res + ")"; // } // private int dfs(int [] arr, int target) { // if (dp[target] != -1) return dp[target]; // int res = 0; // for (int i = 0; i < n; i++) { // if (target >= arr[i]) // res += dfs(arr, target - arr[i]); // } // return dp[target] = res; // } // int [] dp; // int n; // public int combinationSum4(int[] nums, int target) { // n = nums.length; // dp = new int [target +1 ]; // Arrays.fill(dp, -1); // dp [0] = 1; // return dfs(nums, target); // } // public int combinationSum4(int[] nums, int target) { // int n = nums.length; // int [] dp = new int [target +1 ]; // dp [0] = 1; // for (int i = 1; i <= target; i++) { // for (int j = 0; j < n; j++) { // if (i - nums[j] >= 0) // dp[i] += dp[i-nums[j]]; // } // } // return dp[target]; // } // // 找出数组中等于target的最小非重叠区间的长度,用dp[i]表示当前i以及i之前的满足条件的最小区间长度,状态更新规则为 // // dp[i]=min(dp[i-1],i-j+1) if sum[j,i]=target // // 答案更新规则 // // res=min(res,dp[j−1]+i−j+1) // public int minSumOfLengths(int[] arr, int target) { // int n = arr.length; // int [] dp = new int [n]; // Arrays.fill(dp, Integer.MAX_VALUE); // int cur = 0, s = 0; // int res = Integer.MAX_VALUE, minLen = Integer.MAX_VALUE; // for (int i = 0; i < n; i++) { // cur += arr[i]; // while (cur > target) { // cur -= arr[s]; // s += 1; // } // if (cur == target) { // int curLen = i - s + 1; // if (s > 0 && dp[s-1] != Integer.MAX_VALUE) // res = Math.min(res, curLen + dp[s-1]); // minLen = Math.min(minLen, curLen); // } // dp[i] = minLen; // } // return res == Integer.MAX_VALUE ? -1 : res; // } // class Node { // private int val; // private int back; // public Node(int val, int back) { // this.val = val; // this.back = back; // 记住了每一跳是否是往反跳 // } // } // // 给出坐标 x ,可以往前跳的步长 a,往后跳的步长 b。要求输出能跳回家的最少跳跃次数。 // // 求最少跳跃次数,思路用 BFS 求解,最先到达坐标 x 的方案即是最少跳跃次数。 // // 对forbidden 的处理是把记忆化数组里面把他们标记为 true。 // // 禁止连续往后跳 2 次的限制,要求我们在 BFS 入队的时候再记录一下跳跃方向,每次往后跳的时候判断前一跳是否是往后跳,如果是往后跳,此次就不能往后跳了。 // public int minimumJumps(int[] forbidden, int a, int b, int x) { // final int MAX = 100050; // boolean [] take = new boolean [MAX]; // for (int fob: forbidden) // 标记不能跳的点 // take[fob] = true; // int[][] dist = new int[MAX][2]; // 用于记录往前跳与往后跳的次数 // for(int i = 0; i < MAX; i++) // 进行初始化 // Arrays.fill(dist[i], -1); // dist[0][0] = 0; // Queue<Node> q = new LinkedList<>(); // 创造队列 // q.offer(new Node(0, 0)); // Node cur = null; // while (!q.isEmpty()) { // bfs 思路 // cur = q.poll(); // if(cur.val + a < MAX && !take[cur.val + a] && dist[cur.val + a][0] == -1){ // 往前跳 // dist[cur.val + a][0] = dist[cur.val][cur.back] + 1; // q.offer(new Node(cur.val + a, 0)); // forward: 0 // } // if(cur.back != 1 && cur.val - b >= 0 && !take[cur.val - b] && dist[cur.val - b][1] == -1){ // 往后跳 // dist[cur.val - b][1] = dist[cur.val][cur.back] + 1; // q.offer(new Node(cur.val - b, 1)); // backward: 1 // } // } // int ans = Math.min((dist[x][0] == -1 ? Integer.MAX_VALUE : dist[x][0]), (dist[x][1] == -1 ? Integer.MAX_VALUE : dist[x][1])); // return ans == Integer.MAX_VALUE ? -1 : ans; // } // private int dfs(int i, int j) { // } // // To make the computation of each state in constant time, // // we could add another flag to the state that // // indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). // // use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. // int [][][] dp; // public int numberOfSets(int n, int k) { // dp = new int [n][k+1][2]; // } // private int getMinCnt(String s) { // int n = s.length(); // if (n == 1) return 0; // if (n == 2) return s.charAt(0) == s.charAt(1) ? 0 : 1; // int i = 0, j = n-1, cnt = 0; // while (i <= j) { // if (s.charAt(i) != s.charAt(j)) ++ cnt; // ++i; // --j; // } // return cnt; // } // private int dfs(String s, int k, int idx, int v) { // if (idx >= n) return 0; // if (dp[idx][v] <= n) return dp[idx][v]; // if (v == 1) // return dp[idx][v] = m.get(s.substring(idx)); // if (idx == n-v) // return dp[idx][v] = 0; // int min = n+1; // for (int i = idx; i <= n-v; i++) // min = Math.min(min, m.get(s.substring(idx, i+1)) + dfs(s, k, i+1, v-1)); // return dp[idx][v] = min; // } // Map<String, Integer> m = new HashMap<>(); // int [][] dp; // int n; // public int palindromePartition(String s, int k) { // n = s.length(); // if (n == 1 || n == k) return 0; // for (int i = 0; i < n; i++) // for (int j = i; j < n; j++) // m.put(s.substring(i, j+1), getMinCnt(s.substring(i, j+1))); // dp = new int [n][k+1]; // for (int i = 0; i < n; i++) // Arrays.fill(dp[i], n+1); // return dfs(s, k, 0, k); // } // public boolean checkPartitioning(String s) { // int n = s.length(); // if (n == 3) return true; // boolean [][] p = new boolean[n][n]; // for (int i = n-1; i >= 0; i--) // for (int j = i; j < n; j++) // if (s.charAt(i) == s.charAt(j) && (j-i < 2 || p[i+1][j-1])) // p[i][j] = true; // for (int i = 0; i < n-2; i++) { // for (int j = i+1; j < n-1; j++) { // if (p[0][i] && p[i+1][j] && p[j+1][n-1]) return true; // } // } // return false; // } // public int longestPalindrome(String s, String t) { // 这个题目没有懂,需要再好好看一下 // int m = s.length(); // int n = t.length(); // int mn = m + n; // String st = s + t; // int [][] dp = new int [mn][mn]; // for (int i = 0; i < mn; i++) // dp[i][i] = 1; // for (int l = 2; l <= mn; l++) { // for (int i = 0, j = i+l-1; j < mn; i++,j++) { // // if (st.charAt(i) == st.charAt(j)) // dp[i][j] = dp[i+1][j-1] + 2; // else dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]); // } // } // int ans = 0; // for (int i = 0; i < m; i++) { // for (int j = 0; j < n; j++) { // if (s.charAt(i) == t.charAt(j)) // ans = Math.max(ans, dp[i][m+j]); // // } // } // return ans; // } // private List<Integer> findCommonElements(int [] a, int [] b) { // Set<Integer> sa = new HashSet<>(); // Set<Integer> sb = new HashSet<>(); // for (int v : a) // sa.add(v); // for (int v : b) // sb.add(v); // sa.retainAll(sb); // List<Integer> l = new ArrayList<>(); // for (Integer v : sa) // l.add(v); // Collections.sort(l); // return l; // } // private int binarySearch(int [] arr, int v, int l, int r) { // if (l == r) return arr[l] == v ? l : -1; // if (l == r-1) return arr[l] == v ? l : (arr[r] == v ? r : -1); // int m = l + (r-l)/2; // if (arr[m] == v) return m; // if (arr[m] < v) return binarySearch(arr, v, m+1, r); // return binarySearch(arr, v, l, m-1); // } // public int maxSum(int[] a, int[] b) { // int m = a.length; // int n = b.length; // int mod = 1_000_000_007; // if (a[m-1] <= b[0] || a[0] >= b[n-1]) // return (int)((a[m-1] <= b[0] ? Arrays.stream(b).sum() : Arrays.stream(a).sum()) % mod); // long [] pa = new long [m+1]; // long [] pb = new long [n+1]; // for (int i = 1; i <= m; i++) // pa[i] = pa[i-1] + a[i-1]; // for (int i = 1; i <= n; i++) // pb[i] = pb[i-1] + b[i-1]; // List<Integer> s = findCommonElements(a, b); // if (s.size() == 0) return (int)(Math.max(pa[m], pb[n]) % mod); // long res = 0; // int i = 0, j = 0, pi = 0, pj = 0, v = 0; // for (int x = 0; x < s.size(); x++) { // v = s.get(x); // i = binarySearch(a, v, pi, m-1); // j = binarySearch(b, v, pj, n-1); // res = (res + Math.max(pa[i+1]-(pi == 0 ? 0 : pa[pi]), pb[j+1]-(pj == 0 ? 0 : pb[pj]))) % mod; // pi = i+1; // pj = j + 1; // } // if (i != pi || j != pj) { // if (i != pi && j != pj) // res = (res + Math.max(pa[m]-pa[pi], pb[n]-pb[pj])) % mod; // else if (i != pi) // res = (res + pa[m]-pa[pi]) % mod; // else res = (res + pb[n]-pb[pj]) % mod; // } // return (int)res; // } // public int[] pathsWithMaxScore(List<String> board) { // int m = board.size(); // int n = board.get(0).length(); // int [][] max = new int[m][n]; // long [][] cnt = new long [m][n]; // int mod = 1_000_000_007; // cnt[m-1][n-1] = 1; // for (int i = m-2; i >= 0; i--) // if (board.get(i).charAt(n-1) != 'X') { // max[i][n-1] = max[i+1][n-1] + board.get(i).charAt(n-1)-'0'; // cnt[i][n-1] = cnt[i+1][n-1]; // } else { // max[i][n-1] = Integer.MIN_VALUE; // cnt[i][n-1] = Integer.MIN_VALUE; // } // for (int j = n-2; j >= 0; j--) // if (board.get(m-1).charAt(j) != 'X') { // max[m-1][j] = max[m-1][j+1] + board.get(m-1).charAt(j)-'0'; // cnt[m-1][j] = cnt[m-1][j+1]; // } else { // max[m-1][j] = Integer.MIN_VALUE; // cnt[m-1][j] = Integer.MIN_VALUE; // } // int tmp = 0; // for (int i = m-2; i >= 0; i--) { // for (int j = n-2; j >= 0; j--) { // if (board.get(i).charAt(j) == 'X') { // max[i][j] = Integer.MIN_VALUE; // cnt[i][j] = Integer.MIN_VALUE; // continue; // } // tmp = Math.max(max[i+1][j], max[i][j+1]); // tmp = Math.max(tmp, max[i+1][j+1]) + (board.get(i).charAt(j) == 'E' ? 0 : board.get(i).charAt(j) - '0'); // max[i][j]= tmp; // if (tmp == max[i+1][j+1] + (board.get(i).charAt(j) == 'E' ? 0 : board.get(i).charAt(j) - '0')) // cnt[i][j] = cnt[i+1][j+1]; // else { // if (max[i+1][j] == max[i][j+1]) cnt[i][j] = cnt[i+1][j] + cnt[i][j+1]; // else cnt[i][j] = (tmp == max[i+1][j] + (board.get(i).charAt(j) == 'E' ? 0 : board.get(i).charAt(j) - '0') ? cnt[i+1][j] : cnt[i][j+1]); // } // cnt[i][j] %= mod; // } // } // return new int[] {max[0][0] > 0 ? max[0][0] : 0, (int)cnt[0][0] > 0 ? (int)cnt[0][0] : 0}; // } // public int firstDayBeenInAllRooms(int[] nextVisit) { // int n = nextVisit.length; // int [] dp = new int [n]; // int cnt = 0; // dp[0] = 0; // for (int i = 0; i < n; i++) { // } // } // private boolean dfs(char [] s, int i, int cnt) { // cnt of left ( // if (cnt < 0) return false; // if (i == s.length) return cnt == 0; // if (dp[i][cnt] != null) return dp[i][cnt]; // char c = s[i]; // boolean res = false; // if (c == '(') res = dfs(s, i+1, cnt+1); // else if (c == ')') res = dfs(s, i+1, cnt-1); // else res = dfs(s, i+1, cnt) || dfs(s, i+1, cnt+1) || dfs(s, i+1, cnt-1); // return dp[i][cnt] = res; // } // Boolean [][] dp; // int n; // public boolean checkValidString(String s) { // n = s.length(); // dp = new Boolean [n][n]; // return dfs(s.toCharArray(), 0, 0); // } // public int[] maxSumOfThreeSubarrays(int[] nums, int k) { // int n = nums.length; // int [] pre = new int [n+1]; // for (int i = 1; i <= n; i++) // pre[i] = pre[i-1] + nums[i-1]; // // left[i]表示在区间[0, i]范围内长度为k且和最大的子数组的起始位置 // // right[i]表示在区间[i, n - 1]范围内长度为k且和最大的子数组的起始位置 // int [] left = new int [n]; // int [] right = new int [n]; // int [] res = new int [3]; // Arrays.fill(right, n-k); // for (int i = k, total = pre[k]-pre[0]; i < n; i++) { // if (pre[i+1] - pre[i+1-k] > total) { // left[i]= i+1-k; // total = pre[i+1] - pre[i+1-k]; // } else left[i] = left[i-1]; // } // for (int i = n-1-k, total = pre[n]-pre[n-k]; i >= 0; i--) { // if (pre[i+k] - pre[i] >= total) { // right[i] = i; // total = pre[i+k] - pre[i]; // } else right[i] = right[i+1]; // } // int max = Integer.MIN_VALUE; // for (int i = k; i <= n-2*k; i++) { // int l = left[i-1]; // int r = right[i+k]; // int total = (pre[i+k]-pre[i]) + (pre[k+l]-pre[l]) + (pre[r+k] - pre[r]); // if (max < total) { // max = total; // res = new int [] {l, i, r}; // } // } // return res; // } // public int maxDotProduct(int[] a, int[] b) { // int m = a.length; // int n = b.length; // int [][] dp = new int [m][n]; // dp[m-1][n-1] = a[m-1]*b[n-1]; // for (int i = m-2; i >= 0; i--) // dp[i][n-1] = Math.max(a[i] * b[n-1], dp[i+1][n-1]); // for (int j = n-2; j >= 0; j--) // dp[m-1][j] = Math.max(a[m-1]*b[j], dp[m-1][j+1]); // int cur = 0, tmp = 0; // int right = 0, down = 0, dr = 0; // for (int i = m-2; i >= 0; i--) { // for (int j = n-2; j >= 0; j--) { // cur = a[i] * b[j]; // tmp = Math.max(dp[i+1][j], dp[i][j+1]); // tmp = Math.max(tmp, cur); // if (dp[i+1][j+1] > 0 && cur > 0) tmp = Math.max(tmp, dp[i+1][j+1] + cur); // dp[i][j] = tmp; // } // } // return dp[0][0]; // } // private int dfs(int steps, int n, int i) { // if (steps < i) return 0; // 裁枝: 如果剩余步数小于index,说明已无法返回起点 // if (i < 0 || i >= n) return 0; // if (steps == 0 && i == 0) return 1; // if (dp[steps][i] > 0) return dp[steps][i]; // long res = dfs(steps-1, n, i-1) % mod; // res = (res + dfs(steps-1, n, i+1)) % mod; // res = (res + dfs(steps-1, n, i)) % mod; // return dp[steps][i] = (int)res; // } // int mod = 1_000_000_007; // // memo[i][j]代表,还剩下i步时,从下标j返回下标0的方案数 // // 由于能够到达的最远index一定不能超过步数的一半, // // j的最大值为steps/2+1 // int [][] dp; // public int numWays(int steps, int arrLen) { // dp = new int [steps + 1][steps/2 + 1]; // return dfs(steps, arrLen, 0); // } // public int numWays(int steps, int arrLen) { // int maxPos = Math.min(steps/2+1, arrLen); // long[][] dp = new long[steps + 1][maxPos + 1]; // int mod = 1_000_000_007; // dp[1][0] = 1; // dp[1][1] = 1; // for (int i = 2; i <= steps; i++) // for (int j = 0; j < maxPos; j++) // dp[i][j] = (dp[i-1][j] + dp[i-1][j+1] + (j > 0 ? dp[i-1][j-1] : 0)) % mod; // return (int)(dp[steps][0] % mod); // } // public int maxSumSubmatrix(int[][] mat, int k) { // int m = mat.length; // int n = mat[0].length; // if (m == 1 && n == 1) return mat[0][0]; // int [][] pre = new int [m][n]; // int res = Integer.MIN_VALUE; // for (int i = 0; i < m; i++) { // for (int j = 0; j < n; j++) { // int t = mat[i][j]; // if (i > 0) t += pre[i-1][j]; // if (j > 0) t += pre[i][j-1]; // if (i > 0 && j > 0) t -= pre[i-1][j-1]; // pre[i][j] = t; // for (int r = 0; r <= i; r++) { // for (int c = 0; c <= j; c++) { // int d = pre[i][j]; // if (r > 0) d -= pre[r-1][j]; // if (c > 0) d -= pre[i][c-1]; // if (r > 0 && c > 0) d += pre[r-1][c-1]; // if (d <= k) res = Math.max(res, d); // } // } // } // } // return res; // } // // 把二维数组按行或列拆成多个一维数组,然后利用一维数组的累加和来找符合要求的数字, // // 这里用了 lower_bound 来加快的搜索速度,也可以使用二分搜索法来替代。 // public int maxSumSubmatrix(int[][] mat, int target) { // int row = mat.length; // int col = mat[0].length; // int res = Integer.MIN_VALUE; // boolean key = col > row ? false : true; // int m = Math.min(row, col); // int n = Math.max(row, col); // int [] pre = new int [n]; // TreeSet<Integer> ts = new TreeSet<>(); //用来保存当前高度下,长度为从0开始到k位置的矩形的结果。理解set的含义是解决此题的关键。 // Integer tmp = 0; // for (int i = 0; i < m; i++) { // 找从第i行开始一直到第0行这i+1行的可能组成的矩形长度 // Arrays.fill(pre, 0); // for (int j = i; j >= 0; j--) { // ts.clear(); // ts.add(0); // int curSum = 0; // for (int k = 0; k < n; k++) { // if (key) // pre[k] += mat[k][j]; // else pre[k] += mat[j][k]; // curSum += pre[k]; // // * 因为要满足 (sum-set中的元素)<=target, // // * 而且sum-set中的元素的值要尽可能的大, // // * 所以也就是再求小于等于sum-target中满足条件的元素的最小的一个 // // * 正好TreeSet中提供了这个方法ceil(),可以很方便的找出这个元素 // tmp = ts.ceiling(curSum - target); // if (tmp != null) res = Math.max(res, curSum - tmp); // ts.add(curSum); // } // } // } // return res; // } // int [][] dp; // public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { // dp = new int [m][n]; // } // public String largestMultipleOfThree(int[] digits) { // int n = digits.length; // Arrays.sort(digits); // int [] dg = IntStream.rangeClosed(0, n-1).map(z->digits[n-1-z]).toArray(); // System.out.println("dg.length: " + dg.length); // for (int z = 0; z < dg.length; ++z) // System.out.print(dg[z] + ", "); // System.out.println(""); // // find the longest subsequece of sum % 3 == 0 // return ""; // } // // DP + BitSet : 这里面有个小问题需要挑出来 // // 使用一个DP数组存下当前行和之前行每行选一个数可能构成的和, // // 在本题中,可以使用BitSet(简介)来存储之前行可以组成的和(由于所有数的最大值为70,而行数最大也为70,故BitSet最大的位数即为4900)。 // // 对于当前行,遍历BitSet已经set过的位(即代表之前行可能组成的和),然后加上当前数,set新的和 // // 最后遍历BitSet,求出当前位与target的最小值 // public int minimizeTheDifference(int[][] mat, int target) { // int m = mat.length; // int n = mat[0].length; // BitSet sum = new BitSet(); // 遍历每一行,存下当前行和之前行可能组成的和 // for (int i = 0; i < n; i++) // 初始时存下第一行 // sum.set(mat[0][i]); // for (int i = 1; i < m; i++) { // BitSet newSum = new BitSet(); // 用来存新的和 // for (int j = 0; j < n; j++) { // // 注意:要遍历BitSet中的真实位,请使用以下循环:previousSetBit()方法 用于查找在指定的起始索引上或之前是否存在任何真位 // // for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) { // // // operate on index i here // // } // for (int k = sum.length(); (k = sum.previousSetBit(k-1)) >= 0; ) { // newSum.set(k+mat[i][j]); // } // } // sum = newSum; // } // int ans = 4900; // for (int k = sum.length(); (k = sum.previousSetBit(k-1)) >= 0;) { // int diff = Math.abs(k - target); // ans = Math.min(ans, diff); // } // return ans; // } // public int minimizeTheDifference(int[][] mat, int target) { // int m = mat.length; // int n = mat[0].length; // int diff = Integer.MAX_VALUE, limit = 4900; // int [] dp = new int[limit]; // for (int i = 0; i < n; i++) // 相当于是手工实现java BitSet // dp[mat[0][i]] = 1; // for (int i = 1; i < m; i++) { // int [] tmp = new int [limit]; // for (int v = limit-1; v >= 0; v--) { // if (dp[v] == 0) continue; // for (int j = 0; j < n; j++) { // if (v + mat[i][j] < limit) // tmp[v+mat[i][j]] = 1; // } // } // System.arraycopy(tmp, 0, dp, 0, dp.length); // } // for (int i = 0; i < limit; i++) // if (dp[i] > 0) diff = Math.min(diff, Math.abs(i-target)); // return diff; // min difference // } // public boolean splitArraySameAverage(int[] nums) { // int n = nums.length; // int m = n / 2; // int sum = Arrays.stream(nums).sum(); // boolean poss = false; // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0) { // poss = true; // break; // } // } // if (!poss) return false; // BitSet [] bits = new BitSet [m+1]; // // bitset<300001> bits[m + 1] = {1}; // c++ 这里不知道该怎么改写了 // // for (int num : A) { // // for (int i = m; i >= 1; --i) { // // bits[i] |= bits[i - 1] << num; // // } // // } // for (int i = 0; i <= m; i++) // bits[i] = new BitSet(1); // for (int v : nums) { // for (int i = m; i >= 1; i--) // bits[i] |= bits[i-1] << v; // } // for (int i = 1; i <= m; i++) { // // if (sum * i % n == 0 && bits[i][]) // } // return false; // } // private boolean helper(int [] arr, int curSum, int cur, int start) { // if (cur == 0) return curSum == 0; // if (arr[start] > curSum / cur) return false; // for (int i = start; i < arr.length - cur + 1; i++) { // if (i > start && arr[i] == arr[i-1]) continue; // if (helper(arr, curSum - arr[i], cur-1, i+1)) return true; // } // return false; // } // public boolean splitArraySameAverage(int[] nums) { // int n = nums.length; // int m = n / 2; // int sum = Arrays.stream(nums).sum(); // boolean poss = false; // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0) { // poss = true; // break; // } // } // if (!poss) return false; // Arrays.sort(nums); // for (int i = 1; i <= m; i++) // if (sum * i % n == 0 && helper(nums, sum * i / n, i, 0)) return true; // return false; // } // bool splitArraySameAverage(vector<int>& A) { // https://www.cnblogs.com/grandyang/p/10285531.html // int n = A.size(), m = n / 2, sum = accumulate(A.begin(), A.end(), 0); // bool possible = false; // for (int i = 1; i <= m && !possible; ++i) { // if (sum * i % n == 0) possible = true; // } // if (!possible) return false; // bitset<300001> bits[m + 1] = {1}; // for (int num : A) { // for (int i = m; i >= 1; --i) { // bits[i] |= bits[i - 1] << num; // } // } // for (int i = 1; i <= m; ++i) { // if (sum * i % n == 0 && bits[i][sum * i / n]) return true; // } // return false; // } // 1)如果一个长度为n的数组可以被划分为A和B两个数组,我们假设A的长度小于B并且A的大小是k,那么:total_sum / n == A_sum / k == B_sum / (n - k),其中1 <= k <= n / 2。那么可以知道:A_sum = total_sum * k / n。由于A_sum一定是个整数,所以我们可以推导出total_sum * k % n == 0,那就是说,对于特定的total_sum和n而言,符合条件的k不会太多。这样我们在第一步中就首先验证是否存在符合条件的k,如果不存在就可以提前返回false。 // 2)如果经过第一步的验证,发现确实有符合条件的k,那么我们在第二步中,就试图产生k个子元素的所有组合,并且计算他们的和。这里的思路就有点类似于背包问题了,vector<unordered_set<int>> sums,其中sums[i][j]表示A[0, i]这个子数组中的任意j个元素的所有可能和。可以得到递推公式是:sums[i][j] = sums[i - 1][j] "join" (sums[i][j - 1] + A[i]),其中等式右边的第一项表示这j个元素中不包含A[i],而第二项表示这j个元素包含A[i]。这样就可以采用动态规划的思路得到sums[n - 1][k]了(1 <= k <= n / 2)。 // 3)有了sums[n - 1][k],我们就检查sums[n - 1][k]中是否包含(total_sum * k / n)。一旦发现符合条件的k,就返回true,否则就返回false。 // 在递推公式中我们发现,sums[i][j]仅仅和sums[i - 1][j],sums[i][j - 1]有关,所以可以进一步将空间复杂度从O(n^2*M)降低到O(n*M),其中M是n中的所有元素的组合数(可能高达O(2^n))。时间复杂度为O(n^3*M)。 // public boolean splitArraySameAverage(int[] nums) { // int n = nums.length; // int m = n / 2; // int sum = Arrays.stream(nums).sum(); // boolean poss = false; // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0) { // poss = true; // break; // } // } // if (!poss) return false; // List<Set<Integer>> ls = new ArrayList<>(); // for (int i = 0; i <= m; i++) // ls.add(new HashSet<Integer>()); // ls.get(0).add(0); // 这种构建子序列和的方法,要学习一下 // for (int v : nums) { // for each element in A, we try to add it to sums[i] by joining sums[i - 1] // for (int i = m; i >= 1; i--) // for (int t : ls.get(i-1)) // ls.get(i).add(t + v); // } // for (int i = 1; i <= m; i++) { // if (sum * i % n == 0 && ls.get(i).contains(sum * i / n)) // return true; // } // return false; // } // public int numSquares(int n) { // int [] dp = new int [n+1]; // Arrays.fill(dp, n+1); // dp[0] = 0; // for (int i = 1; i <= n; i++) { // for (int j = 1; j*j <= n; j++) // if (i - j*j >= 0) dp[i] = Math.min(dp[i], dp[i-j*j] + 1); // } // return dp[n]; // } // public int coinChange(int[] coins, int amount) { // if (amount == 0) return 0; // int n = coins.length; // int [] dp = new int [amount + 1]; // Arrays.sort(coins); // Arrays.fill(dp, amount + 1); // dp[0] = 0; // for (int i = 0; i <= amount; i++) { // for (int v : coins) { // if (i - v < 0) continue; // dp[i] = Math.min(dp[i], dp[i-v] + 1); // } // } // return dp[amount] == amount + 1 ? -1 : dp[amount]; // } // public int change(int target, int[] nums) { // int[] dp = new int[target + 1]; // // 初始化dp[0]为1 // dp[0] = 1; // // 循环数组中所有数字 // for (int val : nums) { // for (int i = 0; i <= target - val; i++) { // // dp[i]大于0说明,存在dp[i]种组合,其和为i的可能性 // if (dp[i] > 0) { // // 既然存在和为i的可能,那么i加上当前数字的和也是存在的 // dp[i + val] += dp[i]; // } // } // } // return dp[target]; // } // public int backPackIII(int[] A, int[] V, int m) { // int n = A.length; // int [] dp = new int[m+1]; // for (int i = 1; i <= m; i++) { // for (int j = 0; j < n; j++) { // if (i - A[j] >= 0) // dp[i] = Math.max(dp[i], dp[i-A[j]] + V[j]); // } // } // return dp[m]; // } // public int lastStoneWeightII(int[] stones) { // int n = stones.length; // int sum = Arrays.stream(stones).sum(); // boolean[] dp = new boolean[sum+1]; // dp[0] = true; // sum = 0; // for (int v : stones) { // sum += v; // for (int i = sum; i >= v; i--) // if (dp[i-v]) dp[i] = true; // } // for (int i = sum/2; i >= 0; i--) // if (dp[i]) return sum - i * 2; // return 0; // } // public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { // int m = baseCosts.length; // 还有bug, 暂时不想再改这个题目了 // int n = toppingCosts.length; // if (m == 1 && target < baseCosts[0]) return baseCosts[0]; // 不喜欢处理这种特殊情况 // Arrays.sort(toppingCosts); // int [] des = IntStream.rangeClosed(0, n-1).map(z->toppingCosts[n-1-z]).toArray(); // boolean [] dp = new boolean [target + 1]; // int cur = 0; // dp[0] = true; // for (int i = 0; i < m; i++) { // cur = baseCosts[i]; // if (cur <= target) // dp[cur] = true; // } // for (int i = 0; i < n; i++) { // int v = toppingCosts[i]; // for (int j = target; j > 0; j--) { // if (!dp[j]) continue; // if (j + v + v <= target) // dp[j+v+v] = true; // if (j + v <= target) // dp[j+v] = true; // } // } // for (int i = target; i > 0; i--) // if (dp[i]) return i; // return -1; // } // private void helper(int [] arr, int target, int cur, int idx) { // if (Math.abs(cur - target) < Math.abs(res - target) || Math.abs(cur - target) == Math.abs(res - target) && cur < res) // res = cur; // if (idx == arr.length) return; // helper(arr, target, cur, idx+1); // helper(arr, target, cur + arr[idx], idx+1); // helper(arr, target, cur + arr[idx]*2, idx+1); // } // int res = Integer.MAX_VALUE; // public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { // for (int v : baseCosts) // helper(toppingCosts, target, v, 0); // return res; // } // private int dfs(int [] arr, int [] mi, int i, int j, int cnt) { // if (cnt >= mi.length) return 0; // if (cache.containsKey(i) && cache.get(i).containsKey(j)) return cache.get(i).get(j); // int res = Math.max( // mi[cnt] * arr[i] + dfs(arr, mi, i+1, j, cnt+1), // mi[cnt] * arr[j] + dfs(arr, mi, i, j-1, cnt+1)); // if (!cache.containsKey(i)) cache.put(i, new HashMap<Integer, Integer>()); // cache.get(i).put(j, res); // return res; // } // Map<Integer, Map<Integer, Integer>> cache = new HashMap<>(); // public int maximumScore(int[] nums, int[] multipliers) { // return dfs(nums, multipliers, 0, nums.length-1, 0); // } // public int maximumScore(int[] arr, int[] multipliers) { // int n = arr.length; // int m = multipliers.length; // if (n == 1) return arr[0] * multipliers[0]; // int [] dp = new int [n]; // the max product if get i vals from left side // Arrays.fill(dp, Integer.MIN_VALUE); // dp[0] = arr[n-1] * multipliers[0]; // dp[1] = arr[0] * multipliers[0]; // for (int o = 1; o < m; o++) { // if (o + 1 < n) // dp[o+1] = dp[o] + arr[o] * multipliers[o]; // for (int i = o; i > 0; i--) // dp[i] = Math.max(dp[i-1] + arr[i-1] * multipliers[o], dp[i] + arr[n-(o-i)-1] * multipliers[o]); // dp[0] = dp[0] + arr[n - o - 1] * multipliers[o]; // } // int max = Integer.MIN_VALUE; // for (int i = 0; i < n; i++) // max = Math.max(dp[i], max); // return max; // } // 定义二维数组dp[m + 1][m + 1]。dp[i][j]:表示nums数组中前i个数和后j个数组成的最大分数。 // base case: // dp[0][0] = 0; // dp[i][0]:此状态表示nums数组中前i个数和后0个数组成的最大分数,此状态只可能由dp[i - 1][0]转移得到。 // dp[0][j]:此状态表示nums数组中前0个数和后j个数组成的最大分数,此状态只可能由dp[0][j - 1]转移得到。 // dp[i][j]:该状态表示nums数组中前i个数和后j个数组成的最大分数,可能由状态 // dp[i - 1][j]和状态dp[i][j - 1]转移得到,取其中得分最大的一个。 // 遍历所有可能的组合(满足i + j = m)获得最大得分。 // public int maximumScore(int[] arr, int[] multipliers) { // 这里有个bug暂时不想改了,但思路清晰 // int n = arr.length; // int m = multipliers.length; // if (n == 1) return arr[0] * multipliers[0]; // int [][] dp = new int [m+1][m+1]; // for (int i = 1; i <= m; i++) // dp[i][0] = dp[i-1][0] + arr[i-1]*multipliers[i-1]; // for (int i = 1; i <= m; i++) // dp[0][i] = dp[i-1][0] + arr[n-i]*multipliers[i-1]; // for (int i = 1; i <= m; i++) // for (int j = 1; j <= m; j++) // if (i + j <= m) // dp[i][j] = Math.max(dp[i-1][j] + arr[i-1]*multipliers[i+j-1], dp[i][j-1] + arr[n-j]*multipliers[i+j-1]); // int max = Integer.MIN_VALUE; // for (int i = 0; i <= m; i++) // max = Math.max(max, dp[i][m-i]); // return max; // } // // https://blog.csdn.net/luke2834/article/details/89457888 // 这个题目要多写几遍 // public int tallestBillboard(int[] rods) { // 写得好神奇呀 // int n = rods.length; // int sum = Arrays.stream(rods).sum(); // System.out.println("sum: " + sum); // int [][] dp = new int [2][(sum + 1) << 1]; // (sum + 1) * 2 // for (int i = 0; i < 2; i++) // Arrays.fill(dp[i], -1); // dp[0][sum] = 0; // for (int i = 0; i < n; i++) { // int cur = i & 1, next = (i & 1) ^ 1; // 相当于是滚动数组: [0, 1] // for (int j = 0; j < dp[cur].length; j++) { // if (dp[cur][j] == -1) continue; // dp[next][j] = Math.max(dp[cur][j], dp[next][j]); // update to max // dp[next][j+rods[i]] = Math.max(dp[next][j+rods[i]], dp[cur][j] + rods[i]); // dp[next][j-rods[i]] = Math.max(dp[next][j-rods[i]], dp[cur][j] + rods[i]); // } // } // return dp[rods.length & 1][sum] >> 1; // dp[n&1][sum] / 2 // } // // 1. 所有的状态全集:dp[len][sum+1], len = length of array, sum = sum of the array,代表两边共有的高度 // // 2. state transfer: // // a. 忽略当前 dp[i][j] = max(dp[i-1][j], dp[i][j]) // // b. 加入到higher一侧 dp[i][j+h] = max(dp[i][j+h], dp[i-1][j]) // // c. 加入到lower一侧 lower = abs(j-h); dp[i][lower] = max(dp[i][lower], dp[i][j] + min(j, h)); 其中min(j,h)为新增高度 // private void dfs(int [] arr, int idx) { // int cur = arr[idx]; // if (dp[idx][cur] != -1) return; // if (idx == 0) { // dp[idx][cur] = 0; // add // dp[idx][0] = 0; // ignore // return; // } // dfs(arr, idx-1); // int lower = 0; // for (int i = 0; i < dp[idx].length-cur; i++) { // if (dp[idx-1][i] < 0) continue; // dp[idx][i] = Math.max(dp[idx][i], dp[idx-1][i]); // 1: ignore // dp[idx][i+cur] = Math.max(dp[idx][i+cur], dp[idx-1][i]); // 2: add to higher // lower = Math.abs(i - cur); //3. add to lower // dp[idx][lower] = Math.max(dp[idx][lower], dp[idx-1][i] + Math.min(i, cur)); // } // } // int [][] dp; // int n; // public int tallestBillboard(int[] rods) { // int n = rods.length; // int sum = Arrays.stream(rods).sum(); // dp = new int [n][sum+1]; // for (int i = 0; i < n; i++) // Arrays.fill(dp[i], -1); // dfs(rods, n-1); // return dp[n-1][0]; // } // 定义一个数对键值:(i,j):i表示两个子序列的累加和差值的绝对值,j表示这个差值下,子序列中累加和的最大值,定义一个dp的map存放前m个数的所有子序列的累加和之差和对应的累加和最大值:比如:[1,2,3,4,5], 累加和为15,[7,8,9],累加和为24,两者差值为9,那么用(9,24) // 新建一个HashMap temp用于存放第m个数对之前子序列累加和只差的状态转移结果 // 对于新到来的rod,只能够有3中情况: // 1.rod不加入任何列表: // 从dp中拿出每个子序列的差值k的累加和最大值v1,每个结果与temp中相应k的累加和最大值v2比较,如果v1>v2,那么更新temp中k对应的最大累加和为v1 // 2.rod加入累加和较大的序列 // 从dp中拿出每个子序列的差值k的累加和最大值v1,并加上rod,这时差值变成k + rod,累加和最大值变成v1+ rod, 每个结果与temp中相应k + rod的累加和最大值v2比较,如果v1 + rod > v2,那么更新temp中k对应的最大累加和为v1+rod // 3.rod加入累加和较小的序列 // 从dp中拿出每个子序列的差值k的累加和最大值v1,累加和较小的子序列加上了rod,那么和累加和较大的子序列之差为k-rod,k-rod为负数时,说明累加和较小数组超越了累加和较大的数组,为非负数时,说明较大累加和的数组不变,因此当前累加和最大值为x = Max(v, v - (k - rod)), 然后再和temp中序列差为abs(k-rod)的最大累加和v2比较,如果x>v2则更新temp中abs(k-rod)为x; // public int tallestBillboard(int[] rods) { // int n = rods.length; // Map<Integer, Integer> dp = new HashMap<>(); // dp.put(0, 0); // for (int rod : rods) { // System.out.println("\nrod: " + rod); // Map<Integer, Integer> tmp = new HashMap<>(); // dp.forEach((k, v) -> { // if (tmp.getOrDefault(k, -1) < v) tmp.put(k, v); // if (tmp.getOrDefault(k+rod, -1) < v+rod) tmp.put(k + rod, v+rod); // int dis = k - rod; // int larger = Math.max(v, v-dis); // dis = Math.abs(dis); // if (tmp.getOrDefault(dis, -1) < larger) tmp.put(dis, larger); // }); // dp = tmp; // } // return dp.get(0); // } } public static void main(String[] args) { Solution s = new Solution(); int [] a = new int [] {1, 2, 3}; int r = s.tallestBillboard(a); System.out.println("r: " + r); } }
48,290
0.378986
0.3606
1,012
42.694664
27.616957
323
false
false
0
0
0
0
0
0
1.011858
false
false
15
92c750f56192841e73eff4d69402d622f9da17df
31,653,908,997,777
ca004041aeb1b65df7b29245fc416820093290cd
/christ/Ability.java
f5e4c2f0957ce7600d1fbf7f43af8250d86ea3c0
[]
no_license
MrDDom23/cswork
https://github.com/MrDDom23/cswork
79b3d4d81a9d9609de89675ee91a1f3bd7f136bf
d8e21bc849794b4132b9056fc8199f2f0bf43c52
refs/heads/master
2015-08-19T17:50:05.751000
2015-01-20T22:07:17
2015-01-20T22:07:17
29,553,268
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Ability { private String abilityName; private String abilityDescription; private int unlockLvl; private int cost; private boolean target; //true = you private int cooldown; public Ability(String abilityName, String abilityDescription, int unlockLvl, int cost, boolean target, int cooldown) { this.abilityName = abilityName; this.abilityDescription = abilityDescription; this.unlockLvl = unlockLvl; this.cost = cost; this.target = target; this.cooldown = cooldown; } public String toString() { String s = ""; if(target) { s = "you"; } else { s = "the enemy"; } return "\n" + this.abilityName + "\n" + "Description: " + this.abilityDescription + "\n" + "Unlocks at lvl " + this.unlockLvl + ", costs " + this.cost + ", targets " + s + ", and takes " + this.cooldown + " turn(s) to recharge." + "\n"; } public String getAbilityName() { return this.abilityName; } public String getAbilityDescription() { return this.abilityDescription; } public int getUnlockLvl() { return this.unlockLvl; } public int getCost() { return this.cost; } public boolean getTarget() { return this.target; } }
UTF-8
Java
1,192
java
Ability.java
Java
[]
null
[]
public class Ability { private String abilityName; private String abilityDescription; private int unlockLvl; private int cost; private boolean target; //true = you private int cooldown; public Ability(String abilityName, String abilityDescription, int unlockLvl, int cost, boolean target, int cooldown) { this.abilityName = abilityName; this.abilityDescription = abilityDescription; this.unlockLvl = unlockLvl; this.cost = cost; this.target = target; this.cooldown = cooldown; } public String toString() { String s = ""; if(target) { s = "you"; } else { s = "the enemy"; } return "\n" + this.abilityName + "\n" + "Description: " + this.abilityDescription + "\n" + "Unlocks at lvl " + this.unlockLvl + ", costs " + this.cost + ", targets " + s + ", and takes " + this.cooldown + " turn(s) to recharge." + "\n"; } public String getAbilityName() { return this.abilityName; } public String getAbilityDescription() { return this.abilityDescription; } public int getUnlockLvl() { return this.unlockLvl; } public int getCost() { return this.cost; } public boolean getTarget() { return this.target; } }
1,192
0.663591
0.663591
62
18.225807
25.188591
147
false
false
0
0
0
0
0
0
1.870968
false
false
15
87b51d9b620078014e44f7b5007ef8b5d8b77c87
7,859,790,207,038
0d79c6e684aa522cfef402655f96c235254e74df
/src/main/java/Home.java
42667d4f1d1358733c37b79e761915f5b7eb6297
[]
no_license
Manqasana-Lepota/AnimalProjectPart2
https://github.com/Manqasana-Lepota/AnimalProjectPart2
834092262d42ae3237c00a8c356beee694ec7250
ead9c96534d24641020375370a431267195529d8
refs/heads/master
2021-01-03T05:48:54.960000
2020-02-12T07:40:30
2020-02-12T07:40:30
239,948,836
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; public class Home { //creating object of array list ArrayList<Animal> list = new ArrayList<Animal>(); public void adoptPet(Animal animal) { list.add(animal);//Adding the animal to the list } public void makeAllSounds() { //Displaying for (Animal animal : list) { animal.sound(); } } }
UTF-8
Java
390
java
Home.java
Java
[]
null
[]
import java.util.ArrayList; public class Home { //creating object of array list ArrayList<Animal> list = new ArrayList<Animal>(); public void adoptPet(Animal animal) { list.add(animal);//Adding the animal to the list } public void makeAllSounds() { //Displaying for (Animal animal : list) { animal.sound(); } } }
390
0.589744
0.589744
23
15.956522
18.333809
56
false
false
0
0
0
0
0
0
0.173913
false
false
15
f0b0b26113c130985beba17a9d5146dda43a6769
7,859,790,208,945
539101c20542a3ece7e4c8776f93c657c3e6eaf4
/src/com/nathan/funGame/collision/CollisionEvent.java
27fd6fbf4bc80a58837dfe775adc430c3952eda4
[]
no_license
AaronStaar/Super-Awesome-RPG
https://github.com/AaronStaar/Super-Awesome-RPG
0b04847e2d7182fe13bfe096eb4a9f16510e7c34
fa8c77efb124a37788e2862410a3b846d6762b02
refs/heads/master
2021-01-10T20:29:03.098000
2015-07-03T17:28:13
2015-07-03T17:28:13
38,001,510
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nathan.funGame.collision; import com.nathan.funGame.events.Event; public class CollisionEvent extends Event{ public CollisionEvent(Object collider) { super("CollisionEvent", new Object[] {collider}); } }
UTF-8
Java
234
java
CollisionEvent.java
Java
[]
null
[]
package com.nathan.funGame.collision; import com.nathan.funGame.events.Event; public class CollisionEvent extends Event{ public CollisionEvent(Object collider) { super("CollisionEvent", new Object[] {collider}); } }
234
0.735043
0.735043
10
21.4
20.886358
51
false
false
0
0
0
0
0
0
0.9
false
false
15
3e2f571afa9515809c5ef0ca8bed14c953677fbb
23,656,679,872,705
00a8d0f14a7e408052609e03ec280fe5bb896de1
/src/Store.java
e0dac32b35ec0531a3d425302bbdd851acaf0186
[]
no_license
PhamTuandz/Java-book
https://github.com/PhamTuandz/Java-book
a6e6be4240a091773e481bb8a5a573e732a2eeab
550a7c47fafd02a2c860c9173a65de5ee141f821
refs/heads/master
2021-01-02T17:01:03.919000
2020-02-11T08:34:49
2020-02-11T08:34:49
239,712,589
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Store { private static int totalItems = 0; private final int MAX_ITEMS = 50; private Book[] listItems = null; public Store () { listItems = new Book[MAX_ITEMS]; } public boolean checkFull() { if(totalItems == MAX_ITEMS) { return true; } return false; } public boolean checkEmpty() { if(totalItems == 0) { return true; } return false; } public int getItemPosition(String bookID) { for(int i = 0; i < totalItems; i++) { if(bookID.equals(listItems[i].getID()) == true){ return i; } } return -1; } public void add(Book bookObj) { if(this.checkFull()== false) { this.listItems[totalItems] = bookObj; this.totalItems++; System.out.println("Add successfull"); }else { System.out.println("Store if full!"); } } public void list() { if(this.checkEmpty() == false) { for(int i = 0; i < totalItems; i++) { this.listItems[i].showInfo(); } }else { System.out.println("Store is Empty!"); } } public void find(String bookID) { int bookPosition = this.getItemPosition(bookID); if(bookPosition == -1) { System.out.println("This book is not exist!"); }else { listItems[bookPosition].showInfo(); } } }
UTF-8
Java
1,209
java
Store.java
Java
[]
null
[]
public class Store { private static int totalItems = 0; private final int MAX_ITEMS = 50; private Book[] listItems = null; public Store () { listItems = new Book[MAX_ITEMS]; } public boolean checkFull() { if(totalItems == MAX_ITEMS) { return true; } return false; } public boolean checkEmpty() { if(totalItems == 0) { return true; } return false; } public int getItemPosition(String bookID) { for(int i = 0; i < totalItems; i++) { if(bookID.equals(listItems[i].getID()) == true){ return i; } } return -1; } public void add(Book bookObj) { if(this.checkFull()== false) { this.listItems[totalItems] = bookObj; this.totalItems++; System.out.println("Add successfull"); }else { System.out.println("Store if full!"); } } public void list() { if(this.checkEmpty() == false) { for(int i = 0; i < totalItems; i++) { this.listItems[i].showInfo(); } }else { System.out.println("Store is Empty!"); } } public void find(String bookID) { int bookPosition = this.getItemPosition(bookID); if(bookPosition == -1) { System.out.println("This book is not exist!"); }else { listItems[bookPosition].showInfo(); } } }
1,209
0.62531
0.618693
57
20.192982
15.944464
51
false
false
0
0
0
0
0
0
2.315789
false
false
15
3e2fca07adc88a27ef980ff77308d5734b5a2db1
24,893,630,484,952
cbd076eb1d0fc1f362fbbad7a8393e751b98d347
/Mall-master/ManagerSite/src/main/java/com/xmg/mall/web/controller/product/ProductController.java
ff61e812005fe8ebac23ae7e1fe27ae25b1d26a0
[]
no_license
yang18259445022/yangdingjun
https://github.com/yang18259445022/yangdingjun
a898015ce7b4ff62c85c8576bc6879bbd32c5bf8
74ca26229042f74e504df6bd61b83c646977c9f0
refs/heads/master
2020-06-26T16:45:39.529000
2016-11-23T07:29:36
2016-11-23T07:29:36
74,548,407
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xmg.mall.web.controller.product; import com.xmg.mall.base.query.Pagination; import com.xmg.mall.base.query.PaginationUtil; import com.xmg.mall.product.qo.ProductQuery; import com.xmg.mall.product.service.CatalogService; import com.xmg.mall.product.service.ProductService; import com.xmg.mall.product.vo.ExtendedProduct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by lony on 2016/11/9. */ @Controller("productController") @RequestMapping("/product") public class ProductController { private ProductService productService; @Autowired public void setProductService(ProductService productService) { this.productService = productService; } @RequestMapping("/page") public String page(Model model) { return "product/product"; } @RequestMapping("/list") public String list(@ModelAttribute("qo")ProductQuery qo, Model model) { Pagination<ExtendedProduct> pagination = productService.queryProducts(qo); model.addAttribute("pagination", pagination); model.addAttribute("pages", PaginationUtil.getPages(pagination.getRows(), qo.getPageSize())); return "product/product_list"; } @RequestMapping("/toSaveOrUpdate") public String toSaveOrUpdate(Model model) { return "product/product_add_or_update"; } }
UTF-8
Java
1,568
java
ProductController.java
Java
[ { "context": "bind.annotation.RequestMapping;\n\n/**\n * Created by lony on 2016/11/9.\n */\n@Controller(\"productController\"", "end": 632, "score": 0.9950945973396301, "start": 628, "tag": "USERNAME", "value": "lony" } ]
null
[]
package com.xmg.mall.web.controller.product; import com.xmg.mall.base.query.Pagination; import com.xmg.mall.base.query.PaginationUtil; import com.xmg.mall.product.qo.ProductQuery; import com.xmg.mall.product.service.CatalogService; import com.xmg.mall.product.service.ProductService; import com.xmg.mall.product.vo.ExtendedProduct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by lony on 2016/11/9. */ @Controller("productController") @RequestMapping("/product") public class ProductController { private ProductService productService; @Autowired public void setProductService(ProductService productService) { this.productService = productService; } @RequestMapping("/page") public String page(Model model) { return "product/product"; } @RequestMapping("/list") public String list(@ModelAttribute("qo")ProductQuery qo, Model model) { Pagination<ExtendedProduct> pagination = productService.queryProducts(qo); model.addAttribute("pagination", pagination); model.addAttribute("pages", PaginationUtil.getPages(pagination.getRows(), qo.getPageSize())); return "product/product_list"; } @RequestMapping("/toSaveOrUpdate") public String toSaveOrUpdate(Model model) { return "product/product_add_or_update"; } }
1,568
0.750638
0.746173
48
31.666666
25.499454
101
false
false
0
0
0
0
0
0
0.5
false
false
15
896229a03f95bb5e99c1608b11c0ab98d8721b53
10,608,569,267,606
387a08f1f254c28d496fd04720a99335d944a2e3
/src/main/java/com/github/benziko/portunes/encrypter/bytes/ByteEncrypter.java
3d2853c3cccb70ebc4fa08f519e1061b95060cc7
[ "MIT" ]
permissive
IkoroVictor/portunes-spring
https://github.com/IkoroVictor/portunes-spring
4a358d51db9a4c5a70154421e54b591a49a07b71
1cf8026a7ec2c5eddd1474b558396df1258dbc50
refs/heads/master
2020-01-13T02:21:44.047000
2017-04-06T06:19:04
2017-04-06T06:19:04
81,587,438
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.benziko.portunes.encrypter.bytes; import com.github.benziko.portunes.encrypter.Encrypter; /** * @author Victor Ikoro on 2/10/2017. */ public interface ByteEncrypter extends Encrypter<byte[], byte[]> { byte[] encrypt(byte[] value) throws Exception; byte[] decrypt(byte[] value) throws Exception; }
UTF-8
Java
330
java
ByteEncrypter.java
Java
[ { "context": "ziko.portunes.encrypter.Encrypter;\n\n/**\n * @author Victor Ikoro on 2/10/2017.\n */\npublic interface ByteEncrypter ", "end": 138, "score": 0.9998877644538879, "start": 126, "tag": "NAME", "value": "Victor Ikoro" } ]
null
[]
package com.github.benziko.portunes.encrypter.bytes; import com.github.benziko.portunes.encrypter.Encrypter; /** * @author <NAME> on 2/10/2017. */ public interface ByteEncrypter extends Encrypter<byte[], byte[]> { byte[] encrypt(byte[] value) throws Exception; byte[] decrypt(byte[] value) throws Exception; }
324
0.730303
0.709091
13
24.384615
25.93346
66
false
false
0
0
0
0
0
0
0.384615
false
false
15
a2eebe82a78438c41a19ca05913a48f2ba2037a4
37,417,755,099,423
19ef319a75c323f0ee775bbbe3c23dbb1aa28a2a
/src/ust/cytangah/coursecat/TitleTabBookmarksActivity.java
408a7fb919738f71b102937dfb56668a3525885d
[]
no_license
roytang121/hkust_coursecat
https://github.com/roytang121/hkust_coursecat
84007121842ce3e596103fb0c4aa6a3b8a842b87
a0d21a2cb9fcac3fbbc4ca1697ff2f2f8e49f7bd
refs/heads/master
2021-01-19T18:10:39.706000
2013-10-16T06:51:13
2013-10-16T06:51:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ust.cytangah.coursecat; import ust.cytangah.coursecat.MyEnrolledFragment.DownloadEnrolledCourseTask; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.viewpagerindicator.PageIndicator; import com.viewpagerindicator.TitlePageIndicator; public class TitleTabBookmarksActivity extends SherlockFragmentActivity { private Context c; private ViewPager mPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_title_tab_bookmarks); this.c = this; ActionBar actionbar = this.getSupportActionBar(); actionbar.setDisplayShowTitleEnabled(false); //actionbar.setDisplayShowHomeEnabled(false); BookmarkFragmentAdapter mAdapter; PageIndicator mIndicator; mAdapter = new BookmarkFragmentAdapter(this.getSupportFragmentManager()); mPager = (ViewPager)this.findViewById(R.id.pager); mPager.setAdapter(mAdapter); mIndicator = (TitlePageIndicator)this.findViewById(R.id.indicator); mIndicator.setViewPager(mPager); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.activity_title_tab_bookmarks, menu); menu.add(0, 0, 100, "Update") .setIcon(R.drawable.ic_action_refresh) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add(0, 1, 300, "Account") .setIcon(android.R.drawable.ic_menu_preferences) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add(0, 2, 200, "Calendar") .setIcon(android.R.drawable.ic_menu_my_calendar) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case 0: SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(c); SharedPreferences.Editor editor = pref.edit(); editor.remove("enrollhtml"); editor.commit(); Toast.makeText(this, "Reopen bookmarks to update", Toast.LENGTH_SHORT).show(); break; case 1: //Toast.makeText(TitleTabBookmarksActivity.this, "Not yet Available", Toast.LENGTH_SHORT).show(); AccoutInfoHelper.showdialog(c); break; case 2: Intent i_2 = new Intent(TitleTabBookmarksActivity.this, MyCalendarActivity.class); startActivity(i_2); break; } return true; } class BookmarkFragmentAdapter extends FragmentPagerAdapter{ protected String[] CONTENT = new String[]{"Bookmarks", "Enrolled"}; private int mCount = CONTENT.length; public BookmarkFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch(position % CONTENT.length){ case 0: return MyListFragment.newInstance(); case 1: return MyEnrolledFragment.newInstance(); default: return null; } } @Override public int getCount() { // TODO Auto-generated method stub return mCount; } @Override public CharSequence getPageTitle(int position) { return CONTENT[position % CONTENT.length]; } } }
UTF-8
Java
3,730
java
TitleTabBookmarksActivity.java
Java
[]
null
[]
package ust.cytangah.coursecat; import ust.cytangah.coursecat.MyEnrolledFragment.DownloadEnrolledCourseTask; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.viewpagerindicator.PageIndicator; import com.viewpagerindicator.TitlePageIndicator; public class TitleTabBookmarksActivity extends SherlockFragmentActivity { private Context c; private ViewPager mPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_title_tab_bookmarks); this.c = this; ActionBar actionbar = this.getSupportActionBar(); actionbar.setDisplayShowTitleEnabled(false); //actionbar.setDisplayShowHomeEnabled(false); BookmarkFragmentAdapter mAdapter; PageIndicator mIndicator; mAdapter = new BookmarkFragmentAdapter(this.getSupportFragmentManager()); mPager = (ViewPager)this.findViewById(R.id.pager); mPager.setAdapter(mAdapter); mIndicator = (TitlePageIndicator)this.findViewById(R.id.indicator); mIndicator.setViewPager(mPager); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.activity_title_tab_bookmarks, menu); menu.add(0, 0, 100, "Update") .setIcon(R.drawable.ic_action_refresh) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add(0, 1, 300, "Account") .setIcon(android.R.drawable.ic_menu_preferences) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add(0, 2, 200, "Calendar") .setIcon(android.R.drawable.ic_menu_my_calendar) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case 0: SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(c); SharedPreferences.Editor editor = pref.edit(); editor.remove("enrollhtml"); editor.commit(); Toast.makeText(this, "Reopen bookmarks to update", Toast.LENGTH_SHORT).show(); break; case 1: //Toast.makeText(TitleTabBookmarksActivity.this, "Not yet Available", Toast.LENGTH_SHORT).show(); AccoutInfoHelper.showdialog(c); break; case 2: Intent i_2 = new Intent(TitleTabBookmarksActivity.this, MyCalendarActivity.class); startActivity(i_2); break; } return true; } class BookmarkFragmentAdapter extends FragmentPagerAdapter{ protected String[] CONTENT = new String[]{"Bookmarks", "Enrolled"}; private int mCount = CONTENT.length; public BookmarkFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch(position % CONTENT.length){ case 0: return MyListFragment.newInstance(); case 1: return MyEnrolledFragment.newInstance(); default: return null; } } @Override public int getCount() { // TODO Auto-generated method stub return mCount; } @Override public CharSequence getPageTitle(int position) { return CONTENT[position % CONTENT.length]; } } }
3,730
0.736729
0.729759
111
31.603603
23.923782
100
false
false
0
0
0
0
0
0
2.198198
false
false
15
e0ce8bdf19dffef7b07fc3a9507d60b2af40e853
34,265,249,134,865
12a54c8c033e24424ed5c92a02e6ae5a6f951d7b
/src/main/java/banking/TransferCommandValidator.java
c43b367c8e06231df37bd813e84b27bf28cfa977
[]
no_license
abhash8010/TDD-Banking-System
https://github.com/abhash8010/TDD-Banking-System
d2813d782d57dfea49c4de0f7c97a524af0d431c
1d4dcf492484e8d4d817fa25896f4742bff4ba1d
refs/heads/master
2023-05-10T14:24:02.386000
2021-06-10T03:46:59
2021-06-10T03:46:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package banking; import static banking.DepositCommandValidator.*; class TransferCommandValidator { private final Bank bank; private final CommandValidator validator; TransferCommandValidator(Bank bank) { this.bank = bank; validator = new CommandValidator(bank); } boolean validate(String[] commandArguments) { if (validateThatAccountExistsInBank(commandArguments, bank, 1) && validateThatAccountExistsInBank(commandArguments, bank, 2)) { if (commandArguments[1].equals(commandArguments[2])) { return false; } if (isReferencingCDAccount(commandArguments, bank, 1) || isReferencingCDAccount(commandArguments, bank, 2)) { return false; } return validateTransferConformsToDepositRules(commandArguments) && validateTransferConformsToWithdrawalRules(commandArguments); } return false; } private boolean validateTransferConformsToDepositRules(String[] commandArguments) { String accountIDToDepositTo = commandArguments[2]; String amountToTransfer = commandArguments[3]; return validator.validate(new String[]{"deposit", accountIDToDepositTo, amountToTransfer}); } private boolean validateTransferConformsToWithdrawalRules(String[] commandArguments) { String accountIDToWithdrawFrom = commandArguments[1]; String amountToTransfer = commandArguments[3]; return validator.validate(new String[]{"withdraw", accountIDToWithdrawFrom, amountToTransfer}); } }
UTF-8
Java
1,575
java
TransferCommandValidator.java
Java
[]
null
[]
package banking; import static banking.DepositCommandValidator.*; class TransferCommandValidator { private final Bank bank; private final CommandValidator validator; TransferCommandValidator(Bank bank) { this.bank = bank; validator = new CommandValidator(bank); } boolean validate(String[] commandArguments) { if (validateThatAccountExistsInBank(commandArguments, bank, 1) && validateThatAccountExistsInBank(commandArguments, bank, 2)) { if (commandArguments[1].equals(commandArguments[2])) { return false; } if (isReferencingCDAccount(commandArguments, bank, 1) || isReferencingCDAccount(commandArguments, bank, 2)) { return false; } return validateTransferConformsToDepositRules(commandArguments) && validateTransferConformsToWithdrawalRules(commandArguments); } return false; } private boolean validateTransferConformsToDepositRules(String[] commandArguments) { String accountIDToDepositTo = commandArguments[2]; String amountToTransfer = commandArguments[3]; return validator.validate(new String[]{"deposit", accountIDToDepositTo, amountToTransfer}); } private boolean validateTransferConformsToWithdrawalRules(String[] commandArguments) { String accountIDToWithdrawFrom = commandArguments[1]; String amountToTransfer = commandArguments[3]; return validator.validate(new String[]{"withdraw", accountIDToWithdrawFrom, amountToTransfer}); } }
1,575
0.706667
0.700317
42
36.5
39.501808
139
false
false
0
0
0
0
0
0
0.714286
false
false
15
bbff891b0815ad306c787892f574c3d3e3005221
34,729,105,602,159
bf59e68d6ef729dc8a8cb72abff6e7692d57830e
/tex/SendEncrData-excerpt2.java
d011454d6eb1415e6eda311b642978fe849933f7
[]
no_license
ShurayukiHime/StickyPolicies
https://github.com/ShurayukiHime/StickyPolicies
764954bd51a61111fa9d41d3d499a3bf9b2475b9
8620936f470f9ebe338a723b9963ad82cbbd1c51
refs/heads/master
2021-09-12T01:59:29.899000
2018-04-13T12:39:06
2018-04-13T12:39:06
86,911,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
byte[] pii; byte[] encrPiiAndIV = new byte[0]; byte[] keyAndHashEncrypted = new byte[0]; byte[] signedEncrKeyAndHash = new byte[0]; try { // 1) obtain policy: obtained in Bundle // 2) generate symmetric disposable encryption key byte[] encodedSymmetricKey = CryptoUtils.generateSymmetricRandomKey(); byte[] initializationVec = CryptoUtils.generateSecureIV(); // 3) encrypt PII byte[] encryptedPii = CryptoUtils.encrDecrSymmetric(Cipher.ENCRYPT_MODE, encodedSymmetricKey, initializationVec, pii); // 4) hash policy byte[] policyDigest = CryptoUtils.calculateDigest(policy.getBytes(Charset.forName("UTF-8"))); // 5) append policy and digest, encrypt with PubTa ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write(encodedSymmetricKey); byteArrayOutputStream.write(policyDigest); keyAndHashEncrypted = CryptoUtils.encryptAsymmetric(taPublicKey, byteArrayOutputStream.toByteArray()); // 6) sign signedEncrKeyAndHash = CryptoUtils.sign(keyAndHashEncrypted); encrPiiAndIV = new byte[initializationVec.length + encryptedPii.length]; System.arraycopy(encryptedPii, 0, encrPiiAndIV, 0, encryptedPii.length); System.arraycopy(initializationVec, 0, encrPiiAndIV, encryptedPii.length, initializationVec.length); } catch (Exception e) { e.printStackTrace(); mSearchResultsTextView.setText("Sorry, some errors happened while encrypting your data.\nDon't worry, your privacy is still safe!\nPlease try again later."); }
UTF-8
Java
1,477
java
SendEncrData-excerpt2.java
Java
[]
null
[]
byte[] pii; byte[] encrPiiAndIV = new byte[0]; byte[] keyAndHashEncrypted = new byte[0]; byte[] signedEncrKeyAndHash = new byte[0]; try { // 1) obtain policy: obtained in Bundle // 2) generate symmetric disposable encryption key byte[] encodedSymmetricKey = CryptoUtils.generateSymmetricRandomKey(); byte[] initializationVec = CryptoUtils.generateSecureIV(); // 3) encrypt PII byte[] encryptedPii = CryptoUtils.encrDecrSymmetric(Cipher.ENCRYPT_MODE, encodedSymmetricKey, initializationVec, pii); // 4) hash policy byte[] policyDigest = CryptoUtils.calculateDigest(policy.getBytes(Charset.forName("UTF-8"))); // 5) append policy and digest, encrypt with PubTa ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write(encodedSymmetricKey); byteArrayOutputStream.write(policyDigest); keyAndHashEncrypted = CryptoUtils.encryptAsymmetric(taPublicKey, byteArrayOutputStream.toByteArray()); // 6) sign signedEncrKeyAndHash = CryptoUtils.sign(keyAndHashEncrypted); encrPiiAndIV = new byte[initializationVec.length + encryptedPii.length]; System.arraycopy(encryptedPii, 0, encrPiiAndIV, 0, encryptedPii.length); System.arraycopy(initializationVec, 0, encrPiiAndIV, encryptedPii.length, initializationVec.length); } catch (Exception e) { e.printStackTrace(); mSearchResultsTextView.setText("Sorry, some errors happened while encrypting your data.\nDon't worry, your privacy is still safe!\nPlease try again later."); }
1,477
0.792146
0.783345
28
51.785713
37.830788
158
false
false
0
0
0
0
0
0
1.928571
false
false
15
f8cffb496352c4817b893ea0ab9d271ad2807215
35,493,609,776,921
d97672e88b7849f4f19a58576ffbedb77c917db0
/src/main/java/org/egg/model/DTO/LoginDto.java
e1f84db8862ba42f298ca2c652794deb7cebba24
[]
no_license
dataochen/feimaotui_boss
https://github.com/dataochen/feimaotui_boss
0c47fdfa855469310ed92c24bd41f3eaeb1c0af2
0d3277b35ed62cebd65fc290a6f998c4bd98a8d5
refs/heads/master
2020-12-05T23:56:26.949000
2020-05-21T09:19:28
2020-05-21T09:19:28
232,281,978
0
1
null
false
2021-01-28T03:26:00
2020-01-07T08:45:47
2021-01-28T03:08:16
2021-01-28T03:25:59
6,416
0
1
3
JavaScript
false
false
package org.egg.model.DTO; import lombok.Data; import javax.validation.constraints.NotBlank; import java.io.Serializable; /** * Created by chendatao on 2017/12/7. */ @Data public class LoginDto implements Serializable { @NotBlank private String loginName; @NotBlank private String pwd; private String wxMiniOpenId; private String wxOpenId; }
UTF-8
Java
371
java
LoginDto.java
Java
[ { "context": "k;\nimport java.io.Serializable;\n\n/**\n * Created by chendatao on 2017/12/7.\n */\n@Data\npublic class LoginDto imp", "end": 152, "score": 0.9996379613876343, "start": 143, "tag": "USERNAME", "value": "chendatao" } ]
null
[]
package org.egg.model.DTO; import lombok.Data; import javax.validation.constraints.NotBlank; import java.io.Serializable; /** * Created by chendatao on 2017/12/7. */ @Data public class LoginDto implements Serializable { @NotBlank private String loginName; @NotBlank private String pwd; private String wxMiniOpenId; private String wxOpenId; }
371
0.735849
0.716981
19
18.526316
15.325824
47
false
false
0
0
0
0
0
0
0.421053
false
false
15
ca9f6a7864ad2328a52f5f97e0166424af51af10
35,493,609,776,075
9adb7baf68690de3c22ce44b32000a4a5f407826
/src/main/java/com/activemq/TopicSender.java
eb3c6ec49ea9901dcc451b8dc3170709c4bd6997
[]
no_license
DHzhu/JavaMaven
https://github.com/DHzhu/JavaMaven
f61cbc2a493f01125622ff494e2abefd98dde13a
625a4bb878a9030eb701ee2130dc9e81dd30b3b3
refs/heads/master
2021-01-09T20:56:43.513000
2017-03-02T08:03:27
2017-03-02T08:03:27
62,523,719
1
0
null
false
2017-03-02T08:03:28
2016-07-04T01:43:24
2017-01-11T06:39:13
2017-03-02T08:03:28
78
0
0
0
Java
null
null
package com.activemq; import javax.jms.DeliveryMode; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; /** * @Name :TopicSender * @Desc :TODO * @author:zhu * @date :2016年7月12日 */ public class TopicSender { private final int SEND_NUM = 10; private final String BROKER_URL = "tcp://10.10.12.17:61616"; private final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER; private final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; private final String DESTINATION = "js.mq.topic"; public void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception { for (int i = 0; i < this.SEND_NUM; i++) { String message = "发送消息第" + (i + 1) + "条"; TextMessage textMessage = session.createTextMessage(message); System.out.println(textMessage.getText()); // 发送 Topic消息 publisher.send(textMessage); } } public void run() throws Exception { TopicConnection connection = null; TopicSession session = null; try { TopicConnectionFactory factory = new ActiveMQConnectionFactory(this.DEFAULT_USER, this.DEFAULT_PASSWORD, this.BROKER_URL); connection = factory.createTopicConnection(); connection.start(); session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(this.DESTINATION); TopicPublisher publisher = session.createPublisher(topic); publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); sendMessage(session, publisher); session.commit(); } catch (Exception e) { throw e; } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub TopicSender sender = new TopicSender(); sender.run(); } }
UTF-8
Java
2,197
java
TopicSender.java
Java
[ { "context": " * @Name :TopicSender\r\n * @Desc :TODO\r\n * @author:zhu\r\n * @date :2016年7月12日\r\n */\r\npublic class TopicSen", "end": 448, "score": 0.9990240335464478, "start": 445, "tag": "USERNAME", "value": "zhu" } ]
null
[]
package com.activemq; import javax.jms.DeliveryMode; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; /** * @Name :TopicSender * @Desc :TODO * @author:zhu * @date :2016年7月12日 */ public class TopicSender { private final int SEND_NUM = 10; private final String BROKER_URL = "tcp://10.10.12.17:61616"; private final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER; private final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; private final String DESTINATION = "js.mq.topic"; public void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception { for (int i = 0; i < this.SEND_NUM; i++) { String message = "发送消息第" + (i + 1) + "条"; TextMessage textMessage = session.createTextMessage(message); System.out.println(textMessage.getText()); // 发送 Topic消息 publisher.send(textMessage); } } public void run() throws Exception { TopicConnection connection = null; TopicSession session = null; try { TopicConnectionFactory factory = new ActiveMQConnectionFactory(this.DEFAULT_USER, this.DEFAULT_PASSWORD, this.BROKER_URL); connection = factory.createTopicConnection(); connection.start(); session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(this.DESTINATION); TopicPublisher publisher = session.createPublisher(topic); publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); sendMessage(session, publisher); session.commit(); } catch (Exception e) { throw e; } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub TopicSender sender = new TopicSender(); sender.run(); } }
2,197
0.709351
0.698296
76
26.56579
25.388214
125
false
false
0
0
0
0
0
0
1.855263
false
false
15
b1d1fa9f1678c4b1099daf614801cf7d0afd2de6
17,841,294,160,870
8d4a6f2538abd8169a5f4e91bfb62c0b828ee3c1
/workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/skill/HandCardAddSkillNormal.java
b64d4b7280f7748fe8a71aa0629251844ad30449
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
cfvbaibai/CardFantasy
https://github.com/cfvbaibai/CardFantasy
45d4fcfa043341df56a37db5c8a74e7b6ebf8fd9
f6bcfcfd5175da69da9450884cc93023d54be978
refs/heads/master
2022-12-21T06:01:56.447000
2020-03-03T11:31:25
2020-03-03T11:31:25
16,409,909
21
45
BSD-2-Clause
false
2022-12-16T06:12:10
2014-01-31T14:19:57
2021-12-20T09:56:42
2022-12-16T06:12:07
268,866
19
36
7
Java
false
false
package cfvbaibai.cardfantasy.engine.skill; import cfvbaibai.cardfantasy.CardFantasyRuntimeException; import cfvbaibai.cardfantasy.Randomizer; import cfvbaibai.cardfantasy.data.CardSkill; import cfvbaibai.cardfantasy.data.Skill; import cfvbaibai.cardfantasy.engine.SkillUseInfo; import cfvbaibai.cardfantasy.engine.SkillResolver; import cfvbaibai.cardfantasy.engine.CardInfo; import java.util.ArrayList; import java.util.List; public class HandCardAddSkillNormal { public static void apply(SkillResolver resolver, SkillUseInfo skillUseInfo, CardInfo card, Skill addSkill,int number) { if (card == null ) { return; } Skill skill = skillUseInfo.getSkill(); CardSkill cardSkill = new CardSkill(addSkill.getType(), addSkill.getLevel(), 0, false, false, false, false); resolver.getStage().getUI().useSkill(card, skill, true); List<CardInfo> allHandCards = card.getOwner().getHand().toList(); List<CardInfo> addCard=new ArrayList<CardInfo>(); List<CardInfo> revivableCards = new ArrayList<CardInfo>(); boolean flag = true; for (CardInfo handCard : allHandCards) { // for(SkillUseInfo skillInfo:handCard.getSkillUserInfos()) // { // if(skillInfo.getGiveSkill()==2) // { // flag=false; // break; // } // } // if(!flag) // { // flag =true; // continue; // } if (handCard != null && !handCard.containsAllSkill(addSkill.getType())) { revivableCards.add(handCard); } } if (revivableCards.isEmpty()) { return; } addCard = Randomizer.getRandomizer().pickRandom( revivableCards, number, true, null); for (CardInfo once : addCard) { if(once.containsAllSkill(addSkill.getType())) { continue; } SkillUseInfo thisSkillUserInfo= null; thisSkillUserInfo = new SkillUseInfo(once,cardSkill); thisSkillUserInfo.setGiveSkill(2); once.addSkill(thisSkillUserInfo); } } }
UTF-8
Java
2,243
java
HandCardAddSkillNormal.java
Java
[]
null
[]
package cfvbaibai.cardfantasy.engine.skill; import cfvbaibai.cardfantasy.CardFantasyRuntimeException; import cfvbaibai.cardfantasy.Randomizer; import cfvbaibai.cardfantasy.data.CardSkill; import cfvbaibai.cardfantasy.data.Skill; import cfvbaibai.cardfantasy.engine.SkillUseInfo; import cfvbaibai.cardfantasy.engine.SkillResolver; import cfvbaibai.cardfantasy.engine.CardInfo; import java.util.ArrayList; import java.util.List; public class HandCardAddSkillNormal { public static void apply(SkillResolver resolver, SkillUseInfo skillUseInfo, CardInfo card, Skill addSkill,int number) { if (card == null ) { return; } Skill skill = skillUseInfo.getSkill(); CardSkill cardSkill = new CardSkill(addSkill.getType(), addSkill.getLevel(), 0, false, false, false, false); resolver.getStage().getUI().useSkill(card, skill, true); List<CardInfo> allHandCards = card.getOwner().getHand().toList(); List<CardInfo> addCard=new ArrayList<CardInfo>(); List<CardInfo> revivableCards = new ArrayList<CardInfo>(); boolean flag = true; for (CardInfo handCard : allHandCards) { // for(SkillUseInfo skillInfo:handCard.getSkillUserInfos()) // { // if(skillInfo.getGiveSkill()==2) // { // flag=false; // break; // } // } // if(!flag) // { // flag =true; // continue; // } if (handCard != null && !handCard.containsAllSkill(addSkill.getType())) { revivableCards.add(handCard); } } if (revivableCards.isEmpty()) { return; } addCard = Randomizer.getRandomizer().pickRandom( revivableCards, number, true, null); for (CardInfo once : addCard) { if(once.containsAllSkill(addSkill.getType())) { continue; } SkillUseInfo thisSkillUserInfo= null; thisSkillUserInfo = new SkillUseInfo(once,cardSkill); thisSkillUserInfo.setGiveSkill(2); once.addSkill(thisSkillUserInfo); } } }
2,243
0.598306
0.596968
61
35.770493
25.779896
123
false
false
0
0
0
0
0
0
0.754098
false
false
15
681a3fad5a100ab846002842741a02c2af2bc5a3
29,016,799,054,638
6e4f44e1b28bf15b03289b15bdad452821647750
/src/main/java/dantakuti/games/manager/services/PlayerService.java
c146d0946a69fbf07032f098edbb70e3f695719a
[]
no_license
adarshbhattarai/leagueManagerServices
https://github.com/adarshbhattarai/leagueManagerServices
4ca8badabd7d9dea2eec073e6ccf60e9f944a4b7
f4061cc7cf73fa3b750e25bbcb219950523df712
refs/heads/master
2022-11-06T11:30:22.579000
2020-06-20T19:48:05
2020-06-20T19:48:05
270,376,368
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dantakuti.games.manager.services; import dantakuti.games.manager.entity.Game; import dantakuti.games.manager.entity.GameResult; import dantakuti.games.manager.entity.Player; import dantakuti.games.manager.model.PlayerModel; import java.util.Set; /** * @author adarshbhattarai on 2020-05-26 * @project LeagueManager */ public interface PlayerService { Player getPlayer(PlayerModel playerModel); Set<Player> getPlayers(PlayerModel[] players); void updatePlayerStat(Game game, Long groupId, GameResult previousResult); void addNewGameStat(Game game, long groupId); }
UTF-8
Java
598
java
PlayerService.java
Java
[ { "context": "layerModel;\n\nimport java.util.Set;\n\n/**\n * @author adarshbhattarai on 2020-05-26\n * @project LeagueManager\n *", "end": 280, "score": 0.833993673324585, "start": 272, "tag": "USERNAME", "value": "adarshbh" }, { "context": "l;\n\nimport java.util.Set;\n\n/**\n * @author adarshbhattarai on 2020-05-26\n * @project LeagueManager\n */\npubli", "end": 287, "score": 0.7149609923362732, "start": 280, "tag": "NAME", "value": "attarai" } ]
null
[]
package dantakuti.games.manager.services; import dantakuti.games.manager.entity.Game; import dantakuti.games.manager.entity.GameResult; import dantakuti.games.manager.entity.Player; import dantakuti.games.manager.model.PlayerModel; import java.util.Set; /** * @author adarshbhattarai on 2020-05-26 * @project LeagueManager */ public interface PlayerService { Player getPlayer(PlayerModel playerModel); Set<Player> getPlayers(PlayerModel[] players); void updatePlayerStat(Game game, Long groupId, GameResult previousResult); void addNewGameStat(Game game, long groupId); }
598
0.782609
0.769231
23
25
23.58334
78
false
false
0
0
0
0
0
0
0.565217
false
false
15
7ec9982353e444ef19b758a0a2aedac1fea04cdc
32,882,269,644,880
6a9e9de15b10c7f89b3b5859d28b14130f3d8cb0
/src/main/java/com/ne/automation/spring/ApplicationDependencyFactory.java
305bcf06cd952f502c5072711e1e86131ecba1a2
[]
no_license
TejaVaranasi/NeGoAutomationEngine
https://github.com/TejaVaranasi/NeGoAutomationEngine
1518745730af35b93b0b2ecaf87d03d8f87d2f3e
20902bd679f60cdbd9ed18b1e9e47e61f887d379
refs/heads/master
2017-11-02T03:35:26.034000
2017-07-08T10:50:21
2017-07-08T10:50:21
96,240,474
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ne.automation.spring; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.ne.automation.global.DatabaseProperties; @Configuration public class ApplicationDependencyFactory { @Autowired DatabaseProperties databaseProperties; @Bean public SchedulerFactory getSchedulerFactory() { return new StdSchedulerFactory(); } @Bean public ComboPooledDataSource getComboPooledDataSource() { System.out.println("Inside bean creation : " + databaseProperties.MYSQL_DB_URL); ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setJdbcUrl(databaseProperties.MYSQL_DB_URL); cpds.setUser(databaseProperties.MYSQL_DB_USER_NAME); cpds.setPassword(databaseProperties.MYSQL_DB_PASSWORD); cpds.setAcquireIncrement(databaseProperties.MYSQL_DB_ACQUIRE_INCREMENT); cpds.setMinPoolSize(databaseProperties.MYSQL_DB_MIN_POOL_SIZE); cpds.setMaxPoolSize(databaseProperties.MYSQL_DB_MAX_POOL_SIZE); cpds.setMaxStatementsPerConnection(databaseProperties.MYSQL_DB_MAX_STMT_PER_CONN); cpds.setMaxIdleTime(databaseProperties.MYSQL_DB_MAX_IDLE_TIME); return cpds; } }
UTF-8
Java
1,358
java
ApplicationDependencyFactory.java
Java
[]
null
[]
package com.ne.automation.spring; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.ne.automation.global.DatabaseProperties; @Configuration public class ApplicationDependencyFactory { @Autowired DatabaseProperties databaseProperties; @Bean public SchedulerFactory getSchedulerFactory() { return new StdSchedulerFactory(); } @Bean public ComboPooledDataSource getComboPooledDataSource() { System.out.println("Inside bean creation : " + databaseProperties.MYSQL_DB_URL); ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setJdbcUrl(databaseProperties.MYSQL_DB_URL); cpds.setUser(databaseProperties.MYSQL_DB_USER_NAME); cpds.setPassword(databaseProperties.MYSQL_DB_PASSWORD); cpds.setAcquireIncrement(databaseProperties.MYSQL_DB_ACQUIRE_INCREMENT); cpds.setMinPoolSize(databaseProperties.MYSQL_DB_MIN_POOL_SIZE); cpds.setMaxPoolSize(databaseProperties.MYSQL_DB_MAX_POOL_SIZE); cpds.setMaxStatementsPerConnection(databaseProperties.MYSQL_DB_MAX_STMT_PER_CONN); cpds.setMaxIdleTime(databaseProperties.MYSQL_DB_MAX_IDLE_TIME); return cpds; } }
1,358
0.822533
0.820324
39
33.820515
27.566118
84
false
false
0
0
0
0
0
0
1.358974
false
false
15
3e2f7a6645033d817c6287dfaa4ceddcd6b8c846
32,882,269,643,694
23d0c95af39b8ef8f5f405e75a80dae0aafc42d1
/app/src/main/java/com/dennyschuldt/colors/views/SettingsActivity.java
10b01bd83ffbb9e54b5cea0d59fba0c3094cb3af
[]
no_license
DenkSchuldt/Colors
https://github.com/DenkSchuldt/Colors
2496794ccff03e6cee8d3a36fe5519901fc7f631
6988218fb501ded9c3b711739065636934fe139f
refs/heads/master
2021-01-20T04:46:30.907000
2016-05-21T16:22:56
2016-05-21T16:22:56
56,827,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dennyschuldt.colors.views; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.dennyschuldt.colors.R; import com.dennyschuldt.colors.utils.Constants; /** * Created by denny on 4/23/16. */ public class SettingsActivity extends AppCompatActivity { private int deleteNewsTime; private ViewHolder viewHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); viewHolder = new ViewHolder(); viewHolder.buildLayout(); } @Override protected void onStart() { super.onStart(); updateContent(); } /** * */ public void updateContent() { updateVersionName(); } /** * */ public void updateVersionName() { try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); viewHolder.versionLabel.setText("v." + pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } /** * */ private class ViewHolder implements View.OnClickListener{ private LinearLayout layout; private TextView versionLabel; private LinearLayout version; private LinearLayout sendComments; public void buildLayout() { findViews(); setOnClickListeners(); } /** * */ private void findViews() { layout = (LinearLayout) findViewById(R.id.settings_layout); versionLabel = (TextView) findViewById(R.id.settings_version_label); version = (LinearLayout) findViewById(R.id.settings_version); sendComments = (LinearLayout) findViewById(R.id.settings_send_comments); } /** * */ private void setOnClickListeners() { version.setOnClickListener(this); sendComments.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.settings_version: Snackbar.make(layout, R.string.settings_version, Snackbar.LENGTH_LONG).show(); break; case R.id.settings_send_comments: Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", Constants.CONTACT_EMAIL, null)); i.putExtra(android.content.Intent.EXTRA_SUBJECT, "About the Colors app"); startActivity(Intent.createChooser(i, getResources().getString(R.string.settings_comments_label))); break; } } } }
UTF-8
Java
2,753
java
SettingsActivity.java
Java
[ { "context": "schuldt.colors.utils.Constants;\n\n/**\n * Created by denny on 4/23/16.\n */\npublic class SettingsActivity ext", "end": 499, "score": 0.9995828866958618, "start": 494, "tag": "USERNAME", "value": "denny" } ]
null
[]
package com.dennyschuldt.colors.views; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.dennyschuldt.colors.R; import com.dennyschuldt.colors.utils.Constants; /** * Created by denny on 4/23/16. */ public class SettingsActivity extends AppCompatActivity { private int deleteNewsTime; private ViewHolder viewHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); viewHolder = new ViewHolder(); viewHolder.buildLayout(); } @Override protected void onStart() { super.onStart(); updateContent(); } /** * */ public void updateContent() { updateVersionName(); } /** * */ public void updateVersionName() { try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); viewHolder.versionLabel.setText("v." + pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } /** * */ private class ViewHolder implements View.OnClickListener{ private LinearLayout layout; private TextView versionLabel; private LinearLayout version; private LinearLayout sendComments; public void buildLayout() { findViews(); setOnClickListeners(); } /** * */ private void findViews() { layout = (LinearLayout) findViewById(R.id.settings_layout); versionLabel = (TextView) findViewById(R.id.settings_version_label); version = (LinearLayout) findViewById(R.id.settings_version); sendComments = (LinearLayout) findViewById(R.id.settings_send_comments); } /** * */ private void setOnClickListeners() { version.setOnClickListener(this); sendComments.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.settings_version: Snackbar.make(layout, R.string.settings_version, Snackbar.LENGTH_LONG).show(); break; case R.id.settings_send_comments: Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", Constants.CONTACT_EMAIL, null)); i.putExtra(android.content.Intent.EXTRA_SUBJECT, "About the Colors app"); startActivity(Intent.createChooser(i, getResources().getString(R.string.settings_comments_label))); break; } } } }
2,753
0.685071
0.682528
110
24.027273
24.974699
110
false
false
0
0
0
0
0
0
0.463636
false
false
15
33fa52cce934ef15c30cfadb6bf819c666bf64ec
4,157,528,371,339
a4fc55b0695eff821f0f906bd71861fa8888c5e1
/app/src/main/java/com/example/programtest/integers/Palindrome.java
a91be8f3f577d1b7eb5492b0e5cc055a018dcf7b
[ "Apache-2.0" ]
permissive
tanaymondal/Leetcode-Problems
https://github.com/tanaymondal/Leetcode-Problems
598d426647ada52b819675af8d81d3589ff47368
e7d7a9a654d2946a65a56dd9fa32654f982d5c8b
refs/heads/master
2023-05-25T10:32:34.338000
2021-06-18T06:33:52
2021-06-18T06:33:52
371,436,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.programtest.integers; public class Palindrome { public static void main(String[] args) { // Check given number palindrome or not System.out.println("Is Palindrome " + isPalindrome(12121)); System.out.println("Is Palindrome " + isPalindrome(1212826721)); } static boolean isPalindrome(int number) { if (number < 0 || (number % 10 == 0 && number != 0)) { return false; } int reversedNum = 0; while (number > reversedNum) { reversedNum = reversedNum * 10 + number % 10; number = number / 10; } System.out.println("->" + number + " ->" + reversedNum); return reversedNum == number || number == reversedNum / 10; } }
UTF-8
Java
770
java
Palindrome.java
Java
[]
null
[]
package com.example.programtest.integers; public class Palindrome { public static void main(String[] args) { // Check given number palindrome or not System.out.println("Is Palindrome " + isPalindrome(12121)); System.out.println("Is Palindrome " + isPalindrome(1212826721)); } static boolean isPalindrome(int number) { if (number < 0 || (number % 10 == 0 && number != 0)) { return false; } int reversedNum = 0; while (number > reversedNum) { reversedNum = reversedNum * 10 + number % 10; number = number / 10; } System.out.println("->" + number + " ->" + reversedNum); return reversedNum == number || number == reversedNum / 10; } }
770
0.572727
0.535065
26
28.615385
25.337835
72
false
false
0
0
0
0
0
0
0.5
false
false
15
133b521eb1b98f90e52f6dc21803a76d46bdc6cb
14,078,902,805,509
c61ab551bab94a104b4e04d71916621764cd582a
/app/src/main/java/duongdd/se06000/p2plendingapplication/repository/LendingRepositoryImp.java
50b80d6d489183add54dd069bf7afa0c709fc8e9
[]
no_license
Duongg/P2PLending-Application
https://github.com/Duongg/P2PLending-Application
9a64fa2eda6d6a00ffa284fffb3ce2623db21a94
c51a05cc86d35706f4cbba6ddbb2e65d01534934
refs/heads/master
2020-08-06T13:05:49.311000
2019-10-21T05:05:28
2019-10-21T05:05:28
212,985,982
0
0
null
false
2019-10-21T05:05:29
2019-10-05T11:10:08
2019-10-20T18:39:03
2019-10-21T05:05:29
583
0
0
1
Java
false
false
package duongdd.se06000.p2plendingapplication.repository; import androidx.navigation.Navigation; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONObject; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.List; // <<<<<<< duongdd/over-view-borrower import duongdd.se06000.p2plendingapplication.model.DetailInvestmentCalling; // ======= import duongdd.se06000.p2plendingapplication.model.Account; // >>>>>>> master import duongdd.se06000.p2plendingapplication.model.InvestedInformation; import duongdd.se06000.p2plendingapplication.model.InvestmentCallingDetailsInformation; import duongdd.se06000.p2plendingapplication.model.InvestorInvest; import duongdd.se06000.p2plendingapplication.model.ListInvestedCompany; import duongdd.se06000.p2plendingapplication.model.CompanyDisbursement; import duongdd.se06000.p2plendingapplication.model.InvestmentCompanyDetail; import duongdd.se06000.p2plendingapplication.model.InvestorDetail; import duongdd.se06000.p2plendingapplication.model.ListCallingInvestment; import duongdd.se06000.p2plendingapplication.model.ListInvestmentCompany; import duongdd.se06000.p2plendingapplication.model.ListSearchInvestment; import duongdd.se06000.p2plendingapplication.model.Notification; import duongdd.se06000.p2plendingapplication.model.WalletInformation; import duongdd.se06000.p2plendingapplication.util.CallBackData; import duongdd.se06000.p2plendingapplication.util.ClientApi; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LendingRepositoryImp implements LendingRepository{ public static String TOKEN = ""; @Override public void login(String username, String password, final CallBackData<String> callBackData) { JSONObject customer = new JSONObject(); try { customer.put("username", username); customer.put("password", password); } catch (Exception e) { e.printStackTrace(); } ClientApi clientApi = new ClientApi(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), customer.toString()); Call<ResponseBody> call = clientApi.LendingService().loginToken(body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { if(response.code() == 200){ String body = response.body().string(); if(!body.isEmpty()){ TOKEN = body; callBackData.onSuccess(TOKEN); } }else{ callBackData.onFail("Sai tài khoản hoặc mật khẩu"); } }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void createAccount(final Account account, final CallBackData<Account> callBackData) { JSONObject customer = new JSONObject(); try { customer.put("accountID", account.getAccountID()); customer.put("email", account.getEmail()); customer.put("name", account.getName()); customer.put("password", account.getPassword()); customer.put("phone", account.getPhone()); customer.put("role", account.getRole()); customer.put("username", account.getUsername()); } catch (Exception e) { e.printStackTrace(); } ClientApi clientApi = new ClientApi(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), customer.toString()); Call<ResponseBody> call = clientApi.LendingService().createAccount(body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { if(response.code() == 200){ String body = response.body().string(); Type type = new TypeToken<Account>(){}.getType(); Account accountCreate = new Gson().fromJson(body,type); if(accountCreate != null){ callBackData.onSuccess(accountCreate); } }else{ callBackData.onFail("Không thể tạo tài khoản"); } }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void updateAccount(String token, Account account,final CallBackData<Account> callBackData) { JSONObject customer = new JSONObject(); try { customer.put("accountID", account.getAccountID()); customer.put("email", account.getEmail()); customer.put("name", account.getName()); customer.put("password", account.getPassword()); customer.put("phone", account.getPhone()); customer.put("role", account.getRole()); customer.put("username", account.getUsername()); } catch (Exception e) { e.printStackTrace(); } ClientApi clientApi = new ClientApi(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), customer.toString()); Call<ResponseBody> call = clientApi.LendingService().updateAccount(token, body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { if(response.code() == 200){ String body = response.body().string(); Type type = new TypeToken<Account>(){}.getType(); Account accountUpdate = new Gson().fromJson(body,type); if(accountUpdate != null){ callBackData.onSuccess(accountUpdate); } }else{ callBackData.onFail("Không thể sửa tài khoản"); } }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void getWalletInfo(String token,final CallBackData<WalletInformation> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getWalletInfo(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<WalletInformation>(){}.getType(); WalletInformation walletInformation = new Gson().fromJson(body,type); if(walletInformation != null){ callBackData.onSuccess(walletInformation); }else{ callBackData.onFail("Tài khoản không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Tài khoản không tồn tại"); } }); } @Override public void getAccountInformation(String token,final CallBackData<Account> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getAccountInformation(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<Account>(){}.getType(); Account account = new Gson().fromJson(body,type); if(account != null){ callBackData.onSuccess(account); }else{ callBackData.onFail("Tài khoản không tồn tại"); } }catch (Exception e){ callBackData.onFail("Tài khoản không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Tài khoản không tồn tại"); } }); } @Override public void getRoleAccount(String token,final CallBackData<String> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getRoleAccount(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<String>(){}.getType(); String role = new Gson().fromJson(body,type); if(!role.isEmpty()){ callBackData.onSuccess(role); }else{ callBackData.onFail("Tài khoản không tồn tại"); } }catch (Exception e){ callBackData.onFail("Tài khoản không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Tài khoản không tồn tại"); } }); } @Override public void getListInvestmentCompany(String token, final CallBackData<List<ListInvestmentCompany>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListInvestment(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListInvestmentCompany>>(){}.getType(); List<ListInvestmentCompany> listInvestmentCompanies = new Gson().fromJson(body,type); if(listInvestmentCompanies != null){ callBackData.onSuccess(listInvestmentCompanies); }else{ callBackData.onFail("Không có đầu tư nào"); } }catch (Exception e){ callBackData.onFail("Không có đầu tư nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không có đầu tư nào"); } }); } @Override public void getInvestorDetail(String token, int investorDetailsID, final CallBackData<List<InvestorDetail>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getInvestorDetail(token, investorDetailsID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<InvestorDetail>>(){}.getType(); List<InvestorDetail> listInvestmentCompanies = new Gson().fromJson(body,type); if(listInvestmentCompanies != null){ callBackData.onSuccess(listInvestmentCompanies); }else{ callBackData.onFail("Không có đầu tư nào"); } }catch (Exception e){ callBackData.onFail("Không có đầu tư nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không có đầu tư nào"); } }); } @Override public void getInvestedDetailInformation(String token, int investorDetailsID,final CallBackData<InvestedInformation> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getInvestedDetailInformation(token, investorDetailsID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<InvestedInformation>(){}.getType(); InvestedInformation investmentCompanyDetail = new Gson().fromJson(body,type); if(investmentCompanyDetail != null){ callBackData.onSuccess(investmentCompanyDetail); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getInvestmentCompanyDetail(String token, int investmentCompanyID, final CallBackData<InvestmentCompanyDetail> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getInvestmentCompanyDetail(token, investmentCompanyID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<InvestmentCompanyDetail>(){}.getType(); InvestmentCompanyDetail investmentCompanyDetail = new Gson().fromJson(body,type); if(investmentCompanyDetail != null){ callBackData.onSuccess(investmentCompanyDetail); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getListCallingInvestment(String token,final CallBackData<List<ListCallingInvestment>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListCallingInvestment(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListCallingInvestment>>(){}.getType(); List<ListCallingInvestment> listCallingInvestments = new Gson().fromJson(body,type); if(listCallingInvestments != null){ callBackData.onSuccess(listCallingInvestments); }else{ callBackData.onFail("Không có thương vụ nào"); } }catch (Exception e){ callBackData.onFail("Không thương vụ nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không thương vụ nào"); } }); } @Override public void getListSearchInvestment(String token, String keyword, String career,final CallBackData<List<ListSearchInvestment>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListSearchInvestment(token, keyword,career); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListSearchInvestment>>(){}.getType(); List<ListSearchInvestment> listSearchInvestments = new Gson().fromJson(body,type); if(listSearchInvestments != null){ callBackData.onSuccess(listSearchInvestments); }else{ callBackData.onFail("Không có thương vụ nào"); } }catch (Exception e){ callBackData.onFail("Không thương vụ nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không thương vụ nào"); } }); } @Override public void getPaymentAllDisbursement(String token,int investmentCompanyID, int companyDisbursementID,final CallBackData<CompanyDisbursement> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().paymentAllDisbursement(token,investmentCompanyID, companyDisbursementID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<CompanyDisbursement>(){}.getType(); CompanyDisbursement companyDisbursement = new Gson().fromJson(body,type); if(companyDisbursement != null){ callBackData.onSuccess(companyDisbursement); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getPaymentDebtDisbursement(String token,int investmentCompanyID, int companyDisbursementID,final CallBackData<CompanyDisbursement> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().paymentDebtDisbursement(token, investmentCompanyID, companyDisbursementID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<CompanyDisbursement>(){}.getType(); CompanyDisbursement companyDisbursement = new Gson().fromJson(body,type); if(companyDisbursement != null){ callBackData.onSuccess(companyDisbursement); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getPaymentDisbursement(String token,int investmentCompanyID, BigDecimal money, int companyDisbursementID,final CallBackData<CompanyDisbursement> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().paymentDisbursement(token, investmentCompanyID, money, companyDisbursementID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<CompanyDisbursement>(){}.getType(); CompanyDisbursement companyDisbursement = new Gson().fromJson(body,type); if(companyDisbursement != null){ callBackData.onSuccess(companyDisbursement); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void investorInvest(String token, int borrowerID, int investmentCompanyID, BigDecimal money,final CallBackData<InvestorInvest> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().investorInvest(token, borrowerID, investmentCompanyID, money); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<InvestorInvest>(){}.getType(); InvestorInvest investorInvest = new Gson().fromJson(body,type); if(investorInvest != null){ callBackData.onSuccess(investorInvest); }else{ callBackData.onFail("Số tiền không hợp lệ"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Số tiền không hợp lệ"); } }); } @Override public void getListInvestedCompany(String token,final CallBackData<List<ListInvestedCompany>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListInvested(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListInvestedCompany>>(){}.getType(); List<ListInvestedCompany> listInvestedCompanies = new Gson().fromJson(body,type); if(listInvestedCompanies != null){ callBackData.onSuccess(listInvestedCompanies); }else{ callBackData.onFail("Không có đầu tư nào"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void getNotification(String token, final CallBackData<List<Notification>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call =clientApi.LendingService().getNotification(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<List<Notification>>(){}.getType(); List<Notification> notificationList = new Gson().fromJson(body,type); if(notificationList != null){ callBackData.onSuccess(notificationList); }else { callBackData.onFail("Thông báo không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } @Override public void getCallingInvestmentDetailsInformation(String token, int investmentCompanyID, final CallBackData<InvestmentCallingDetailsInformation> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call =clientApi.LendingService().getCallingInvestmentDetailsInformation(token, investmentCompanyID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<InvestmentCallingDetailsInformation>(){}.getType(); InvestmentCallingDetailsInformation investmentCallingDetailsInformation = new Gson().fromJson(body, type); if(investmentCallingDetailsInformation != null){ callBackData.onSuccess(investmentCallingDetailsInformation); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } @Override public void getListDisbursementMoney(String token, int investmentCompanyID, final CallBackData<List<CompanyDisbursement>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListDisbursementMoney(token, investmentCompanyID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<List<CompanyDisbursement>>(){}.getType(); List<CompanyDisbursement> companyDisbursementList =new Gson().fromJson(body,type); if(companyDisbursementList != null){ callBackData.onSuccess(companyDisbursementList); }else { callBackData.onFail("Không có thương vụ nào"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không có thương vụ nào"); } }); } @Override public void getDetailCallingInvestment(String token, int investmentCompanyID, final CallBackData<DetailInvestmentCalling> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().detailInvestmentCallingCompany(token, investmentCompanyID ); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<DetailInvestmentCalling>(){}.getType(); DetailInvestmentCalling detailInvestmentCalling = new Gson().fromJson(body,type); if(detailInvestmentCalling != null){ callBackData.onSuccess(detailInvestmentCalling); }else { callBackData.onFail("Không có thương vụ nào kêu gọi"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } }
UTF-8
Java
32,569
java
LendingRepositoryImp.java
Java
[ { "context": " try {\n customer.put(\"username\", username);\n customer.put(\"password\", password);", "end": 1966, "score": 0.9690070748329163, "start": 1958, "tag": "USERNAME", "value": "username" }, { "context": "\", username);\n customer.put(\"password\", password);\n } catch (Exception e) {\n e.p", "end": 2014, "score": 0.7259071469306946, "start": 2006, "tag": "PASSWORD", "value": "password" }, { "context": "t.getName());\n customer.put(\"password\", account.getPassword());\n customer.put(\"phone\", account.getPhon", "end": 5581, "score": 0.993910014629364, "start": 5562, "tag": "PASSWORD", "value": "account.getPassword" } ]
null
[]
package duongdd.se06000.p2plendingapplication.repository; import androidx.navigation.Navigation; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONObject; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.List; // <<<<<<< duongdd/over-view-borrower import duongdd.se06000.p2plendingapplication.model.DetailInvestmentCalling; // ======= import duongdd.se06000.p2plendingapplication.model.Account; // >>>>>>> master import duongdd.se06000.p2plendingapplication.model.InvestedInformation; import duongdd.se06000.p2plendingapplication.model.InvestmentCallingDetailsInformation; import duongdd.se06000.p2plendingapplication.model.InvestorInvest; import duongdd.se06000.p2plendingapplication.model.ListInvestedCompany; import duongdd.se06000.p2plendingapplication.model.CompanyDisbursement; import duongdd.se06000.p2plendingapplication.model.InvestmentCompanyDetail; import duongdd.se06000.p2plendingapplication.model.InvestorDetail; import duongdd.se06000.p2plendingapplication.model.ListCallingInvestment; import duongdd.se06000.p2plendingapplication.model.ListInvestmentCompany; import duongdd.se06000.p2plendingapplication.model.ListSearchInvestment; import duongdd.se06000.p2plendingapplication.model.Notification; import duongdd.se06000.p2plendingapplication.model.WalletInformation; import duongdd.se06000.p2plendingapplication.util.CallBackData; import duongdd.se06000.p2plendingapplication.util.ClientApi; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LendingRepositoryImp implements LendingRepository{ public static String TOKEN = ""; @Override public void login(String username, String password, final CallBackData<String> callBackData) { JSONObject customer = new JSONObject(); try { customer.put("username", username); customer.put("password", <PASSWORD>); } catch (Exception e) { e.printStackTrace(); } ClientApi clientApi = new ClientApi(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), customer.toString()); Call<ResponseBody> call = clientApi.LendingService().loginToken(body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { if(response.code() == 200){ String body = response.body().string(); if(!body.isEmpty()){ TOKEN = body; callBackData.onSuccess(TOKEN); } }else{ callBackData.onFail("Sai tài khoản hoặc mật khẩu"); } }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void createAccount(final Account account, final CallBackData<Account> callBackData) { JSONObject customer = new JSONObject(); try { customer.put("accountID", account.getAccountID()); customer.put("email", account.getEmail()); customer.put("name", account.getName()); customer.put("password", account.getPassword()); customer.put("phone", account.getPhone()); customer.put("role", account.getRole()); customer.put("username", account.getUsername()); } catch (Exception e) { e.printStackTrace(); } ClientApi clientApi = new ClientApi(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), customer.toString()); Call<ResponseBody> call = clientApi.LendingService().createAccount(body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { if(response.code() == 200){ String body = response.body().string(); Type type = new TypeToken<Account>(){}.getType(); Account accountCreate = new Gson().fromJson(body,type); if(accountCreate != null){ callBackData.onSuccess(accountCreate); } }else{ callBackData.onFail("Không thể tạo tài khoản"); } }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void updateAccount(String token, Account account,final CallBackData<Account> callBackData) { JSONObject customer = new JSONObject(); try { customer.put("accountID", account.getAccountID()); customer.put("email", account.getEmail()); customer.put("name", account.getName()); customer.put("password", <PASSWORD>()); customer.put("phone", account.getPhone()); customer.put("role", account.getRole()); customer.put("username", account.getUsername()); } catch (Exception e) { e.printStackTrace(); } ClientApi clientApi = new ClientApi(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), customer.toString()); Call<ResponseBody> call = clientApi.LendingService().updateAccount(token, body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { if(response.code() == 200){ String body = response.body().string(); Type type = new TypeToken<Account>(){}.getType(); Account accountUpdate = new Gson().fromJson(body,type); if(accountUpdate != null){ callBackData.onSuccess(accountUpdate); } }else{ callBackData.onFail("Không thể sửa tài khoản"); } }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void getWalletInfo(String token,final CallBackData<WalletInformation> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getWalletInfo(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<WalletInformation>(){}.getType(); WalletInformation walletInformation = new Gson().fromJson(body,type); if(walletInformation != null){ callBackData.onSuccess(walletInformation); }else{ callBackData.onFail("Tài khoản không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Tài khoản không tồn tại"); } }); } @Override public void getAccountInformation(String token,final CallBackData<Account> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getAccountInformation(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<Account>(){}.getType(); Account account = new Gson().fromJson(body,type); if(account != null){ callBackData.onSuccess(account); }else{ callBackData.onFail("Tài khoản không tồn tại"); } }catch (Exception e){ callBackData.onFail("Tài khoản không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Tài khoản không tồn tại"); } }); } @Override public void getRoleAccount(String token,final CallBackData<String> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getRoleAccount(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<String>(){}.getType(); String role = new Gson().fromJson(body,type); if(!role.isEmpty()){ callBackData.onSuccess(role); }else{ callBackData.onFail("Tài khoản không tồn tại"); } }catch (Exception e){ callBackData.onFail("Tài khoản không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Tài khoản không tồn tại"); } }); } @Override public void getListInvestmentCompany(String token, final CallBackData<List<ListInvestmentCompany>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListInvestment(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListInvestmentCompany>>(){}.getType(); List<ListInvestmentCompany> listInvestmentCompanies = new Gson().fromJson(body,type); if(listInvestmentCompanies != null){ callBackData.onSuccess(listInvestmentCompanies); }else{ callBackData.onFail("Không có đầu tư nào"); } }catch (Exception e){ callBackData.onFail("Không có đầu tư nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không có đầu tư nào"); } }); } @Override public void getInvestorDetail(String token, int investorDetailsID, final CallBackData<List<InvestorDetail>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getInvestorDetail(token, investorDetailsID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<InvestorDetail>>(){}.getType(); List<InvestorDetail> listInvestmentCompanies = new Gson().fromJson(body,type); if(listInvestmentCompanies != null){ callBackData.onSuccess(listInvestmentCompanies); }else{ callBackData.onFail("Không có đầu tư nào"); } }catch (Exception e){ callBackData.onFail("Không có đầu tư nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không có đầu tư nào"); } }); } @Override public void getInvestedDetailInformation(String token, int investorDetailsID,final CallBackData<InvestedInformation> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getInvestedDetailInformation(token, investorDetailsID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<InvestedInformation>(){}.getType(); InvestedInformation investmentCompanyDetail = new Gson().fromJson(body,type); if(investmentCompanyDetail != null){ callBackData.onSuccess(investmentCompanyDetail); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getInvestmentCompanyDetail(String token, int investmentCompanyID, final CallBackData<InvestmentCompanyDetail> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getInvestmentCompanyDetail(token, investmentCompanyID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<InvestmentCompanyDetail>(){}.getType(); InvestmentCompanyDetail investmentCompanyDetail = new Gson().fromJson(body,type); if(investmentCompanyDetail != null){ callBackData.onSuccess(investmentCompanyDetail); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getListCallingInvestment(String token,final CallBackData<List<ListCallingInvestment>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListCallingInvestment(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListCallingInvestment>>(){}.getType(); List<ListCallingInvestment> listCallingInvestments = new Gson().fromJson(body,type); if(listCallingInvestments != null){ callBackData.onSuccess(listCallingInvestments); }else{ callBackData.onFail("Không có thương vụ nào"); } }catch (Exception e){ callBackData.onFail("Không thương vụ nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không thương vụ nào"); } }); } @Override public void getListSearchInvestment(String token, String keyword, String career,final CallBackData<List<ListSearchInvestment>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListSearchInvestment(token, keyword,career); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListSearchInvestment>>(){}.getType(); List<ListSearchInvestment> listSearchInvestments = new Gson().fromJson(body,type); if(listSearchInvestments != null){ callBackData.onSuccess(listSearchInvestments); }else{ callBackData.onFail("Không có thương vụ nào"); } }catch (Exception e){ callBackData.onFail("Không thương vụ nào"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không thương vụ nào"); } }); } @Override public void getPaymentAllDisbursement(String token,int investmentCompanyID, int companyDisbursementID,final CallBackData<CompanyDisbursement> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().paymentAllDisbursement(token,investmentCompanyID, companyDisbursementID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<CompanyDisbursement>(){}.getType(); CompanyDisbursement companyDisbursement = new Gson().fromJson(body,type); if(companyDisbursement != null){ callBackData.onSuccess(companyDisbursement); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getPaymentDebtDisbursement(String token,int investmentCompanyID, int companyDisbursementID,final CallBackData<CompanyDisbursement> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().paymentDebtDisbursement(token, investmentCompanyID, companyDisbursementID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<CompanyDisbursement>(){}.getType(); CompanyDisbursement companyDisbursement = new Gson().fromJson(body,type); if(companyDisbursement != null){ callBackData.onSuccess(companyDisbursement); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void getPaymentDisbursement(String token,int investmentCompanyID, BigDecimal money, int companyDisbursementID,final CallBackData<CompanyDisbursement> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().paymentDisbursement(token, investmentCompanyID, money, companyDisbursementID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<CompanyDisbursement>(){}.getType(); CompanyDisbursement companyDisbursement = new Gson().fromJson(body,type); if(companyDisbursement != null){ callBackData.onSuccess(companyDisbursement); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ callBackData.onFail("Thương vụ không tồn tại"); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Thương vụ không tồn tại"); } }); } @Override public void investorInvest(String token, int borrowerID, int investmentCompanyID, BigDecimal money,final CallBackData<InvestorInvest> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().investorInvest(token, borrowerID, investmentCompanyID, money); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<InvestorInvest>(){}.getType(); InvestorInvest investorInvest = new Gson().fromJson(body,type); if(investorInvest != null){ callBackData.onSuccess(investorInvest); }else{ callBackData.onFail("Số tiền không hợp lệ"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Số tiền không hợp lệ"); } }); } @Override public void getListInvestedCompany(String token,final CallBackData<List<ListInvestedCompany>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListInvested(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try { String body = response.body().string(); Type type = new TypeToken<List<ListInvestedCompany>>(){}.getType(); List<ListInvestedCompany> listInvestedCompanies = new Gson().fromJson(body,type); if(listInvestedCompanies != null){ callBackData.onSuccess(listInvestedCompanies); }else{ callBackData.onFail("Không có đầu tư nào"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } @Override public void getNotification(String token, final CallBackData<List<Notification>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call =clientApi.LendingService().getNotification(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<List<Notification>>(){}.getType(); List<Notification> notificationList = new Gson().fromJson(body,type); if(notificationList != null){ callBackData.onSuccess(notificationList); }else { callBackData.onFail("Thông báo không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } @Override public void getCallingInvestmentDetailsInformation(String token, int investmentCompanyID, final CallBackData<InvestmentCallingDetailsInformation> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call =clientApi.LendingService().getCallingInvestmentDetailsInformation(token, investmentCompanyID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<InvestmentCallingDetailsInformation>(){}.getType(); InvestmentCallingDetailsInformation investmentCallingDetailsInformation = new Gson().fromJson(body, type); if(investmentCallingDetailsInformation != null){ callBackData.onSuccess(investmentCallingDetailsInformation); }else{ callBackData.onFail("Thương vụ không tồn tại"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } @Override public void getListDisbursementMoney(String token, int investmentCompanyID, final CallBackData<List<CompanyDisbursement>> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().getListDisbursementMoney(token, investmentCompanyID); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<List<CompanyDisbursement>>(){}.getType(); List<CompanyDisbursement> companyDisbursementList =new Gson().fromJson(body,type); if(companyDisbursementList != null){ callBackData.onSuccess(companyDisbursementList); }else { callBackData.onFail("Không có thương vụ nào"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callBackData.onFail("Không có thương vụ nào"); } }); } @Override public void getDetailCallingInvestment(String token, int investmentCompanyID, final CallBackData<DetailInvestmentCalling> callBackData) { ClientApi clientApi = new ClientApi(); Call<ResponseBody> call = clientApi.LendingService().detailInvestmentCallingCompany(token, investmentCompanyID ); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code() == 200){ try{ String body = response.body().string(); Type type = new TypeToken<DetailInvestmentCalling>(){}.getType(); DetailInvestmentCalling detailInvestmentCalling = new Gson().fromJson(body,type); if(detailInvestmentCalling != null){ callBackData.onSuccess(detailInvestmentCalling); }else { callBackData.onFail("Không có thương vụ nào kêu gọi"); } }catch (Exception e){ e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } }
32,562
0.543202
0.5378
730
43.121918
34.010357
176
false
false
0
0
0
0
0
0
0.557534
false
false
15
c751048e62c7dee37ce5e396a016c07f2856349c
26,242,250,234,101
1dd03ae1cdd0f80d5b07114e0cba3faee331b425
/AndroidStudySamples/framework/src/main/java/com/changxiao/framework/util/MD5.java
73802e6f65b07e1e14e98b0386b83dd144ad8859
[]
no_license
xiaoqianchang/AndroidStudioProjects
https://github.com/xiaoqianchang/AndroidStudioProjects
94392371a7d53c7866132842d47753c048ba2d2b
f5b256df3404f56ad53e80c818c551114555950e
refs/heads/master
2020-08-10T00:51:53.251000
2019-10-10T15:16:00
2019-10-10T15:16:00
214,214,308
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.changxiao.framework.util; import android.text.TextUtils; import java.math.BigInteger; import java.security.MessageDigest; /** * MD5 * * Created by Chang.Xiao on 2019/1/13. * * @version 1.0 */ public class MD5 { public static String md5(byte[] input) { String result = ""; if (input != null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input); BigInteger hash = new BigInteger(1, md.digest()); for(result = hash.toString(16); result.length() < 32; result = "0" + result) { ; } } catch (Exception var4) { Logger.log("md5加密出错" + var4.getMessage()); } } return result; } public static String md5(String input) { String result = input; if (input != null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); for(result = hash.toString(16); result.length() < 32; result = "0" + result) { ; } } catch (Exception var4) { Logger.log("md5加密出错" + var4.getMessage()); } } return result; } public static String getFileNameMd5(String url) { if (TextUtils.isEmpty(url)) { return ""; } else { int end = url.indexOf("?"); url = url.substring(url.indexOf("/", "http://".length()), end == -1 ? url.length() : end); return md5(url); } } }
UTF-8
Java
1,508
java
MD5.java
Java
[ { "context": "curity.MessageDigest;\n\n/**\n * MD5\n *\n * Created by Chang.Xiao on 2019/1/13.\n *\n * @version 1.0\n */\npublic class", "end": 174, "score": 0.9998455047607422, "start": 164, "tag": "NAME", "value": "Chang.Xiao" } ]
null
[]
package com.changxiao.framework.util; import android.text.TextUtils; import java.math.BigInteger; import java.security.MessageDigest; /** * MD5 * * Created by Chang.Xiao on 2019/1/13. * * @version 1.0 */ public class MD5 { public static String md5(byte[] input) { String result = ""; if (input != null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input); BigInteger hash = new BigInteger(1, md.digest()); for(result = hash.toString(16); result.length() < 32; result = "0" + result) { ; } } catch (Exception var4) { Logger.log("md5加密出错" + var4.getMessage()); } } return result; } public static String md5(String input) { String result = input; if (input != null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); for(result = hash.toString(16); result.length() < 32; result = "0" + result) { ; } } catch (Exception var4) { Logger.log("md5加密出错" + var4.getMessage()); } } return result; } public static String getFileNameMd5(String url) { if (TextUtils.isEmpty(url)) { return ""; } else { int end = url.indexOf("?"); url = url.substring(url.indexOf("/", "http://".length()), end == -1 ? url.length() : end); return md5(url); } } }
1,508
0.567024
0.542895
63
22.682539
23.106947
96
false
false
0
0
0
0
0
0
0.47619
false
false
15
0ab0592621976647e0940c7b6665e576ebc63560
10,462,540,339,139
f1eacc3a83a9f24c5875bea5c9ba21fd335efe38
/Proyecto/src/proyecto/CompuertasLogicas.java
b000ddf5e74d9d566d41fad7378996e61c667d8c
[]
no_license
Ignaciograne/Proyecto1
https://github.com/Ignaciograne/Proyecto1
fbb7ae02594f3cc1cf055dc8decd6decf026419d
903d4429903934ad6003770027169313da39ea86
refs/heads/master
2020-07-10T19:01:09.764000
2019-09-28T05:54:06
2019-09-28T05:54:06
204,341,601
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package proyecto; public class CompuertasLogicas { /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la multiplicación (int). */ public int compuertaAnd(int i1, int i2){ return (i1 * i2); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la suma (int). */ public int compuertaNand(int i1, int i2){ return 1 - (i1 * i2); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la suma, en caso de ser mayor a 1 retorna 1 igualmente (int). */ public int compuertaOr(int i1, int i2){ if ((i1 + i2) >= 1) return 1; return 0; } /** * @param i1 Valor binario (int). * @return Retorna la resta obtenida de 1 con el valor binario obtenido (int). */ public int compuertaNot(int i1){ return (1 - i1); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la suma invertido, en caso de ser mayor a 1 retorna 0 igualmente (int). */ public int compuertaNor(int i1, int i2){ if ((i1 + i2) >= 1) return 0; return 1; } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado del xor (int). */ public int compuertaXor(int i1, int i2){ return (i1 ^ i2); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la resta entre 1 y el xor obtenido (int). */ public int compuertaXnor(int i1, int i2){ return 1 - (i1 ^ i2); } }
UTF-8
Java
1,953
java
CompuertasLogicas.java
Java
[]
null
[]
package proyecto; public class CompuertasLogicas { /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la multiplicación (int). */ public int compuertaAnd(int i1, int i2){ return (i1 * i2); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la suma (int). */ public int compuertaNand(int i1, int i2){ return 1 - (i1 * i2); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la suma, en caso de ser mayor a 1 retorna 1 igualmente (int). */ public int compuertaOr(int i1, int i2){ if ((i1 + i2) >= 1) return 1; return 0; } /** * @param i1 Valor binario (int). * @return Retorna la resta obtenida de 1 con el valor binario obtenido (int). */ public int compuertaNot(int i1){ return (1 - i1); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la suma invertido, en caso de ser mayor a 1 retorna 0 igualmente (int). */ public int compuertaNor(int i1, int i2){ if ((i1 + i2) >= 1) return 0; return 1; } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado del xor (int). */ public int compuertaXor(int i1, int i2){ return (i1 ^ i2); } /** * @param i1 Primer valor binario (int). * @param i2 Segundo valor binario (int). * @return Obtiene el resultado de la resta entre 1 y el xor obtenido (int). */ public int compuertaXnor(int i1, int i2){ return 1 - (i1 ^ i2); } }
1,953
0.559426
0.531762
70
26.9
24.112919
110
false
false
0
0
0
0
0
0
0.257143
false
false
15
d94204e7028f785659b65b0f66b7c8229ef91170
15,539,191,703,852
067dd1da377c69310b18ede06a9cc68e264b9664
/src/main/java/model/Attr.java
d609e4a05d96d5a7cbb513fc9151c6536d7c5ea1
[]
no_license
mikl778890/magazine
https://github.com/mikl778890/magazine
4c675f4539196328f563ea4f4f0b809c68e24f36
5cd3c9b0a19fcd7a49647d8384c5ac7adce7d723
refs/heads/master
2016-09-12T09:08:36.844000
2016-05-29T08:27:08
2016-05-29T08:27:08
58,524,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import javax.persistence.*; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.ManyToOne; import java.io.Serializable; /** * Created by mikl on 08.05.16. */ @Entity public class Attr implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name; private String value; @ManyToOne private Item item; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } }
UTF-8
Java
970
java
Attr.java
Java
[ { "context": "e;\nimport java.io.Serializable;\n\n/**\n * Created by mikl on 08.05.16.\n */\n@Entity\npublic class Attr implem", "end": 214, "score": 0.9995782971382141, "start": 210, "tag": "USERNAME", "value": "mikl" } ]
null
[]
package model; import javax.persistence.*; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.ManyToOne; import java.io.Serializable; /** * Created by mikl on 08.05.16. */ @Entity public class Attr implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name; private String value; @ManyToOne private Item item; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } }
970
0.619588
0.613402
58
15.724138
14.730678
55
false
false
0
0
0
0
0
0
0.310345
false
false
15
f4c8f1b7e9fa56718334c98d4c44a2d3878a9872
17,016,660,465,802
6e39cb9920201454cdce78b06b1e8c428f46a799
/mods/Railcraft_1.10.2-10.0.1/ic2/api/info/ITeBlock.java
fe44aa73424bafa41b2209df8c5a8eabbaaa86ab
[ "MIT" ]
permissive
TheCandiedHat/FTB-Beyond-Source-Code
https://github.com/TheCandiedHat/FTB-Beyond-Source-Code
1ded76d800debec940a111b974b53ee0c31c6681
d79ffaefc510c6d3267983b118247c1d390cf10c
refs/heads/master
2021-01-18T16:46:00.394000
2017-03-30T22:35:09
2017-03-30T22:35:09
86,754,889
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ic2.api.info; import java.util.Set; import net.minecraft.block.material.Material; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import ic2.api.event.TeBlockFinalCallEvent; import ic2.api.item.ITeBlockSpecialItem; import ic2.api.tile.IWrenchable; /** First of all, yes this class is empty. It's public documentation for the actual internal interface ITeBlock. <strong>Use the internal one not this!</strong> * <p> * You may be asking, why would an internal interface need documenting? Well, the answer is so people can use <code>TileEntityBlock</code>. * That class is the base for all IC2 tile entities, so by being able to use that you're level to IC2. * Many methods are protected in there too, as they're only designed to be called by <code>BlockTileEntity</code> (which is the block all IC2 tile entities will be on), * by being able to extend it means all those methods you can now extend and be confident they will be called correctly. * </p> * <p> * The more observant might have noticed there was an event that allowed you to do basically the same thing called <code>TeBlockBakeEvent</code>. * Whilst that event used to add your own class onto <code>TeBlock</code> (that wasn't ideal as you could end up using the same ID as another addon which would cause a crash), * this allows you to completely implement your own version of <code>TeBlock</code>, then let IC2 take it and build the necessary structures around it. * Both mean you no longer have to use <code>EnumHelper</code> and lots of reflection to mess about with <code>TeBlock</code>, * just to be left with either a crash from doing it too late/wrong, or lots of code bound to IC2 (such as language keys and blockstate jsons being in IC2's assets). * </p> * <p> * Unlike <code>TeBlockBakeEvent</code>, this gives you near total control of your tile entities: * <blockquote> * You can pick whether each of your tile entity items show up in creative, and the order in which they do.<br/> * You can choose whether you use an <code>enum</code> or <code>class</code> for your implementation. * We use (and I personally recommend) using an <code>enum</code>, as the values should never change, but in the end the choice is yours.<br/> * There is a proper separation between each registered <code>ITeBlock</code> by resource location, rather than everything being inserted into a single <code>enum</code>. * You also receive your own instance of <code>BlockTileEntity</code> and <code>ItemBlockTileEntity</code> rather than having to use IC2's own one.<br/> * All the language keys and blockstate file are in your own assets (which you can, and in fact have to, pick). * </blockquote> * It is a vast improvement over <code>TeBlockBakeEvent</code>, which is probably important as it's gone now ;) * </p> * <br/> * The event allows you to properly register your own version of <code>TeBlock</code> in a way that will be as fully supported as is physically possible. * It's not in the actual API itself as it's heavily dependent on internal classes, so you have this instead. * This is also probably the most documented thing in the entire IC2 API. <small>I'm too kind really. ;)</small> * </p> * <hr> * <p> * So that's all well and good, but what you really want is an example of how to do it properly. Good idea, let's go. * <blockquote><pre><code> *import net.minecraftforge.common.MinecraftForge; *import net.minecraftforge.fml.common.Mod; *import net.minecraftforge.fml.common.Mod.EventHandler; *import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; *import net.minecraftforge.fml.common.event.FMLInitializationEvent; * *{@literal @}Mod(modId="ExampleIC2Addon") *public class ExampleIC2Addon { * public ExampleIC2Addon() { * //You have to register before IC2 reaches Pre-Initialization, which unless you specifically load before it is unlikely you'll achieve. * //Especially if you're an addon, you'll want to be loading after IC2 not before! * //But, your mod's constructor will definitely be called before then. The issue is it's called more than once. * //If you try registering the same tile entity ID twice it will crash (more on that later), so you'll have to use a singleton instance. * //An enum works well for this, but anything will work as long as it's registered to the event bus once, and only once. * MinecraftForge.EVENT_BUS.register(TileEntityRegisterer.INSTANCE); * } * * {@literal @}EventHandler * public void preInit(FMLPreInitializationEvent event) { * MyTeBlock.registerTileEntities(); * } * * {@literal @}EventHandler * public void preInit(FMLInitializationEvent event) { * MyTeBlock.buildDummies(); * } *} * *import ic2.api.event.TeBlockFinalCallEvent; *import ic2.core.block.TeBlockRegistry; *import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; * *public enum TileEntityRegisterer { * INSTANCE; * * {@literal @}SubscribeEvent * public void register(TeBlockFinalCallEvent event) { * TeBlockRegistry.addAll(MyTeBlock.class, MyTeBlock.IDENTITY); * } *} * *import ic2.core.block.BlockTileEntity; *import ic2.core.block.ITeBlock; *import ic2.core.block.TileEntityBlock; *import ic2.core.item.block.ItemBlockTileEntity; *import ic2.core.ref.TeBlock.DefaultDrop; *import ic2.core.ref.TeBlock.HarvestTool; *import ic2.core.ref.TeBlock.ITePlaceHandler; *import ic2.core.util.Util; *import net.minecraft.block.material.Material; *import net.minecraft.creativetab.CreativeTabs; *import net.minecraft.item.EnumRarity; *import net.minecraft.item.ItemStack; *import net.minecraft.tileentity.TileEntity; *import net.minecraft.util.EnumFacing; *import net.minecraft.util.ResourceLocation; * *public enum MyTeBlock implements ITeBlock { * my_machine_name(MyMachineTileEntity.class, 0, false, Util.noFacings, false, HarvestTool.Pickaxe, DefaultDrop.Machine, 5, 10, EnumRarity.UNCOMMON, Material.IRON); * * private MyTeBlock(Class<? extends TileEntityBlock> teClass, int ID, * boolean hasActive, Set{@literal <}EnumFacing{@literal >} possibleFacings, boolean canBeWrenched, * HarvestTool tool, DefaultDrop drop, * float hardness, float explosionResistance, EnumRarity rarity, Material material) { * this.teClass = teClass; * this.ID = ID; * this.hasActive = hasActive; * this.possibleFacings = possibleFacings; * this.canBeWrenched = canBeWrenched; * this.tool = tool; * this.drop = drop; * this.hardness = hardness; * this.explosionResistance = explosionResistance; * this.rarity = rarity; * this.material = material; * } * * {@literal @}Override * public boolean hasItem() { * return teClass != null && itemMeta != -1; * } * * {@literal @}Override * public String getName() { * return name(); * } * * {@literal @}Override * public ResourceLocation getIdentifier() { * return IDENTITY; * } * * {@literal @}Override * public Class<? extends TileEntityBlock> getTeClass() { * return teClass; * } * * {@literal @}Override * public boolean hasActive() { * return hasActive; * } * * {@literal @}Override * public int getId() { * return ID; * } * * {@literal @}Override * public float getHardness() { * return hardness; * } * * {@literal @}Override * public HarvestTool getHarvestTool() { * return tool; * } * * {@literal @}Override * public DefaultDrop getDefaultDrop() { * return drop; * } * * {@literal @}Override * public float getExplosionResistance() { * return explosionResistance; * } * * {@literal @}Override * public boolean allowWrenchRotating() { * return canBeWrenched; * } * * {@literal @}Override * public Set{@literal <}EnumFacing{@literal >} getSupportedFacings() { * return possibleFacings; * } * * {@literal @}Override * public EnumRarity getRarity() { * return rarity; * } * * {@literal @}Override * public Material getMaterial() { * return material; * } * * {@literal @}Override * public void addSubBlocks(List{@literal <}ItemStack{@literal >} list, BlockTileEntity block, ItemBlockTileEntity item, CreativeTabs tab) { * for (MyTeBlock block : values()) { * if (type.hasItem()) { * list.add(block.getItemStack(type)); * } * } * } * * {@literal @}Override * public void setPlaceHandler(ITePlaceHandler handler) { * this.placeHandler = handler; * } * * {@literal @}Override * public ITePlaceHandler getPlaceHandler() { * return placeHandler; * } * * public static void registerTileEntities() { * for (MyTeBlock block : values()) { * if (block.teClass != null) TileEntity.addMapping(block.teClass, IDENTITY.getResourceDomain() + ':' + block.getName()); * } * } * * public static void buildDummies() { * for (MyTeBlock block : values()) { * //System.out.printf("Registering %s (with teClass %s)%n", block.getName(), block.teClass); * if (block.teClass != null) { * try { * block.dummyTe = block.teClass.newInstance(); * } catch (Exception e) { * e.printStackTrace(); * } * } * } * } * * {@literal @}Override * public TileEntityBlock getDummyTe() { * return dummyTe; * } * * private final Class<? extends TileEntityBlock> teClass; * private final int ID; * private final boolean hasActive; * private final Set{@literal <}EnumFacing{@literal >} possibleFacings; * private final boolean canBeWrenched; * private final HarvestTool tool; * private final DefaultDrop drop; * private final float hardness; * private final float explosionResistance; * private final EnumRarity rarity; * private final Material material; * private TileEntityBlock dummyTe; * private ITePlaceHandler placeHandler; * * public static final ResourceLocation IDENTITY = new ResourceLocation("ExampleIC2Addon", "machines"); *} * </code></pre></blockquote> * And that's it, you now have <code>my_machine_name</code> registered with the <code>MyMachineTileEntity</code> tile entity class, * the language key to translate it's name being ExampleIC2Addon.machines.my_machine_name and * the blockstate being in <code>machines.json</code> file in your mod's assets. * </p> * <hr> * <p> * But hang on, what are all the parameters of our new <code>enum</code> and what does <code>ITeBlock</code> do with them? What are dummy tile entities for? * Don't worry, it's quite simple (once you know it at least). * </p> * <p> * First we'll start on what {@link TeBlockFinalCallEvent} is. It's posted on the {@link MinecraftForge#EVENT_BUS} just before the blocks are built, * after which point any further attempts to register <code>ITeBlock</code>s will fail, as we can't inject them late due to the model generating. * It is best to hook into this to register your <code>ITeBlock</code>s, as it will be guaranteed to be posted at the right time. * <br/><br/> * In terms of <code>ITeBlock</code>, there's quite a bit of information it needs in order to function. We'll go through each parameter (or getter method most cases too) in turn: * <ul> * <li><b>name</b>: The name the new tile entity. This is important as the localisation and resource names depend on it, as well as some network syncing code.</li> * <li><b>teClass</b>: The class of your tile entity, it must extend <code>TileEntityBlock</code> otherwise it would miss critical methods to work. * If extending that is a problem then using <code>ITeBlock</code> isn't what you should be doing.</li> * <li><b>itemMeta</b>: The ID of the new instance. This is utterly critical, as it's the thing used to detect which <code>ITeBlock</code> an item is. * That's very important as the tile entity class is worked out by the ID when a block's being placed in <code>ItemBlockTileEntity</code>. * Changing this will cause everyone's items to change and there is no stopping that if you do. * The ID you pick should start at 0, and go up to Short.MAX_VALUE. * Use -1 if the tile entity doesn't have an item form (or is placed using an item other than <code>ItemBlockTileEntity</code>).</li> * <li><b>identifier</b>: The resource location associated with the <code>ITeBlock</code>. * The language keys, translations and internal mappings all use this, so it's best to store it as a static final variable and use that. * <li><b>hasActive</b>: If the tile entity has an active state too, which is based off whether <code>TileEntityBlock#getActive()</code> returns <code>true</code> or not. * The models for that will be at name_active, you can check <code>te.json</code> for an example if you wish.</li> * <li><b>supportedFacings</b>: A set of <code>EnumFacing</code>s that the block can face, used for rotating by the wrench for example. * IC2 has some useful constants relating to that in <code>Util</code> (allFacings, horizontalFacings, downSideFacings and noFacings).</li> * <li><b>allowWrenchRotating</b>: Whether the tile entity can be rotated with a wrench (for {@link IWrenchable}).</li> * <li><b>harvestTool</b>: The tool used to harvest the tile entity, currently only None, Pickaxe, Shovel and Axe. * More can be added on request, but support has to be specifically added, so there's no nice way via <code>EnumHelper</code> unfortunately.</li> * <li><b>defaultDrop</b>: The item(s) that will drop when the block is broken using the correct tool. Currently only Self, None, Generator, Machine, and AdvMachine. * Like <code>harvestTool</code>, more can be added upon request.</li> * <li><b>hardness</b>: The hardness the block should have with the tile entity, IC2 normally uses 5.</li> * <li><b>explosionResistance</b>: The explosionResistance the block should have with the tile entity, IC2 normally uses 10.</li> * <li><b>rarity</b>: The <code>EnumRarity</code> that the item will have for the tile entity.</li> * <li><b>material</b>: The {@link Material} that the block representing the tile entity should have. Maximum of 16 different ones per ITeBlock registration.</li> * <li><b>placeHandler</b>: Custom placement logic, used for things like Reactor Chambers within IC2 itself. * Returning null for this uses the default logic (placing like a normal block).</li> * <li><b>dummyTe</b>: An instance of the tile entity never registered to the world (don't try doing that) used for getting additional information about the Tile Entity. * Mostly an internal thing, only exposed in case your Tile Entity uses a special constructor.</li> * * <li><b>addSubBlocks</b>: Called by <code>BlockTileEntity</code> to add all the <code>ITeBlock</code>s you want to the creative menu. * {@link BlockTileEntity#getItemStack(ITeBlock)} will be a useful method to get the item stack, a block instance is passed for that reason. * This is only called once on a random <code>ITeBlock</code> for the resource location, because they are internally stored in a {@link Set} so has no order. * Will probably be changed to a static method if/when the move is made to only Java 8 support. * </ul> * <strong>IMPORTANT THINGS TO NOTE</strong> * <dl> * <dt>Getting your instance of <code>BlockTileEntity</code> and <code>ItemBlockTileEntity</code></dt> * <dd>For <code>BlockTileEntity</code>, use {@link TeBlockRegistry#get(ResourceLocation)}.<br/> * For <code>ItemBlockTileEntity</code>, use {@link BlockTileEntity#getItem()}.</dd> * <dt>Using a custom item model for your <code>ITeBlock</code></dt> * <dd>Implement <code>ITeBlockSpecialItem</code> along with <code>ITeBlock</code>, then the item model will be what's provided rather than the block model.</dd> * </dl> * More will be added to this list if questions keep re-occurring, or are about a suitably important topic. * </p> * <hr> * <p> * There, that should be everything you need to utilise <code>ITeBlock</code> to add your own tile entities using IC2's very flexible framework. * I'll be happy to answer any questions you have on it, your best bet is to ask me (Chocohead) on <a href="http://forum.industrial-craft.net">the IC2 forums</a>, * although if you post in the support section other people might be able to help before I see your post. * I'll certainly take suggestions too, this is a first version of <code>ITeBlock</code>, so I'm sure there could be improvements made. * <br/> * <small>Goodness I spent too long on this again...</small> * </p> * * * @see {@link TeBlockFinalCallEvent} for the event you'll need to subscribe to. * @see {@link ic2.core.ref.TeBlock} for how all the IC2 implements {@link ITeBlock}. * @see {@link ic2.core.ref.TeBlock.HarvestTool} for the currently available tools (you'll need this for adding new tile entities). * @see {@link ic2.core.ref.TeBlock.DefaultDrop} for the currently available drops (you'll need this for adding new tile entities too). * @see {@link ic2.core.ref.TeBlock.ITePlaceHandler} for making your own block placement handler (example in {@link ic2.core.item.ItemHandlers#reactorChamberPlace}). * @see {@link ic2.core.util.Util} for the useful facings you might want for <code>supportedFacings</code>. * @see {@link ic2.core.block.TileEntityBlock} for the base tile entity. * @see {@link ic2.core.block.BlockTileEntity} for the base block (you'll never need to construct this yourself). * @see {@link ic2.core.item.block.ItemBlockTileEntity} for the base item (you'll never need to construct this yourself either). * @see {@link ITeBlockSpecialItem} for the interface used to have a custom item location. * * * @since IC2 2.6.114 * @version 1.2 * * @author Chocohead */ public interface ITeBlock { }
UTF-8
Java
17,634
java
ITeBlock.java
Java
[ { "context": "\t@since IC2 2.6.114\n *\t@version 1.2\n *\n * @author Chocohead\n */\npublic interface ITeBlock {\n}", "end": 17600, "score": 0.9986453056335449, "start": 17591, "tag": "USERNAME", "value": "Chocohead" } ]
null
[]
package ic2.api.info; import java.util.Set; import net.minecraft.block.material.Material; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import ic2.api.event.TeBlockFinalCallEvent; import ic2.api.item.ITeBlockSpecialItem; import ic2.api.tile.IWrenchable; /** First of all, yes this class is empty. It's public documentation for the actual internal interface ITeBlock. <strong>Use the internal one not this!</strong> * <p> * You may be asking, why would an internal interface need documenting? Well, the answer is so people can use <code>TileEntityBlock</code>. * That class is the base for all IC2 tile entities, so by being able to use that you're level to IC2. * Many methods are protected in there too, as they're only designed to be called by <code>BlockTileEntity</code> (which is the block all IC2 tile entities will be on), * by being able to extend it means all those methods you can now extend and be confident they will be called correctly. * </p> * <p> * The more observant might have noticed there was an event that allowed you to do basically the same thing called <code>TeBlockBakeEvent</code>. * Whilst that event used to add your own class onto <code>TeBlock</code> (that wasn't ideal as you could end up using the same ID as another addon which would cause a crash), * this allows you to completely implement your own version of <code>TeBlock</code>, then let IC2 take it and build the necessary structures around it. * Both mean you no longer have to use <code>EnumHelper</code> and lots of reflection to mess about with <code>TeBlock</code>, * just to be left with either a crash from doing it too late/wrong, or lots of code bound to IC2 (such as language keys and blockstate jsons being in IC2's assets). * </p> * <p> * Unlike <code>TeBlockBakeEvent</code>, this gives you near total control of your tile entities: * <blockquote> * You can pick whether each of your tile entity items show up in creative, and the order in which they do.<br/> * You can choose whether you use an <code>enum</code> or <code>class</code> for your implementation. * We use (and I personally recommend) using an <code>enum</code>, as the values should never change, but in the end the choice is yours.<br/> * There is a proper separation between each registered <code>ITeBlock</code> by resource location, rather than everything being inserted into a single <code>enum</code>. * You also receive your own instance of <code>BlockTileEntity</code> and <code>ItemBlockTileEntity</code> rather than having to use IC2's own one.<br/> * All the language keys and blockstate file are in your own assets (which you can, and in fact have to, pick). * </blockquote> * It is a vast improvement over <code>TeBlockBakeEvent</code>, which is probably important as it's gone now ;) * </p> * <br/> * The event allows you to properly register your own version of <code>TeBlock</code> in a way that will be as fully supported as is physically possible. * It's not in the actual API itself as it's heavily dependent on internal classes, so you have this instead. * This is also probably the most documented thing in the entire IC2 API. <small>I'm too kind really. ;)</small> * </p> * <hr> * <p> * So that's all well and good, but what you really want is an example of how to do it properly. Good idea, let's go. * <blockquote><pre><code> *import net.minecraftforge.common.MinecraftForge; *import net.minecraftforge.fml.common.Mod; *import net.minecraftforge.fml.common.Mod.EventHandler; *import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; *import net.minecraftforge.fml.common.event.FMLInitializationEvent; * *{@literal @}Mod(modId="ExampleIC2Addon") *public class ExampleIC2Addon { * public ExampleIC2Addon() { * //You have to register before IC2 reaches Pre-Initialization, which unless you specifically load before it is unlikely you'll achieve. * //Especially if you're an addon, you'll want to be loading after IC2 not before! * //But, your mod's constructor will definitely be called before then. The issue is it's called more than once. * //If you try registering the same tile entity ID twice it will crash (more on that later), so you'll have to use a singleton instance. * //An enum works well for this, but anything will work as long as it's registered to the event bus once, and only once. * MinecraftForge.EVENT_BUS.register(TileEntityRegisterer.INSTANCE); * } * * {@literal @}EventHandler * public void preInit(FMLPreInitializationEvent event) { * MyTeBlock.registerTileEntities(); * } * * {@literal @}EventHandler * public void preInit(FMLInitializationEvent event) { * MyTeBlock.buildDummies(); * } *} * *import ic2.api.event.TeBlockFinalCallEvent; *import ic2.core.block.TeBlockRegistry; *import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; * *public enum TileEntityRegisterer { * INSTANCE; * * {@literal @}SubscribeEvent * public void register(TeBlockFinalCallEvent event) { * TeBlockRegistry.addAll(MyTeBlock.class, MyTeBlock.IDENTITY); * } *} * *import ic2.core.block.BlockTileEntity; *import ic2.core.block.ITeBlock; *import ic2.core.block.TileEntityBlock; *import ic2.core.item.block.ItemBlockTileEntity; *import ic2.core.ref.TeBlock.DefaultDrop; *import ic2.core.ref.TeBlock.HarvestTool; *import ic2.core.ref.TeBlock.ITePlaceHandler; *import ic2.core.util.Util; *import net.minecraft.block.material.Material; *import net.minecraft.creativetab.CreativeTabs; *import net.minecraft.item.EnumRarity; *import net.minecraft.item.ItemStack; *import net.minecraft.tileentity.TileEntity; *import net.minecraft.util.EnumFacing; *import net.minecraft.util.ResourceLocation; * *public enum MyTeBlock implements ITeBlock { * my_machine_name(MyMachineTileEntity.class, 0, false, Util.noFacings, false, HarvestTool.Pickaxe, DefaultDrop.Machine, 5, 10, EnumRarity.UNCOMMON, Material.IRON); * * private MyTeBlock(Class<? extends TileEntityBlock> teClass, int ID, * boolean hasActive, Set{@literal <}EnumFacing{@literal >} possibleFacings, boolean canBeWrenched, * HarvestTool tool, DefaultDrop drop, * float hardness, float explosionResistance, EnumRarity rarity, Material material) { * this.teClass = teClass; * this.ID = ID; * this.hasActive = hasActive; * this.possibleFacings = possibleFacings; * this.canBeWrenched = canBeWrenched; * this.tool = tool; * this.drop = drop; * this.hardness = hardness; * this.explosionResistance = explosionResistance; * this.rarity = rarity; * this.material = material; * } * * {@literal @}Override * public boolean hasItem() { * return teClass != null && itemMeta != -1; * } * * {@literal @}Override * public String getName() { * return name(); * } * * {@literal @}Override * public ResourceLocation getIdentifier() { * return IDENTITY; * } * * {@literal @}Override * public Class<? extends TileEntityBlock> getTeClass() { * return teClass; * } * * {@literal @}Override * public boolean hasActive() { * return hasActive; * } * * {@literal @}Override * public int getId() { * return ID; * } * * {@literal @}Override * public float getHardness() { * return hardness; * } * * {@literal @}Override * public HarvestTool getHarvestTool() { * return tool; * } * * {@literal @}Override * public DefaultDrop getDefaultDrop() { * return drop; * } * * {@literal @}Override * public float getExplosionResistance() { * return explosionResistance; * } * * {@literal @}Override * public boolean allowWrenchRotating() { * return canBeWrenched; * } * * {@literal @}Override * public Set{@literal <}EnumFacing{@literal >} getSupportedFacings() { * return possibleFacings; * } * * {@literal @}Override * public EnumRarity getRarity() { * return rarity; * } * * {@literal @}Override * public Material getMaterial() { * return material; * } * * {@literal @}Override * public void addSubBlocks(List{@literal <}ItemStack{@literal >} list, BlockTileEntity block, ItemBlockTileEntity item, CreativeTabs tab) { * for (MyTeBlock block : values()) { * if (type.hasItem()) { * list.add(block.getItemStack(type)); * } * } * } * * {@literal @}Override * public void setPlaceHandler(ITePlaceHandler handler) { * this.placeHandler = handler; * } * * {@literal @}Override * public ITePlaceHandler getPlaceHandler() { * return placeHandler; * } * * public static void registerTileEntities() { * for (MyTeBlock block : values()) { * if (block.teClass != null) TileEntity.addMapping(block.teClass, IDENTITY.getResourceDomain() + ':' + block.getName()); * } * } * * public static void buildDummies() { * for (MyTeBlock block : values()) { * //System.out.printf("Registering %s (with teClass %s)%n", block.getName(), block.teClass); * if (block.teClass != null) { * try { * block.dummyTe = block.teClass.newInstance(); * } catch (Exception e) { * e.printStackTrace(); * } * } * } * } * * {@literal @}Override * public TileEntityBlock getDummyTe() { * return dummyTe; * } * * private final Class<? extends TileEntityBlock> teClass; * private final int ID; * private final boolean hasActive; * private final Set{@literal <}EnumFacing{@literal >} possibleFacings; * private final boolean canBeWrenched; * private final HarvestTool tool; * private final DefaultDrop drop; * private final float hardness; * private final float explosionResistance; * private final EnumRarity rarity; * private final Material material; * private TileEntityBlock dummyTe; * private ITePlaceHandler placeHandler; * * public static final ResourceLocation IDENTITY = new ResourceLocation("ExampleIC2Addon", "machines"); *} * </code></pre></blockquote> * And that's it, you now have <code>my_machine_name</code> registered with the <code>MyMachineTileEntity</code> tile entity class, * the language key to translate it's name being ExampleIC2Addon.machines.my_machine_name and * the blockstate being in <code>machines.json</code> file in your mod's assets. * </p> * <hr> * <p> * But hang on, what are all the parameters of our new <code>enum</code> and what does <code>ITeBlock</code> do with them? What are dummy tile entities for? * Don't worry, it's quite simple (once you know it at least). * </p> * <p> * First we'll start on what {@link TeBlockFinalCallEvent} is. It's posted on the {@link MinecraftForge#EVENT_BUS} just before the blocks are built, * after which point any further attempts to register <code>ITeBlock</code>s will fail, as we can't inject them late due to the model generating. * It is best to hook into this to register your <code>ITeBlock</code>s, as it will be guaranteed to be posted at the right time. * <br/><br/> * In terms of <code>ITeBlock</code>, there's quite a bit of information it needs in order to function. We'll go through each parameter (or getter method most cases too) in turn: * <ul> * <li><b>name</b>: The name the new tile entity. This is important as the localisation and resource names depend on it, as well as some network syncing code.</li> * <li><b>teClass</b>: The class of your tile entity, it must extend <code>TileEntityBlock</code> otherwise it would miss critical methods to work. * If extending that is a problem then using <code>ITeBlock</code> isn't what you should be doing.</li> * <li><b>itemMeta</b>: The ID of the new instance. This is utterly critical, as it's the thing used to detect which <code>ITeBlock</code> an item is. * That's very important as the tile entity class is worked out by the ID when a block's being placed in <code>ItemBlockTileEntity</code>. * Changing this will cause everyone's items to change and there is no stopping that if you do. * The ID you pick should start at 0, and go up to Short.MAX_VALUE. * Use -1 if the tile entity doesn't have an item form (or is placed using an item other than <code>ItemBlockTileEntity</code>).</li> * <li><b>identifier</b>: The resource location associated with the <code>ITeBlock</code>. * The language keys, translations and internal mappings all use this, so it's best to store it as a static final variable and use that. * <li><b>hasActive</b>: If the tile entity has an active state too, which is based off whether <code>TileEntityBlock#getActive()</code> returns <code>true</code> or not. * The models for that will be at name_active, you can check <code>te.json</code> for an example if you wish.</li> * <li><b>supportedFacings</b>: A set of <code>EnumFacing</code>s that the block can face, used for rotating by the wrench for example. * IC2 has some useful constants relating to that in <code>Util</code> (allFacings, horizontalFacings, downSideFacings and noFacings).</li> * <li><b>allowWrenchRotating</b>: Whether the tile entity can be rotated with a wrench (for {@link IWrenchable}).</li> * <li><b>harvestTool</b>: The tool used to harvest the tile entity, currently only None, Pickaxe, Shovel and Axe. * More can be added on request, but support has to be specifically added, so there's no nice way via <code>EnumHelper</code> unfortunately.</li> * <li><b>defaultDrop</b>: The item(s) that will drop when the block is broken using the correct tool. Currently only Self, None, Generator, Machine, and AdvMachine. * Like <code>harvestTool</code>, more can be added upon request.</li> * <li><b>hardness</b>: The hardness the block should have with the tile entity, IC2 normally uses 5.</li> * <li><b>explosionResistance</b>: The explosionResistance the block should have with the tile entity, IC2 normally uses 10.</li> * <li><b>rarity</b>: The <code>EnumRarity</code> that the item will have for the tile entity.</li> * <li><b>material</b>: The {@link Material} that the block representing the tile entity should have. Maximum of 16 different ones per ITeBlock registration.</li> * <li><b>placeHandler</b>: Custom placement logic, used for things like Reactor Chambers within IC2 itself. * Returning null for this uses the default logic (placing like a normal block).</li> * <li><b>dummyTe</b>: An instance of the tile entity never registered to the world (don't try doing that) used for getting additional information about the Tile Entity. * Mostly an internal thing, only exposed in case your Tile Entity uses a special constructor.</li> * * <li><b>addSubBlocks</b>: Called by <code>BlockTileEntity</code> to add all the <code>ITeBlock</code>s you want to the creative menu. * {@link BlockTileEntity#getItemStack(ITeBlock)} will be a useful method to get the item stack, a block instance is passed for that reason. * This is only called once on a random <code>ITeBlock</code> for the resource location, because they are internally stored in a {@link Set} so has no order. * Will probably be changed to a static method if/when the move is made to only Java 8 support. * </ul> * <strong>IMPORTANT THINGS TO NOTE</strong> * <dl> * <dt>Getting your instance of <code>BlockTileEntity</code> and <code>ItemBlockTileEntity</code></dt> * <dd>For <code>BlockTileEntity</code>, use {@link TeBlockRegistry#get(ResourceLocation)}.<br/> * For <code>ItemBlockTileEntity</code>, use {@link BlockTileEntity#getItem()}.</dd> * <dt>Using a custom item model for your <code>ITeBlock</code></dt> * <dd>Implement <code>ITeBlockSpecialItem</code> along with <code>ITeBlock</code>, then the item model will be what's provided rather than the block model.</dd> * </dl> * More will be added to this list if questions keep re-occurring, or are about a suitably important topic. * </p> * <hr> * <p> * There, that should be everything you need to utilise <code>ITeBlock</code> to add your own tile entities using IC2's very flexible framework. * I'll be happy to answer any questions you have on it, your best bet is to ask me (Chocohead) on <a href="http://forum.industrial-craft.net">the IC2 forums</a>, * although if you post in the support section other people might be able to help before I see your post. * I'll certainly take suggestions too, this is a first version of <code>ITeBlock</code>, so I'm sure there could be improvements made. * <br/> * <small>Goodness I spent too long on this again...</small> * </p> * * * @see {@link TeBlockFinalCallEvent} for the event you'll need to subscribe to. * @see {@link ic2.core.ref.TeBlock} for how all the IC2 implements {@link ITeBlock}. * @see {@link ic2.core.ref.TeBlock.HarvestTool} for the currently available tools (you'll need this for adding new tile entities). * @see {@link ic2.core.ref.TeBlock.DefaultDrop} for the currently available drops (you'll need this for adding new tile entities too). * @see {@link ic2.core.ref.TeBlock.ITePlaceHandler} for making your own block placement handler (example in {@link ic2.core.item.ItemHandlers#reactorChamberPlace}). * @see {@link ic2.core.util.Util} for the useful facings you might want for <code>supportedFacings</code>. * @see {@link ic2.core.block.TileEntityBlock} for the base tile entity. * @see {@link ic2.core.block.BlockTileEntity} for the base block (you'll never need to construct this yourself). * @see {@link ic2.core.item.block.ItemBlockTileEntity} for the base item (you'll never need to construct this yourself either). * @see {@link ITeBlockSpecialItem} for the interface used to have a custom item location. * * * @since IC2 2.6.114 * @version 1.2 * * @author Chocohead */ public interface ITeBlock { }
17,634
0.721561
0.717818
344
50.264534
50.80872
178
false
false
0
0
0
0
0
0
1.854651
false
false
15