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
121edab1b713a02f6b5aec9aa3d265b6cf129568
29,884,382,497,675
d27baf9c56f85d4386e1c847f0ab5e5b69225425
/src/main/java/com/jc/jc_backer/Websocket/WebsocketServer.java
80afc49aadce7884b80055fa4783890846c3a74e
[]
no_license
chenzhichengczc/gzjc_backer
https://github.com/chenzhichengczc/gzjc_backer
42a381c49385631366897f41883596c7a405b8d4
802a9f1e4d8510b77f061db9984519e24f074b27
refs/heads/master
2020-04-28T14:00:27.079000
2019-04-30T06:49:25
2019-04-30T06:49:25
175,324,167
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jc.jc_backer.Websocket; import com.jc.jc_backer.common.utils.FilePath; import com.jc.jc_backer.common.utils.TailLogUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author :fenghuang * @date :Created in 2019/4/18 11:46 * @description:websocket服务器端 * @modified By: * @version: */ @Component @ServerEndpoint("/getInfoLog") public class WebsocketServer { private static final Logger logger = LoggerFactory.getLogger(WebsocketServer.class); private List<Session> sessionList = new ArrayList<>(); @OnOpen public void open(Session session){ //把每一个连入当前url的session加入到集合里面 sessionList.add(session); try { TailLogUtil tailLogThread = new TailLogUtil(session, FilePath.INFO_PATH); tailLogThread.start(); } catch (Exception e) { e.printStackTrace(); } } @OnMessage public void message(Session session,String message){ System.out.println("message = " + message); } @OnClose public void close(Session session){ try { session.close(); } catch (IOException e) { e.printStackTrace(); } sessionList.remove(session); } @OnError public void onError(Throwable thr) { thr.printStackTrace(); } }
UTF-8
Java
1,601
java
WebsocketServer.java
Java
[ { "context": "rrayList;\nimport java.util.List;\n\n/**\n * @author :fenghuang\n * @date :Created in 2019/4/18 11:46\n * @descript", "end": 447, "score": 0.9919885396957397, "start": 438, "tag": "USERNAME", "value": "fenghuang" } ]
null
[]
package com.jc.jc_backer.Websocket; import com.jc.jc_backer.common.utils.FilePath; import com.jc.jc_backer.common.utils.TailLogUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author :fenghuang * @date :Created in 2019/4/18 11:46 * @description:websocket服务器端 * @modified By: * @version: */ @Component @ServerEndpoint("/getInfoLog") public class WebsocketServer { private static final Logger logger = LoggerFactory.getLogger(WebsocketServer.class); private List<Session> sessionList = new ArrayList<>(); @OnOpen public void open(Session session){ //把每一个连入当前url的session加入到集合里面 sessionList.add(session); try { TailLogUtil tailLogThread = new TailLogUtil(session, FilePath.INFO_PATH); tailLogThread.start(); } catch (Exception e) { e.printStackTrace(); } } @OnMessage public void message(Session session,String message){ System.out.println("message = " + message); } @OnClose public void close(Session session){ try { session.close(); } catch (IOException e) { e.printStackTrace(); } sessionList.remove(session); } @OnError public void onError(Throwable thr) { thr.printStackTrace(); } }
1,601
0.667096
0.658725
63
23.650793
19.92857
88
false
false
0
0
0
0
0
0
0.396825
false
false
13
930bc3642e48ca503371cb1134a3140c683dd93e
11,433,202,950,585
1ba27fc930ba20782e9ef703e0dc7b69391e191b
/Src/UserMgmt/src/main/java/com/compuware/caqs/security/stats/ConnectionStatData.java
be629ce08e4d9a54333a16d69974e271dd89aac4
[]
no_license
LO-RAN/codeQualityPortal
https://github.com/LO-RAN/codeQualityPortal
b0d81c76968bdcfce659959d0122e398c647b09f
a7c26209a616d74910f88ce0d60a6dc148dda272
refs/heads/master
2023-07-11T18:39:04.819000
2022-03-31T15:37:56
2022-03-31T15:37:56
37,261,337
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.compuware.caqs.security.stats; import java.util.Calendar; /** * Connection statistics including the day, the total number of connections and the maximum * simultaneous connections. * @author cwfr-fdubois */ public class ConnectionStatData { /** The day of the statistics. */ private Calendar day; /** The total number of connections for the day. */ private int sumNbUser; /** The maximum simultaneous connections for the day. */ private int maxNbUser; /** * Constructor with every data as parameters. * @param day the statistics day. * @param sumNbUser the total number of connections for the day. * @param maxNbUser the maximum simultaneous connections for the day. */ public ConnectionStatData(Calendar day, int sumNbUser, int maxNbUser) { this.day = day; this.sumNbUser = sumNbUser; this.maxNbUser = maxNbUser; } /** * Get the statistics day. * @return the statistics day. */ public Calendar getDay() { return day; } /** * Set the statistics day. * @param day the statistics day. */ public void setDay(Calendar day) { this.day = day; } /** * Get the maximum simultaneous connections for the day. * @return the maximum simultaneous connections for the day. */ public int getMaxNbUser() { return maxNbUser; } /** * Set the maximum simultaneous connections for the day. * @param maxNbUser the maximum simultaneous connections for the day. */ public void setMaxNbUser(int maxNbUser) { this.maxNbUser = maxNbUser; } /** * Get the total number of connections for the day. * @return the total number of connections for the day. */ public int getSumNbUser() { return sumNbUser; } /** * Set the total number of connections for the day. * @param sumNbUser the total number of connections for the day. */ public void setSumNbUser(int sumNbUser) { this.sumNbUser = sumNbUser; } }
UTF-8
Java
2,196
java
ConnectionStatData.java
Java
[ { "context": "he maximum\n * simultaneous connections.\n * @author cwfr-fdubois\n */\npublic class ConnectionStatData {\n\n /** Th", "end": 321, "score": 0.9989719986915588, "start": 309, "tag": "USERNAME", "value": "cwfr-fdubois" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.compuware.caqs.security.stats; import java.util.Calendar; /** * Connection statistics including the day, the total number of connections and the maximum * simultaneous connections. * @author cwfr-fdubois */ public class ConnectionStatData { /** The day of the statistics. */ private Calendar day; /** The total number of connections for the day. */ private int sumNbUser; /** The maximum simultaneous connections for the day. */ private int maxNbUser; /** * Constructor with every data as parameters. * @param day the statistics day. * @param sumNbUser the total number of connections for the day. * @param maxNbUser the maximum simultaneous connections for the day. */ public ConnectionStatData(Calendar day, int sumNbUser, int maxNbUser) { this.day = day; this.sumNbUser = sumNbUser; this.maxNbUser = maxNbUser; } /** * Get the statistics day. * @return the statistics day. */ public Calendar getDay() { return day; } /** * Set the statistics day. * @param day the statistics day. */ public void setDay(Calendar day) { this.day = day; } /** * Get the maximum simultaneous connections for the day. * @return the maximum simultaneous connections for the day. */ public int getMaxNbUser() { return maxNbUser; } /** * Set the maximum simultaneous connections for the day. * @param maxNbUser the maximum simultaneous connections for the day. */ public void setMaxNbUser(int maxNbUser) { this.maxNbUser = maxNbUser; } /** * Get the total number of connections for the day. * @return the total number of connections for the day. */ public int getSumNbUser() { return sumNbUser; } /** * Set the total number of connections for the day. * @param sumNbUser the total number of connections for the day. */ public void setSumNbUser(int sumNbUser) { this.sumNbUser = sumNbUser; } }
2,196
0.638889
0.638889
86
24.534883
23.323158
91
false
false
0
0
0
0
0
0
0.22093
false
false
13
5f8b20507f1b108f2bd75350ae5a092ca5ea72d5
13,804,024,942,963
c3b089b363237a00fad8c1514ba501dfcbdbaf34
/src/com/company/query/QueryPrintAll.java
2e28c36d8911c9cfd87231ebb348c4748dd6bd27
[]
no_license
nataliesmithmsm/MileStone2v2
https://github.com/nataliesmithmsm/MileStone2v2
df3cd4f1bc431aad680151333704ea50e51ed350
ceaa6ae393ccf935eb57d952579d4491b362f616
refs/heads/master
2021-08-20T07:11:00.683000
2017-11-28T13:43:13
2017-11-28T13:43:13
111,912,251
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.query; import com.company.Mongo.ConnectionToMongo; import com.company.dataobjects.PersonalDetails; import com.mongodb.*; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class QueryPrintAll { public List<PersonalDetails> printAllDocuments() throws IOException { ObjectMapper mapper = new ObjectMapper(); List <PersonalDetails> profileList = new ArrayList<>(); MongoCollection<BasicDBObject> allProfiles = ConnectionToMongo.connection(); MongoCursor<BasicDBObject> cursor = allProfiles.find().iterator(); while (cursor.hasNext()) { String profiles = cursor.next().toString(); profileList.add(getAllProfiles(mapper, profiles.toString())); System.out.println(profiles); } return profileList; } private PersonalDetails getAllProfiles(ObjectMapper mapper, String profiles) throws IOException { return mapper.readValue(profiles, PersonalDetails.class); } }
UTF-8
Java
1,163
java
QueryPrintAll.java
Java
[]
null
[]
package com.company.query; import com.company.Mongo.ConnectionToMongo; import com.company.dataobjects.PersonalDetails; import com.mongodb.*; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class QueryPrintAll { public List<PersonalDetails> printAllDocuments() throws IOException { ObjectMapper mapper = new ObjectMapper(); List <PersonalDetails> profileList = new ArrayList<>(); MongoCollection<BasicDBObject> allProfiles = ConnectionToMongo.connection(); MongoCursor<BasicDBObject> cursor = allProfiles.find().iterator(); while (cursor.hasNext()) { String profiles = cursor.next().toString(); profileList.add(getAllProfiles(mapper, profiles.toString())); System.out.println(profiles); } return profileList; } private PersonalDetails getAllProfiles(ObjectMapper mapper, String profiles) throws IOException { return mapper.readValue(profiles, PersonalDetails.class); } }
1,163
0.72485
0.72485
38
29.605263
28.347969
101
false
false
0
0
0
0
0
0
0.578947
false
false
13
24a69c492fa8cfb1edbefd1c69b846c867bef47a
18,210,661,335,721
5dd839a53a1ad5fb3df2b60c4f796bcdc6f06bee
/app/src/main/java/com/example/sid/NotesCrypt/utils/SessionListener.java
4eb935eb082d44d851df9721e95fd9533f26390b
[]
no_license
sidstk/NotesCrypt
https://github.com/sidstk/NotesCrypt
9415472bbd8040b236fd7b3a13b34d6e037700c2
848072637459187d0734c7641081ee1b20eb658c
refs/heads/master
2020-03-24T21:01:16.965000
2018-10-18T12:47:38
2018-10-18T12:47:38
143,008,464
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sid.NotesCrypt.utils; public interface SessionListener { void foregroundSessionExpired(); void backgroundSessionExpired(); }
UTF-8
Java
155
java
SessionListener.java
Java
[]
null
[]
package com.example.sid.NotesCrypt.utils; public interface SessionListener { void foregroundSessionExpired(); void backgroundSessionExpired(); }
155
0.780645
0.780645
7
21.142857
18.129917
41
false
false
0
0
0
0
0
0
0.428571
false
false
13
b874b706de64cbeb856ab08fc46fc8505bc1ea7b
17,274,358,471,744
92211e55abe46244bfe02b25cb29045ad25be473
/runescape-client/src/main/java/class1.java
bcbbdf0da83ff17cb1bc205830f92e8bc3e26091
[ "BSD-2-Clause" ]
permissive
pombredanne/runelite
https://github.com/pombredanne/runelite
474ff52394cef7fddf827b15b38a570dd0f107dc
c86e63ea780b2fbf97d30bd506354deeb94524d2
refs/heads/master
2018-04-27T10:32:12.263000
2017-05-19T16:19:40
2017-05-19T16:20:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("c") public class class1 { @ObfuscatedName("c") public static Comparator field11; @ObfuscatedName("n") public static Comparator field12; @ObfuscatedName("q") public static Comparator field13; @ObfuscatedName("t") public static Comparator field14; @ObfuscatedName("d") public final List field15; @ObfuscatedName("fv") @ObfuscatedGetter( intValue = 2019010125 ) @Export("cameraZ") static int cameraZ; @ObfuscatedName("hw") @ObfuscatedGetter( intValue = 920665721 ) @Export("menuY") static int menuY; @ObfuscatedName("t") @ObfuscatedSignature( signature = "(III)V", garbageValue = "-983407984" ) static void method15(int var0, int var1) { long var2 = (long)(var1 + (var0 << 16)); class183 var4 = (class183)class187.field2771.method2773(var2); if(var4 != null) { class187.field2758.method2714(var4); } } @ObfuscatedName("d") @ObfuscatedSignature( signature = "(Ljava/util/Comparator;ZI)V", garbageValue = "2113961692" ) public void method16(Comparator var1, boolean var2) { if(var2) { Collections.sort(this.field15, var1); } else { Collections.sort(this.field15, Collections.reverseOrder(var1)); } } static { field11 = new class7(); new class0(); field12 = new class5(); field13 = new class6(); field14 = new class3(); } @ObfuscatedSignature( signature = "(LBuffer;Z)V", garbageValue = "1" ) public class1(Buffer var1, boolean var2) { int var3 = var1.readUnsignedShort(); boolean var4 = var1.readUnsignedByte() == 1; byte var5; if(var4) { var5 = 1; } else { var5 = 0; } int var6 = var1.readUnsignedShort(); this.field15 = new ArrayList(var6); for(int var7 = 0; var7 < var6; ++var7) { this.field15.add(new class2(var1, var5, var3)); } } }
UTF-8
Java
2,286
java
class1.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("c") public class class1 { @ObfuscatedName("c") public static Comparator field11; @ObfuscatedName("n") public static Comparator field12; @ObfuscatedName("q") public static Comparator field13; @ObfuscatedName("t") public static Comparator field14; @ObfuscatedName("d") public final List field15; @ObfuscatedName("fv") @ObfuscatedGetter( intValue = 2019010125 ) @Export("cameraZ") static int cameraZ; @ObfuscatedName("hw") @ObfuscatedGetter( intValue = 920665721 ) @Export("menuY") static int menuY; @ObfuscatedName("t") @ObfuscatedSignature( signature = "(III)V", garbageValue = "-983407984" ) static void method15(int var0, int var1) { long var2 = (long)(var1 + (var0 << 16)); class183 var4 = (class183)class187.field2771.method2773(var2); if(var4 != null) { class187.field2758.method2714(var4); } } @ObfuscatedName("d") @ObfuscatedSignature( signature = "(Ljava/util/Comparator;ZI)V", garbageValue = "2113961692" ) public void method16(Comparator var1, boolean var2) { if(var2) { Collections.sort(this.field15, var1); } else { Collections.sort(this.field15, Collections.reverseOrder(var1)); } } static { field11 = new class7(); new class0(); field12 = new class5(); field13 = new class6(); field14 = new class3(); } @ObfuscatedSignature( signature = "(LBuffer;Z)V", garbageValue = "1" ) public class1(Buffer var1, boolean var2) { int var3 = var1.readUnsignedShort(); boolean var4 = var1.readUnsignedByte() == 1; byte var5; if(var4) { var5 = 1; } else { var5 = 0; } int var6 = var1.readUnsignedShort(); this.field15 = new ArrayList(var6); for(int var7 = 0; var7 < var6; ++var7) { this.field15.add(new class2(var1, var5, var3)); } } }
2,286
0.629484
0.566054
92
23.847826
16.484468
72
false
false
0
0
0
0
0
0
0.51087
false
false
13
0750fcf7472ae8c440e6ee7e3095459668311ce6
21,483,426,433,694
e35643efb8ee4f1a9d2336a23b86c6b15db899dc
/src/com/codegym/FizzBuzzTranslate.java
338504c71cc5cda2d33518959ccca2111f1d269b
[]
no_license
thaophamhetxat/FizzBuzzTranslate
https://github.com/thaophamhetxat/FizzBuzzTranslate
0eee386013a09999b42ac09d540a6f3a09f7b033
ccc916630623face8f51374c98f4a98f3dd3d785
refs/heads/master
2023-06-10T13:21:14.058000
2021-06-14T04:05:04
2021-06-14T04:05:04
376,698,548
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codegym; public class FizzBuzzTranslate { public static String translate(int number) { if (number < 10) { switch (number) { case 1: System.out.println("mot"); break; case 2: System.out.println("hai"); break; case 3: System.out.println("ba"); break; case 4: System.out.println("bon"); break; case 5: System.out.println("nam"); break; case 6: System.out.println("sau"); break; case 7: System.out.println("bay"); break; case 8: System.out.println("tam"); break; case 9: System.out.println("chin"); break; } } return "mot"; } }
UTF-8
Java
1,098
java
FizzBuzzTranslate.java
Java
[]
null
[]
package com.codegym; public class FizzBuzzTranslate { public static String translate(int number) { if (number < 10) { switch (number) { case 1: System.out.println("mot"); break; case 2: System.out.println("hai"); break; case 3: System.out.println("ba"); break; case 4: System.out.println("bon"); break; case 5: System.out.println("nam"); break; case 6: System.out.println("sau"); break; case 7: System.out.println("bay"); break; case 8: System.out.println("tam"); break; case 9: System.out.println("chin"); break; } } return "mot"; } }
1,098
0.339709
0.32969
39
27.153847
13.489861
48
false
false
0
0
0
0
0
0
0.512821
false
false
13
5a594b6191c78f35f726d6b6c4643fd1ccf8f9ca
24,215,025,682,791
1dd48d3ff66359438f4a23b54dfd04989b4fe24a
/leetcode/medium6/Solution491.java
725fdbb7c15c927ba7606567e6b30da74ebebb82
[]
no_license
luyou86/algorithm
https://github.com/luyou86/algorithm
4d6760bd30b48bafa9f1e60447617e467ab4eb3e
3cfd0e4aa42857ffbde1f99318c1ad27ca980487
refs/heads/master
2021-10-22T22:45:07.386000
2019-03-13T08:43:36
2019-03-13T08:43:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithm.medium6; import org.junit.Test; import java.util.*; /** * Created by youlu on 2018/10/12. */ public class Solution491 { public void search(List<List<Integer>> result, List<Integer> list, int[] nums, int index){ if(index >= nums.length){ return; } int i = index, count = 0; if(i + 1 < nums.length && nums[i] == nums[i+1]){ list.add(nums[i]); result.add(new ArrayList<>(list)); list.remove(list.size() - 1); } while (i + 1 < nums.length && nums[i] == nums[i+1]){ list.add(nums[i]); i++; count++; } if(i + 1 == nums.length && nums[i] == nums[i-1]){ list.add(nums[i]); count++; i++; } if(i != index) { result.add(new ArrayList<>(list)); search(result, list, nums, i); while (count > 0) { list.remove(list.size() - 1); count--; } } for(int j = i; j < nums.length; j++) { if (nums[j] >= list.get(list.size() - 1)) { if (j + 1 < nums.length && nums[j] == nums[j + 1]) { search(result, list, nums, j); } else { if (nums[j] != nums[j - 1]) { list.add(nums[j]); search(result, list, nums, j + 1); list.remove(list.size() - 1); } } } } } public void search1(List<List<Integer>> result, List<Integer> list, int[] nums, int index){ if(index >= nums.length){ return; } for(int i = index; i < nums.length; i++){ if(nums[i] >= list.get(list.size() - 1)) { if(nums[i] == nums[i-1] && list.get(list.size() - 1) != nums[i]){ continue; } if (i + 1 < nums.length && nums[i] == nums[i + 1] && nums[i] != nums[i-1]) { list.add(nums[i]); result.add(new ArrayList<>(list)); list.remove(list.size() - 1); int temp = i, count = 0; while (temp + 1 < nums.length && nums[temp] == nums[temp + 1]) { list.add(nums[temp]); count++; temp++; } if (temp + 1 == nums.length && nums[temp] == nums[temp - 1]) { list.add(nums[temp]); temp++; count++; } if (temp != i) { result.add(new ArrayList<>(list)); search1(result, list, nums, temp); while (count > 0) { list.remove(list.size() - 1); count--; } } }else{ list.add(nums[i]); result.add(new ArrayList<>(list)); search1(result,list, nums, i+1); list.remove(list.size() - 1); } } } } public void search2(List<List<Integer>> result, List<Integer> list, int[] nums, int index){ if(index >= nums.length){ return; } for(int i = index; i < nums.length; i++){ if(nums[i] >= list.get(list.size() - 1)){ if(nums[i] == nums[i-1] && list.get(list.size() - 1) != nums[i]){ continue; } list.add(nums[i]); result.add(new ArrayList<>(list)); search2(result, list, nums, i+1); list.remove(list.size() - 1); } } } public void search3(Set<String> set, String str, int[] nums, int index){ if(index >= nums.length){ return; } int lastNumberIndex = str.length() - 1; while (lastNumberIndex >= 0 ){ char ch = str.charAt(lastNumberIndex); if(ch != ':'){ lastNumberIndex--; }else { break; } } String subStr = str.substring(lastNumberIndex + 1, str.length()); int value = Integer.parseInt(subStr); for(int i = index; i < nums.length; i++){ if(nums[i] >= value){ String next = str; next += Character.toString(':'); String temp = Integer.toString(nums[i]); next += temp; set.add(next); search3(set, next, nums, i+1); } } } //Accepted ---- 139ms /* not effecient */ public List<List<Integer>> findSubsequences(int[] nums){ if(nums.length == 0 || nums == null){ return new ArrayList<>(); } Set<String> set = new HashSet<>(); List<List<Integer>> result = new ArrayList<>(); for(int i = 0; i < nums.length; i++){ String str = ""; str += Integer.toString(nums[i]); search3(set, str, nums, i + 1); } for(String str : set){ List<Integer> list = new ArrayList<>(); String[] numbers = str.split(":"); for(int i = 0; i < numbers.length; i++){ list.add(Integer.parseInt(numbers[i])); } result.add(list); } return result; } @Test public void test(){ // int[] nums = {4,6,7,7}; // int[] nums = {4,3,2,1}; // int[] nums = {1,2,3,8,8}; // int[] nums = {1,2,3,4,5,6,7,8,9,10,1,1,1,1,1}; // int[] nums = {1,2,3,1,1}; int[] nums = {-100,-99,-98,-97,-96,-96}; long startTime = System.currentTimeMillis(); List<List<Integer>> result = findSubsequences(nums); long endTime = System.currentTimeMillis(); for(int i = 0; i < result.size(); i++){ for(int j = 0; j < result.get(i).size(); j++){ System.out.print(result.get(i).get(j) + " "); } System.out.println(); } /* for(String str : set){ for(int i = 0; i < str.length(); i++){ System.out.print(str.charAt(i)); } System.out.println(); }*/ System.out.println("running time : " + (endTime - startTime)); } @Test public void test1(){ System.out.print(Integer.parseInt(Integer.toString(-1000))); } }
UTF-8
Java
6,679
java
Solution491.java
Java
[ { "context": "unit.Test;\n\nimport java.util.*;\n\n/**\n * Created by youlu on 2018/10/12.\n */\npublic class Solution491 {\n ", "end": 96, "score": 0.9662453532218933, "start": 91, "tag": "USERNAME", "value": "youlu" } ]
null
[]
package algorithm.medium6; import org.junit.Test; import java.util.*; /** * Created by youlu on 2018/10/12. */ public class Solution491 { public void search(List<List<Integer>> result, List<Integer> list, int[] nums, int index){ if(index >= nums.length){ return; } int i = index, count = 0; if(i + 1 < nums.length && nums[i] == nums[i+1]){ list.add(nums[i]); result.add(new ArrayList<>(list)); list.remove(list.size() - 1); } while (i + 1 < nums.length && nums[i] == nums[i+1]){ list.add(nums[i]); i++; count++; } if(i + 1 == nums.length && nums[i] == nums[i-1]){ list.add(nums[i]); count++; i++; } if(i != index) { result.add(new ArrayList<>(list)); search(result, list, nums, i); while (count > 0) { list.remove(list.size() - 1); count--; } } for(int j = i; j < nums.length; j++) { if (nums[j] >= list.get(list.size() - 1)) { if (j + 1 < nums.length && nums[j] == nums[j + 1]) { search(result, list, nums, j); } else { if (nums[j] != nums[j - 1]) { list.add(nums[j]); search(result, list, nums, j + 1); list.remove(list.size() - 1); } } } } } public void search1(List<List<Integer>> result, List<Integer> list, int[] nums, int index){ if(index >= nums.length){ return; } for(int i = index; i < nums.length; i++){ if(nums[i] >= list.get(list.size() - 1)) { if(nums[i] == nums[i-1] && list.get(list.size() - 1) != nums[i]){ continue; } if (i + 1 < nums.length && nums[i] == nums[i + 1] && nums[i] != nums[i-1]) { list.add(nums[i]); result.add(new ArrayList<>(list)); list.remove(list.size() - 1); int temp = i, count = 0; while (temp + 1 < nums.length && nums[temp] == nums[temp + 1]) { list.add(nums[temp]); count++; temp++; } if (temp + 1 == nums.length && nums[temp] == nums[temp - 1]) { list.add(nums[temp]); temp++; count++; } if (temp != i) { result.add(new ArrayList<>(list)); search1(result, list, nums, temp); while (count > 0) { list.remove(list.size() - 1); count--; } } }else{ list.add(nums[i]); result.add(new ArrayList<>(list)); search1(result,list, nums, i+1); list.remove(list.size() - 1); } } } } public void search2(List<List<Integer>> result, List<Integer> list, int[] nums, int index){ if(index >= nums.length){ return; } for(int i = index; i < nums.length; i++){ if(nums[i] >= list.get(list.size() - 1)){ if(nums[i] == nums[i-1] && list.get(list.size() - 1) != nums[i]){ continue; } list.add(nums[i]); result.add(new ArrayList<>(list)); search2(result, list, nums, i+1); list.remove(list.size() - 1); } } } public void search3(Set<String> set, String str, int[] nums, int index){ if(index >= nums.length){ return; } int lastNumberIndex = str.length() - 1; while (lastNumberIndex >= 0 ){ char ch = str.charAt(lastNumberIndex); if(ch != ':'){ lastNumberIndex--; }else { break; } } String subStr = str.substring(lastNumberIndex + 1, str.length()); int value = Integer.parseInt(subStr); for(int i = index; i < nums.length; i++){ if(nums[i] >= value){ String next = str; next += Character.toString(':'); String temp = Integer.toString(nums[i]); next += temp; set.add(next); search3(set, next, nums, i+1); } } } //Accepted ---- 139ms /* not effecient */ public List<List<Integer>> findSubsequences(int[] nums){ if(nums.length == 0 || nums == null){ return new ArrayList<>(); } Set<String> set = new HashSet<>(); List<List<Integer>> result = new ArrayList<>(); for(int i = 0; i < nums.length; i++){ String str = ""; str += Integer.toString(nums[i]); search3(set, str, nums, i + 1); } for(String str : set){ List<Integer> list = new ArrayList<>(); String[] numbers = str.split(":"); for(int i = 0; i < numbers.length; i++){ list.add(Integer.parseInt(numbers[i])); } result.add(list); } return result; } @Test public void test(){ // int[] nums = {4,6,7,7}; // int[] nums = {4,3,2,1}; // int[] nums = {1,2,3,8,8}; // int[] nums = {1,2,3,4,5,6,7,8,9,10,1,1,1,1,1}; // int[] nums = {1,2,3,1,1}; int[] nums = {-100,-99,-98,-97,-96,-96}; long startTime = System.currentTimeMillis(); List<List<Integer>> result = findSubsequences(nums); long endTime = System.currentTimeMillis(); for(int i = 0; i < result.size(); i++){ for(int j = 0; j < result.get(i).size(); j++){ System.out.print(result.get(i).get(j) + " "); } System.out.println(); } /* for(String str : set){ for(int i = 0; i < str.length(); i++){ System.out.print(str.charAt(i)); } System.out.println(); }*/ System.out.println("running time : " + (endTime - startTime)); } @Test public void test1(){ System.out.print(Integer.parseInt(Integer.toString(-1000))); } }
6,679
0.408295
0.389879
219
29.497717
22.931181
97
false
false
0
0
0
0
0
0
0.817352
false
false
13
e36b0a876d3b5be595f6eda075f33cd4554dd4d4
4,398,046,521,221
792f8ac63929160c42f8b6708bcb5ddecd4c27f4
/app/src/main/java/lv/krokyze/graffiti_programmr/GraffitiDetailsActivity.java
1f9ddb15bbffc8e0f4a28c16afdf22b8ed9618ba
[]
no_license
krokyze/San-Francisco-Graffiti
https://github.com/krokyze/San-Francisco-Graffiti
e7ed6eab7a086190f1fe89f4106b7f6dacf8f96b
77164e47f6068218417397bd394f9e24394081cc
HEAD
2016-09-07T12:09:03.039000
2014-09-29T20:06:55
2014-09-29T20:06:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lv.krokyze.graffiti_programmr; import android.app.Activity; import android.app.FragmentTransaction; import android.os.Bundle; public class GraffitiDetailsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getFragmentManager().beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .replace(R.id.container, new GraffitiDetailsFragment()) .commit(); } }
UTF-8
Java
587
java
GraffitiDetailsActivity.java
Java
[]
null
[]
package lv.krokyze.graffiti_programmr; import android.app.Activity; import android.app.FragmentTransaction; import android.os.Bundle; public class GraffitiDetailsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getFragmentManager().beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .replace(R.id.container, new GraffitiDetailsFragment()) .commit(); } }
587
0.706985
0.706985
20
28.35
24.462778
73
false
false
0
0
0
0
0
0
0.4
false
false
13
d49e629212080578798f072fcf9bc2f7b5a4e761
17,033,840,310,555
785e34890f3effd6483e0bded1ab6e77b14186a2
/src/main/java/com/denizenscript/denizencore/scripts/commands/queue/DefineCommand.java
ad806d1f8e05f6811b7fb5b7425f1df54cdc1fba
[ "MIT" ]
permissive
DenizenScript/Denizen-Core
https://github.com/DenizenScript/Denizen-Core
00cda338c92dfda0c152591f209e60534acfc86e
04426a72d622c00ae73518263c20e8d4b3b2b9b3
refs/heads/master
2023-08-09T07:37:41.375000
2023-08-06T01:54:56
2023-08-06T01:54:56
24,804,721
15
46
MIT
false
2023-06-12T16:27:05
2014-10-05T00:03:35
2023-04-24T14:24:02
2023-06-12T16:27:03
4,550
15
28
1
Java
false
false
package com.denizenscript.denizencore.scripts.commands.queue; import com.denizenscript.denizencore.exceptions.InvalidArgumentsException; import com.denizenscript.denizencore.objects.Argument; import com.denizenscript.denizencore.objects.core.QueueTag; import com.denizenscript.denizencore.utilities.CoreUtilities; import com.denizenscript.denizencore.utilities.data.ActionableDataProvider; import com.denizenscript.denizencore.utilities.data.DataAction; import com.denizenscript.denizencore.utilities.data.DataActionHelper; import com.denizenscript.denizencore.utilities.debugging.Debug; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.ObjectTag; import com.denizenscript.denizencore.scripts.ScriptEntry; import com.denizenscript.denizencore.scripts.commands.AbstractCommand; import com.denizenscript.denizencore.scripts.queues.ScriptQueue; public class DefineCommand extends AbstractCommand { public DefineCommand() { setName("define"); setSyntax("define [<id>](:<action>)[:<value>]"); setRequiredArguments(1, 2); isProcedural = true; allowedDynamicPrefixes = true; } // <--[command] // @Name Define // @Syntax define [<id>](:<action>)[:<value>] // @Required 1 // @Maximum 2 // @Short Creates a temporary variable inside a script queue. // @Synonyms Definition // @Group queue // @Guide https://guide.denizenscript.com/guides/basics/definitions.html // // @Description // Definitions are queue-level 'variables' that can be used throughout a script, once defined, by using the <[<id>]> tag. // Definitions are only valid on the current queue and are not transferred to any new queues constructed within the script, // such as by a 'run' command, without explicitly specifying to do so. // // Definitions are lighter and faster than creating a temporary flag. // Definitions are also automatically removed when the queue is completed, so there is no worry for leaving unused data hanging around. // // This command supports data actions, see <@link language data actions>. // // Definitions can be sub-mapped with the '.' character, meaning a def named 'x.y.z' is actually a def 'x' as a MapTag with key 'y' as a MapTag with key 'z' as the final defined value. // In other words, "<[a.b.c]>" is equivalent to "<[a].get[b].get[c]>" // // @Tags // <[<id>]> to get the value assigned to an ID // <QueueTag.definition[<definition>]> // <QueueTag.definitions> // // @Usage // Use to make complex tags look less complex, and scripts more readable. // - narrate "You invoke your power of notice..." // - define range <player.flag[range_level].mul[3]> // - define blocks <player.flag[noticeable_blocks]> // - define count <player.location.find_blocks[<[blocks]>].within[<[range]>].size> // - narrate "<&[base]>[NOTICE] You have noticed <[count].custom_color[emphasis]> blocks in the area that may be of interest." // // @Usage // Use to validate a player input to a command script, and then output the found player's name. // - define target <server.match_player[<context.args.get[1]>]||null> // - if <[target]> == null: // - narrate "<red>Unknown player target." // - stop // - narrate "You targeted <[target].name>!" // // @Usage // Use to keep the value of a tag that you might use many times within a single script. // - define arg1 <context.args.get[1]> // - if <[arg1]> == hello: // - narrate Hello! // - else if <[arg1]> == goodbye: // - narrate Goodbye! // // @Usage // Use to remove a definition. // - define myDef:! // // @Usage // Use to make a MapTag definition and set the value of a key inside. // - define myroot.mykey MyValue // - define myroot.myotherkey MyOtherValue // - narrate "The main value is <[myroot.mykey]>, and the map's available key set is <[myroot].keys>" // // --> public static class DefinitionActionProvider extends ActionableDataProvider { public ScriptQueue queue; @Override public ObjectTag getValueAt(String keyName) { return queue.getDefinitionObject(keyName); } @Override public void setValueAt(String keyName, ObjectTag value) { queue.addDefinition(keyName, value); } } @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : scriptEntry) { if (!scriptEntry.hasObject("definition")) { if (CoreUtilities.contains(arg.getRawValue(), ':')) { DefinitionActionProvider provider = new DefinitionActionProvider(); provider.queue = scriptEntry.getResidingQueue(); scriptEntry.addObject("action", DataActionHelper.parse(provider, arg, scriptEntry.context)); } else { scriptEntry.addObject("definition", new ElementTag(CoreUtilities.toLowerCase(arg.getValue()))); } } else if (!scriptEntry.hasObject("value")) { scriptEntry.addObject("value", arg.hasPrefix() && arg.object instanceof ElementTag ? arg.getRawElement() : arg.object); } else { arg.reportUnhandled(); } } if ((!scriptEntry.hasObject("definition") || !scriptEntry.hasObject("value")) && !scriptEntry.hasObject("action")) { throw new InvalidArgumentsException("Must specify a definition and value!"); } } @Override public void execute(ScriptEntry scriptEntry) { ElementTag definition = scriptEntry.getElement("definition"); ObjectTag value = scriptEntry.getObjectTag("value"); ElementTag remove = scriptEntry.getElement("remove"); DataAction action = (DataAction) scriptEntry.getObject("action"); if (scriptEntry.dbCallShouldDebug()) { Debug.report(scriptEntry, getName(), new QueueTag(scriptEntry.getResidingQueue()), definition, value, action, remove); } if (action != null) { action.execute(scriptEntry.getContext()); return; } scriptEntry.getResidingQueue().addDefinition(definition.asString(), value.duplicate()); } }
UTF-8
Java
6,602
java
DefineCommand.java
Java
[]
null
[]
package com.denizenscript.denizencore.scripts.commands.queue; import com.denizenscript.denizencore.exceptions.InvalidArgumentsException; import com.denizenscript.denizencore.objects.Argument; import com.denizenscript.denizencore.objects.core.QueueTag; import com.denizenscript.denizencore.utilities.CoreUtilities; import com.denizenscript.denizencore.utilities.data.ActionableDataProvider; import com.denizenscript.denizencore.utilities.data.DataAction; import com.denizenscript.denizencore.utilities.data.DataActionHelper; import com.denizenscript.denizencore.utilities.debugging.Debug; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.ObjectTag; import com.denizenscript.denizencore.scripts.ScriptEntry; import com.denizenscript.denizencore.scripts.commands.AbstractCommand; import com.denizenscript.denizencore.scripts.queues.ScriptQueue; public class DefineCommand extends AbstractCommand { public DefineCommand() { setName("define"); setSyntax("define [<id>](:<action>)[:<value>]"); setRequiredArguments(1, 2); isProcedural = true; allowedDynamicPrefixes = true; } // <--[command] // @Name Define // @Syntax define [<id>](:<action>)[:<value>] // @Required 1 // @Maximum 2 // @Short Creates a temporary variable inside a script queue. // @Synonyms Definition // @Group queue // @Guide https://guide.denizenscript.com/guides/basics/definitions.html // // @Description // Definitions are queue-level 'variables' that can be used throughout a script, once defined, by using the <[<id>]> tag. // Definitions are only valid on the current queue and are not transferred to any new queues constructed within the script, // such as by a 'run' command, without explicitly specifying to do so. // // Definitions are lighter and faster than creating a temporary flag. // Definitions are also automatically removed when the queue is completed, so there is no worry for leaving unused data hanging around. // // This command supports data actions, see <@link language data actions>. // // Definitions can be sub-mapped with the '.' character, meaning a def named 'x.y.z' is actually a def 'x' as a MapTag with key 'y' as a MapTag with key 'z' as the final defined value. // In other words, "<[a.b.c]>" is equivalent to "<[a].get[b].get[c]>" // // @Tags // <[<id>]> to get the value assigned to an ID // <QueueTag.definition[<definition>]> // <QueueTag.definitions> // // @Usage // Use to make complex tags look less complex, and scripts more readable. // - narrate "You invoke your power of notice..." // - define range <player.flag[range_level].mul[3]> // - define blocks <player.flag[noticeable_blocks]> // - define count <player.location.find_blocks[<[blocks]>].within[<[range]>].size> // - narrate "<&[base]>[NOTICE] You have noticed <[count].custom_color[emphasis]> blocks in the area that may be of interest." // // @Usage // Use to validate a player input to a command script, and then output the found player's name. // - define target <server.match_player[<context.args.get[1]>]||null> // - if <[target]> == null: // - narrate "<red>Unknown player target." // - stop // - narrate "You targeted <[target].name>!" // // @Usage // Use to keep the value of a tag that you might use many times within a single script. // - define arg1 <context.args.get[1]> // - if <[arg1]> == hello: // - narrate Hello! // - else if <[arg1]> == goodbye: // - narrate Goodbye! // // @Usage // Use to remove a definition. // - define myDef:! // // @Usage // Use to make a MapTag definition and set the value of a key inside. // - define myroot.mykey MyValue // - define myroot.myotherkey MyOtherValue // - narrate "The main value is <[myroot.mykey]>, and the map's available key set is <[myroot].keys>" // // --> public static class DefinitionActionProvider extends ActionableDataProvider { public ScriptQueue queue; @Override public ObjectTag getValueAt(String keyName) { return queue.getDefinitionObject(keyName); } @Override public void setValueAt(String keyName, ObjectTag value) { queue.addDefinition(keyName, value); } } @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : scriptEntry) { if (!scriptEntry.hasObject("definition")) { if (CoreUtilities.contains(arg.getRawValue(), ':')) { DefinitionActionProvider provider = new DefinitionActionProvider(); provider.queue = scriptEntry.getResidingQueue(); scriptEntry.addObject("action", DataActionHelper.parse(provider, arg, scriptEntry.context)); } else { scriptEntry.addObject("definition", new ElementTag(CoreUtilities.toLowerCase(arg.getValue()))); } } else if (!scriptEntry.hasObject("value")) { scriptEntry.addObject("value", arg.hasPrefix() && arg.object instanceof ElementTag ? arg.getRawElement() : arg.object); } else { arg.reportUnhandled(); } } if ((!scriptEntry.hasObject("definition") || !scriptEntry.hasObject("value")) && !scriptEntry.hasObject("action")) { throw new InvalidArgumentsException("Must specify a definition and value!"); } } @Override public void execute(ScriptEntry scriptEntry) { ElementTag definition = scriptEntry.getElement("definition"); ObjectTag value = scriptEntry.getObjectTag("value"); ElementTag remove = scriptEntry.getElement("remove"); DataAction action = (DataAction) scriptEntry.getObject("action"); if (scriptEntry.dbCallShouldDebug()) { Debug.report(scriptEntry, getName(), new QueueTag(scriptEntry.getResidingQueue()), definition, value, action, remove); } if (action != null) { action.execute(scriptEntry.getContext()); return; } scriptEntry.getResidingQueue().addDefinition(definition.asString(), value.duplicate()); } }
6,602
0.640261
0.638746
146
43.219177
36.647804
188
false
false
0
0
0
0
0
0
0.465753
false
false
13
0a42169acf2e69f7d63bdbbf2b6fb64fce88ae9e
17,033,840,306,915
e7b5869d18b55a1e9951a65571934f9c8308ed9e
/src/test/java/testCases/TC_002_Login.java
7a9b25cda8f7680af953a39cc708839494ffd24e
[]
no_license
abhijithmhn64/opencart-1
https://github.com/abhijithmhn64/opencart-1
6f736aa93ba10d893bb3819737bf017e435fed8e
2794dab6e188a770f91092fc9dda19cbbf69a018
refs/heads/master
2023-05-28T12:10:15.843000
2021-06-08T13:39:38
2021-06-08T13:39:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testCases; import org.testng.Assert; import org.testng.annotations.Test; import pageObjects.HomePage; import pageObjects.LoginPage; import testBase.BaseClass; public class TC_002_Login extends BaseClass { @Test(groups= {"sanity","master"}) public void test_login() { logger.info("Started TC_002_Login"); try { driver.get(rb.getString("appURL")); logger.info("HomePage displayed"); HomePage hp=new HomePage(driver); hp.clickMyAccount(); logger.info("MyAccount clicked"); hp.clickLogin(); logger.info("Login link clicked"); LoginPage lp=new LoginPage(driver); lp.setEmail(rb.getString("email")); logger.info("email entered"); lp.setPassword(rb.getString("password")); logger.info("password entered"); lp.clickbtnLogin(); logger.info("login button clicked"); boolean targetPage=lp.isMyAccountPageExist(); if(targetPage) { logger.info("Login successfull"); Assert.assertTrue(true); } else { logger.info("Login failed"); captureScreen(driver,"test_login"); Assert.fail(); } } catch (Exception e) { logger.fatal("Login failed"); Assert.fail(); } logger.info("Finished TC_002_Login"); } }
UTF-8
Java
1,219
java
TC_002_Login.java
Java
[ { "context": "\"email entered\");\n\t\t\tlp.setPassword(rb.getString(\"password\"));\n\t\t\tlogger.info(\"password entered\");\n\t\t\tlp.cli", "end": 723, "score": 0.9839531779289246, "start": 715, "tag": "PASSWORD", "value": "password" } ]
null
[]
package testCases; import org.testng.Assert; import org.testng.annotations.Test; import pageObjects.HomePage; import pageObjects.LoginPage; import testBase.BaseClass; public class TC_002_Login extends BaseClass { @Test(groups= {"sanity","master"}) public void test_login() { logger.info("Started TC_002_Login"); try { driver.get(rb.getString("appURL")); logger.info("HomePage displayed"); HomePage hp=new HomePage(driver); hp.clickMyAccount(); logger.info("MyAccount clicked"); hp.clickLogin(); logger.info("Login link clicked"); LoginPage lp=new LoginPage(driver); lp.setEmail(rb.getString("email")); logger.info("email entered"); lp.setPassword(rb.getString("<PASSWORD>")); logger.info("password entered"); lp.clickbtnLogin(); logger.info("login button clicked"); boolean targetPage=lp.isMyAccountPageExist(); if(targetPage) { logger.info("Login successfull"); Assert.assertTrue(true); } else { logger.info("Login failed"); captureScreen(driver,"test_login"); Assert.fail(); } } catch (Exception e) { logger.fatal("Login failed"); Assert.fail(); } logger.info("Finished TC_002_Login"); } }
1,221
0.673503
0.66612
57
20.385965
15.552689
48
false
false
0
0
0
0
0
0
2.666667
false
false
13
2be92bf6f23efc8a60c0e418c8a25cc98659500b
17,033,840,307,540
5d8f1ce5add5f174bf6937ab380cb8aba0d175c5
/api/src/main/java/wrapper/JsonApiFormatTuple.java
afb587750b4fb607cf3a4103f06f6fac0331516a
[]
no_license
zcharli/distributed-review-sys
https://github.com/zcharli/distributed-review-sys
e0253a14d3622ce6d87623bc6d899eb6177ddf11
dae5f5f3a48a42b4b725828989565669ba73835e
refs/heads/master
2021-01-13T12:46:37.901000
2018-04-18T04:38:55
2018-04-18T04:38:55
72,443,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by cli on 10/21/2016. */ public class JsonApiFormatTuple<SAMPLE, FULL> { private final static Logger LOGGER = LoggerFactory.getLogger(JsonApiFormatTuple.class); public SAMPLE shortRepresentation; public FULL fullRepresentation; public JsonApiFormatTuple(SAMPLE sample, FULL full) { if (sample == null || full == null) { LOGGER.error("Created a JsonApiFormatTuple with a null parameter"); } shortRepresentation = sample; fullRepresentation = full; } public static class JsonApiShortRelationshipRep { public String type; public String id; public JsonApiShortRelationshipRep(String type, String id) { this.type = type; this.id = id; } } }
UTF-8
Java
894
java
JsonApiFormatTuple.java
Java
[ { "context": "ort org.slf4j.LoggerFactory;\r\n\r\n/**\r\n * Created by cli on 10/21/2016.\r\n */\r\npublic class JsonApiFormatTu", "end": 103, "score": 0.9699881672859192, "start": 100, "tag": "USERNAME", "value": "cli" } ]
null
[]
package wrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by cli on 10/21/2016. */ public class JsonApiFormatTuple<SAMPLE, FULL> { private final static Logger LOGGER = LoggerFactory.getLogger(JsonApiFormatTuple.class); public SAMPLE shortRepresentation; public FULL fullRepresentation; public JsonApiFormatTuple(SAMPLE sample, FULL full) { if (sample == null || full == null) { LOGGER.error("Created a JsonApiFormatTuple with a null parameter"); } shortRepresentation = sample; fullRepresentation = full; } public static class JsonApiShortRelationshipRep { public String type; public String id; public JsonApiShortRelationshipRep(String type, String id) { this.type = type; this.id = id; } } }
894
0.634228
0.623043
33
25.09091
24.448292
91
false
false
0
0
0
0
0
0
0.545455
false
false
13
ff3a40bdbe48cb287b410d95ba2e53506abf794a
27,986,006,951,793
11600e3de1633fa6fdb863514144bbbb92af8401
/protocol/command/AnonFactory.java
f4d0752c358b5ef8cca60bd4b55c34bb0c20e312
[]
no_license
qaco/iportbook
https://github.com/qaco/iportbook
a085424b0c5f2049dd35ae9ee5a59b97ef01174e
a816ac365c4cfae0f5c472f9b6e490f36b5812c2
refs/heads/master
2018-02-09T13:48:28.209000
2017-07-10T10:13:33
2017-07-10T10:13:33
96,763,800
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package protocol.command ; import protocol.* ; import exception.* ; import java.util.Arrays ; import java.io.InputStream ; import java.io.IOException ; import main.MainVals ; import protocol.field.FieldVals ; public class AnonFactory { public Anon create(InputStream in) throws UnknownResultException, IOException { BlockingReceiver r = new BlockingReceiver(in) ; r.receive() ; return this.create(r.getData()) ; } private Anon create(byte[] raw_arr) throws UnknownResultException { Receiver r = new Receiver(raw_arr) ; String code = r.extractCode() ; byte[][] params = r.splitInput() ; byte[] mess ; try { switch (code) { case AnonVals.REGISTRATION: mess = r.lastBytes(FieldVals.PASS_SIZE) ; return new Registration(params[1], params[2], mess) ; case AnonVals.CONNECTION : mess = r.lastBytes(FieldVals.PASS_SIZE) ; return new Connection(params[1], mess) ; case AnonVals.PUB: mess = r.nthArgToEnd(3) ; return new Pub(params[1], params[2], mess) ; default : throw new UnknownCommandException("anon", code) ; } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace() ; throw new TooFewArgsException(code, String.valueOf(params.length)) ; } } }
UTF-8
Java
1,547
java
AnonFactory.java
Java
[]
null
[]
package protocol.command ; import protocol.* ; import exception.* ; import java.util.Arrays ; import java.io.InputStream ; import java.io.IOException ; import main.MainVals ; import protocol.field.FieldVals ; public class AnonFactory { public Anon create(InputStream in) throws UnknownResultException, IOException { BlockingReceiver r = new BlockingReceiver(in) ; r.receive() ; return this.create(r.getData()) ; } private Anon create(byte[] raw_arr) throws UnknownResultException { Receiver r = new Receiver(raw_arr) ; String code = r.extractCode() ; byte[][] params = r.splitInput() ; byte[] mess ; try { switch (code) { case AnonVals.REGISTRATION: mess = r.lastBytes(FieldVals.PASS_SIZE) ; return new Registration(params[1], params[2], mess) ; case AnonVals.CONNECTION : mess = r.lastBytes(FieldVals.PASS_SIZE) ; return new Connection(params[1], mess) ; case AnonVals.PUB: mess = r.nthArgToEnd(3) ; return new Pub(params[1], params[2], mess) ; default : throw new UnknownCommandException("anon", code) ; } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace() ; throw new TooFewArgsException(code, String.valueOf(params.length)) ; } } }
1,547
0.556561
0.552683
46
32.608696
21.56535
74
false
false
0
0
0
0
0
0
0.695652
false
false
13
2ca3b7b10294ba7d33d178309c52c37f945554d9
30,116,310,697,372
637c2c60c001ec5bc34dee52c052b9afb18e5728
/src/test/java/com/jimo/algo/week2/SolutionTest.java
eb628bb9d76a922adf6a71014ecd14cac365e0d3
[]
no_license
jimolonely/algorithm
https://github.com/jimolonely/algorithm
e7caf663868ab5bd95172e3b06c35739d98f42b4
6dda324e15390c8c98cebc9b7e245ce19b289001
refs/heads/master
2021-06-30T01:50:08.571000
2019-07-03T01:06:01
2019-07-03T01:06:01
162,934,254
0
0
null
false
2022-12-08T01:14:00
2018-12-24T00:44:28
2022-12-08T01:13:37
2022-12-08T01:13:59
563
0
0
2
Java
false
false
package com.jimo.algo.week2; import org.junit.Test; import static org.junit.Assert.*; public class SolutionTest { @Test public void numsSameConsecDiff() { final Solution s = new Solution(); final int[] a = s.numsSameConsecDiff(1, 0); for (int i : a) { System.out.print(i + " "); } } }
UTF-8
Java
303
java
SolutionTest.java
Java
[]
null
[]
package com.jimo.algo.week2; import org.junit.Test; import static org.junit.Assert.*; public class SolutionTest { @Test public void numsSameConsecDiff() { final Solution s = new Solution(); final int[] a = s.numsSameConsecDiff(1, 0); for (int i : a) { System.out.print(i + " "); } } }
303
0.660066
0.650165
18
15.888889
15.527355
45
false
false
0
0
0
0
0
0
1.166667
false
false
13
b336169d772d42909a71fca2db737f137624d2d3
16,183,436,774,540
84abf44f04e7e19cc07eb4b8c8fe14db1ccb9b22
/trunk/src/main/java/healthmanager/modelo/dao/Detalle_hoja_gastoDao.java
6b2a2f986fb72a14363f4c7c18f816f0e2aa5b0f
[]
no_license
BGCX261/zkmhealthmanager-svn-to-git
https://github.com/BGCX261/zkmhealthmanager-svn-to-git
3183263172355b7ac0884b793c1ca3143a950411
bb626589f101034137a2afa62d8e8bfe32bf7d47
refs/heads/master
2021-01-22T02:57:49.394000
2015-08-25T15:32:48
2015-08-25T15:32:48
42,323,197
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Detalle_hoja_gastoDao.java * * Generado Automaticamente . * Ing. Luis Miguel Hernández Pérez */ package healthmanager.modelo.dao; import java.util.List; import java.util.Map; import healthmanager.modelo.bean.Detalle_hoja_gasto; public interface Detalle_hoja_gastoDao { void crear(Detalle_hoja_gasto detalle_hoja_gasto); int actualizar(Detalle_hoja_gasto detalle_hoja_gasto); Detalle_hoja_gasto consultar(Detalle_hoja_gasto detalle_hoja_gasto); int eliminar(Detalle_hoja_gasto detalle_hoja_gasto); List<Detalle_hoja_gasto> listar(Map<String,Object> parameters); void setLimit(String limit); boolean existe(Map<String,Object> param); }
UTF-8
Java
672
java
Detalle_hoja_gastoDao.java
Java
[ { "context": "Dao.java\n * \n * Generado Automaticamente .\n * Ing. Luis Miguel Hernández Pérez\n */ \n\npackage healthmanager.modelo.dao;\n\nimport j", "end": 102, "score": 0.996483564376831, "start": 75, "tag": "NAME", "value": "Luis Miguel Hernández Pérez" } ]
null
[]
/* * Detalle_hoja_gastoDao.java * * Generado Automaticamente . * Ing. <NAME> */ package healthmanager.modelo.dao; import java.util.List; import java.util.Map; import healthmanager.modelo.bean.Detalle_hoja_gasto; public interface Detalle_hoja_gastoDao { void crear(Detalle_hoja_gasto detalle_hoja_gasto); int actualizar(Detalle_hoja_gasto detalle_hoja_gasto); Detalle_hoja_gasto consultar(Detalle_hoja_gasto detalle_hoja_gasto); int eliminar(Detalle_hoja_gasto detalle_hoja_gasto); List<Detalle_hoja_gasto> listar(Map<String,Object> parameters); void setLimit(String limit); boolean existe(Map<String,Object> param); }
649
0.759701
0.759701
30
21.366667
23.229986
70
false
false
0
0
0
0
0
0
0.666667
false
false
13
4744abf08c4a42d1fa0807804811238958098e04
33,887,291,984,303
4929736556d739df662de3d8c4960ed754741335
/GURPSA/src/characterManager/Character.java
af1d2cb3c12fe463036bfc5f1d01449d67a75549
[]
no_license
spencerbriere/GURPSA
https://github.com/spencerbriere/GURPSA
044715cc4cdf412a747e7615158021170f1db072
e77e0b2cfbc024ac8c9df57fbe2fb5a636cc46e5
refs/heads/master
2021-01-19T14:04:52.196000
2017-09-07T18:08:04
2017-09-07T18:08:04
100,883,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package characterManager; import java.util.Vector; import javax.xml.bind.annotation.*; import dataContainers.CharacterFields.*; import dataContainers.CharacterFields.ReactionModifiers.*; import skillManager.SkillManager; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlSeeAlso({Skill.class, CharactersSkill.class}) public class Character { private String name, player, height, weight, appearance; private int SM, age; private int ST,DX,IQ,HT; private int HP,FP; private int Will,PER; private int TL; private float speed; private int move; //Appearance modifiers, statuses, reputations @XmlElementWrapper(name = "SkillList") @XmlElement(name = "PlayerSkill") private Vector<CharactersSkill> playerSkills; @XmlElementWrapper(name = "AdvantageList") @XmlElement(name = "Advantage") private Vector<CharactersAdvantage> playerAdvantages; @XmlElementWrapper(name = "LanguageList") @XmlElement(name = "Language") private Vector<Language> playerLanguages; @XmlElementWrapper(name = "CultureList") @XmlElement(name = "Culture") private Vector<CulturalFamiliarity> playerCultures; /* @XmlElementWrapper(name = "ReactionModList") @XmlElement(name = "ReactionModifier") private Vector<ReactionModifier> playerReactionMods;*/ @XmlElement(name = "AppearanceModifier") private AppearanceModifier playerAppearance; @XmlElementWrapper(name = "ReputationList") @XmlElement(name = "Reputation") private Vector<ReputationModifier> playerReputations; @XmlElementWrapper(name = "StatusList") @XmlElement(name = "Status") private Vector<StatusModifier> playerStatuses; //This constructor is just for generating an XML file to test. //We'll need much, much more awesome constructors soon. public Character() { // name = "Teresa"; name = ""; // player = "David Clare"; player = ""; // height = "5'8"; height = ""; // weight = "200lbs"; weight = ""; // appearance = "Purple hair??"; appearance = ""; // SM = 0; SM = 0; // age = 24; age = 0; // ST = 15; ST = 10; // DX = 12; DX = 10; // IQ = 8; IQ = 10; // HT = 15; HT = 10; // HP = 18; HP = 10; // FP = 18; FP = 10; // Will = 13; Will = 10; // PER = 6; PER = 10; // TL = 4; setTL(7); // speed = 7.0f; speed = 5.0f; // move = 7; move = 5; // playerSkills = new Vector<CharactersSkill>(); // playerAdvantages = new Vector<CharactersAdvantage>(); // playerAdvantages.add(new Advantage("Very Fit", "15 Points", "Placeholder for Very Fit description.")); // playerAdvantages.add(new Advantage("Ambidexterity", "5 Points", "Placeholder for Ambidexterity description.")); // playerAdvantages.add(new Advantage("Fast Swimmer (+1 basic move)", "5 Points", "Placeholder for increased Move Speed description.")); // playerCultures = new Vector<CulturalFamiliarity>(); // playerCultures.add(new CulturalFamiliarity("Human")); // playerCultures.add(new CulturalFamiliarity("Lynian")); // playerCultures.add(new CulturalFamiliarity("Wyverian")); // playerLanguages = new Vector<Language>(); // playerLanguages.add(new Language("Human",Language.Fluency.NATIVE,Language.Fluency.NATIVE)); // playerAppearance = new AppearanceModifier(0,0); playerReputations = new Vector<ReputationModifier>(); // playerReputations.add(new ReputationModifier("Loc Lac Guild workers", +2, "recognized on a 10- roll.")); // playerReputations.add(new ReputationModifier("Loc Lac Guild workers", -2, "recognized on a 7- roll.")); playerStatuses = new Vector<StatusModifier>(); // playerStatuses.add(new StatusModifier("Hunter",1)); } //A liiiittle slower than it should be. public Vector<CharactersSkill> checkForAppropriateSkills(SkillManager skillManager, String skillName) { Vector<CharactersSkill> possibleSkills = new Vector<CharactersSkill>(); Vector<SkillDefault> defaults = new Vector<SkillDefault>(); defaults = (Vector<SkillDefault>) skillManager.getSkill(skillName).getDefaults(); for(int i = 0 ; i < playerSkills.size() ; i++) { if(playerSkills.get(i).getSkillName().equals(skillName)) possibleSkills.add(playerSkills.get(i)); for(int j = 0 ; j < defaults.size(); j++) { if(playerSkills.get(i).getSkillName().equals(defaults.get(j).getName())) possibleSkills.add(new CharactersSkill(playerSkills.get(i).getSkillName(), playerSkills.get(i).getLevel() - defaults.get(j).getPenalty())); } } for(int i = 0 ; i < defaults.size(); i++) { if(defaults.get(i).getName().equals("DX") || defaults.get(i).getName().equals("IQ") || defaults.get(i).getName().equals("HT") || defaults.get(i).getName().equals("Will") || defaults.get(i).getName().equals("Per")) possibleSkills.add(new CharactersSkill(defaults.get(i).getName(), -1 * defaults.get(i).getPenalty())); } return possibleSkills; } public String getName() { return name; } public String getPlayer() { return player; } public String getHeight() { return height; } public String getWeight() { return weight; } public String getAppearance() { return appearance; } public int getSM() { return SM; } public int getAge() { return age; } public int getST() { return ST; } public int getDX() { return DX; } public int getIQ() { return IQ; } public int getHT() { return HT; } public int getHP() { return HP; } public int getFP() { return FP; } public int getWill() { return Will; } public int getPER() { return PER; } public float getSpeed() { return speed; } public int getMove() { return move; } public Vector<Language> getLanguages() { return playerLanguages; } public Vector<CharactersSkill> getSkills() { return playerSkills; } public Vector<CulturalFamiliarity> getCultures() { return playerCultures; } public AppearanceModifier getAppearanceMod() { return playerAppearance; } public Vector<CharactersAdvantage> getAdvantages() { return playerAdvantages; } public void addSkill(String skillName, int relativeLevel) { this.playerSkills.addElement(new CharactersSkill(skillName, relativeLevel)); } public void setSkills(Vector<CharactersSkill> newSkills) { this.playerSkills = newSkills; } public void addAdvantage(String advantageName) { this.playerAdvantages.addElement(new CharactersAdvantage(advantageName)); } public void setAdvantages(Vector<CharactersAdvantage> newAdvantages) { this.playerAdvantages = newAdvantages; } public void setName(String name) { this.name = name; } public void setPlayer(String player) { this.player = player; } public void setHeight(String height) { this.height = height; } public void setWeight(String weight) { this.weight = weight; } public void setAppearance(String appearance) { this.appearance = appearance; } public void setSM(int SM) { this.SM = SM; } public void setAge(int age) { this.age = age; } public void setST(int ST) { this.ST = ST; } public void setDX(int DX) { this.DX = DX; } public void setIQ(int IQ) { this.IQ = IQ; } public void setHT(int HT) { this.HT = HT; } public void setHP(int HP) { this.HP = HP; } public void setFP(int FP) { this.FP = FP; } public void setWill(int Will) { this.Will = Will; } public void setPER(int PER) { this.PER = PER; } public void setSpeed(float speed) { this.speed = speed; } public void setMove(int move) { this.move = move; } public void addLanguage(String lang, String written, String spoken) { Language.Fluency s = Language.Fluency.NONE; Language.Fluency w = Language.Fluency.NONE; switch(spoken.toUpperCase()) { case "NONE": s = Language.Fluency.NONE; break; case "BROKEN": s = Language.Fluency.BROKEN; break; case "ACCENTED": s = Language.Fluency.ACCENTED; break; case "NATIVE": s = Language.Fluency.NATIVE; break; } switch(written.toUpperCase()) { case "NONE": w = Language.Fluency.NONE; break; case "BROKEN": w = Language.Fluency.BROKEN; break; case "ACCENTED": w = Language.Fluency.ACCENTED; break; case "NATIVE": w = Language.Fluency.NATIVE; break; } playerLanguages.add(new Language(lang, w, s)); } public void addCulture(String culture) { playerCultures.add(new CulturalFamiliarity(culture)); } public void setAppearanceMod(int appropriate, int other) { playerAppearance = new AppearanceModifier(appropriate, other); } //Just to help me test reading the XML file public String toString() { /* String output = "Name: " + name + "\r\n"; output += "Player: " + player + "\r\n"; output += "Height: " + height + "\r\n"; output += "Weight: " + weight + "\r\n"; output += "Appearance: " + appearance + "\r\n"; output += "SM: " + SM + "\r\n"; output += "Age: " + age + "\r\n"; output += "ST: " + ST + "\r\n"; output += "DX: " + DX + "\r\n"; output += "IQ: " + IQ + "\r\n"; output += "HT: " + HT + "\r\n"; output += "Will: " + Will + "\r\n"; output += "PER: " + PER + "\r\n"; output += "Basic Speed: " + speed + "\r\n"; output += "Basic Move: " + move + "\r\n"; for(int i = 0 ; i < playerSkills.size() ; i++) output += playerSkills.get(i).getSkillName() + " at " + playerSkills.get(i).getLevel() + "\r\n"; for(int i = 0 ; i < playerAdvantages.size() ; i++) output += playerAdvantages.get(i).toString() + "\r\n"; for(int i = 0 ; i < playerLanguages.size() ; i++) output += playerLanguages.get(i).toString() + "\r\n"; for(int i = 0 ; i < playerCultures.size() ; i++) output += playerCultures.get(i).toString() + "\r\n"; output += playerAppearance.toString() + "\r\n"; for(int i = 0 ; i < playerReputations.size() ; i++) output += playerReputations.get(i).toString() + "\r\n"; for(int i = 0 ; i < playerStatuses.size() ; i++) output += playerStatuses.get(i).toString() + "\r\n"; return output; */ return name; } public int getTL() { return TL; } public void setTL(int tL) { TL = tL; } public boolean has(String name, int minimum) { for(CharactersAdvantage adv : playerAdvantages) { if(adv.getAdvantageName().equals(name)) { return true; } } for(CharactersSkill skill : playerSkills) { if(skill.getSkillName().equals(name)) { if(skill.getLevel() >= minimum) { return true; } else { return false; } } } return false; } }
UTF-8
Java
10,913
java
Character.java
Java
[ { "context": "ctors soon.\r\n\tpublic Character()\r\n\t{\r\n//\t\tname = \"Teresa\";\r\n\t\tname = \"\";\r\n//\t\tplayer = \"David Clare\";\r\n\t\tp", "end": 1827, "score": 0.9996911883354187, "start": 1821, "tag": "NAME", "value": "Teresa" }, { "context": "//\t\tname = \"Teresa\";\r...
null
[]
package characterManager; import java.util.Vector; import javax.xml.bind.annotation.*; import dataContainers.CharacterFields.*; import dataContainers.CharacterFields.ReactionModifiers.*; import skillManager.SkillManager; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlSeeAlso({Skill.class, CharactersSkill.class}) public class Character { private String name, player, height, weight, appearance; private int SM, age; private int ST,DX,IQ,HT; private int HP,FP; private int Will,PER; private int TL; private float speed; private int move; //Appearance modifiers, statuses, reputations @XmlElementWrapper(name = "SkillList") @XmlElement(name = "PlayerSkill") private Vector<CharactersSkill> playerSkills; @XmlElementWrapper(name = "AdvantageList") @XmlElement(name = "Advantage") private Vector<CharactersAdvantage> playerAdvantages; @XmlElementWrapper(name = "LanguageList") @XmlElement(name = "Language") private Vector<Language> playerLanguages; @XmlElementWrapper(name = "CultureList") @XmlElement(name = "Culture") private Vector<CulturalFamiliarity> playerCultures; /* @XmlElementWrapper(name = "ReactionModList") @XmlElement(name = "ReactionModifier") private Vector<ReactionModifier> playerReactionMods;*/ @XmlElement(name = "AppearanceModifier") private AppearanceModifier playerAppearance; @XmlElementWrapper(name = "ReputationList") @XmlElement(name = "Reputation") private Vector<ReputationModifier> playerReputations; @XmlElementWrapper(name = "StatusList") @XmlElement(name = "Status") private Vector<StatusModifier> playerStatuses; //This constructor is just for generating an XML file to test. //We'll need much, much more awesome constructors soon. public Character() { // name = "Teresa"; name = ""; // player = "<NAME>"; player = ""; // height = "5'8"; height = ""; // weight = "200lbs"; weight = ""; // appearance = "Purple hair??"; appearance = ""; // SM = 0; SM = 0; // age = 24; age = 0; // ST = 15; ST = 10; // DX = 12; DX = 10; // IQ = 8; IQ = 10; // HT = 15; HT = 10; // HP = 18; HP = 10; // FP = 18; FP = 10; // Will = 13; Will = 10; // PER = 6; PER = 10; // TL = 4; setTL(7); // speed = 7.0f; speed = 5.0f; // move = 7; move = 5; // playerSkills = new Vector<CharactersSkill>(); // playerAdvantages = new Vector<CharactersAdvantage>(); // playerAdvantages.add(new Advantage("Very Fit", "15 Points", "Placeholder for Very Fit description.")); // playerAdvantages.add(new Advantage("Ambidexterity", "5 Points", "Placeholder for Ambidexterity description.")); // playerAdvantages.add(new Advantage("Fast Swimmer (+1 basic move)", "5 Points", "Placeholder for increased Move Speed description.")); // playerCultures = new Vector<CulturalFamiliarity>(); // playerCultures.add(new CulturalFamiliarity("Human")); // playerCultures.add(new CulturalFamiliarity("Lynian")); // playerCultures.add(new CulturalFamiliarity("Wyverian")); // playerLanguages = new Vector<Language>(); // playerLanguages.add(new Language("Human",Language.Fluency.NATIVE,Language.Fluency.NATIVE)); // playerAppearance = new AppearanceModifier(0,0); playerReputations = new Vector<ReputationModifier>(); // playerReputations.add(new ReputationModifier("Loc Lac Guild workers", +2, "recognized on a 10- roll.")); // playerReputations.add(new ReputationModifier("Loc Lac Guild workers", -2, "recognized on a 7- roll.")); playerStatuses = new Vector<StatusModifier>(); // playerStatuses.add(new StatusModifier("Hunter",1)); } //A liiiittle slower than it should be. public Vector<CharactersSkill> checkForAppropriateSkills(SkillManager skillManager, String skillName) { Vector<CharactersSkill> possibleSkills = new Vector<CharactersSkill>(); Vector<SkillDefault> defaults = new Vector<SkillDefault>(); defaults = (Vector<SkillDefault>) skillManager.getSkill(skillName).getDefaults(); for(int i = 0 ; i < playerSkills.size() ; i++) { if(playerSkills.get(i).getSkillName().equals(skillName)) possibleSkills.add(playerSkills.get(i)); for(int j = 0 ; j < defaults.size(); j++) { if(playerSkills.get(i).getSkillName().equals(defaults.get(j).getName())) possibleSkills.add(new CharactersSkill(playerSkills.get(i).getSkillName(), playerSkills.get(i).getLevel() - defaults.get(j).getPenalty())); } } for(int i = 0 ; i < defaults.size(); i++) { if(defaults.get(i).getName().equals("DX") || defaults.get(i).getName().equals("IQ") || defaults.get(i).getName().equals("HT") || defaults.get(i).getName().equals("Will") || defaults.get(i).getName().equals("Per")) possibleSkills.add(new CharactersSkill(defaults.get(i).getName(), -1 * defaults.get(i).getPenalty())); } return possibleSkills; } public String getName() { return name; } public String getPlayer() { return player; } public String getHeight() { return height; } public String getWeight() { return weight; } public String getAppearance() { return appearance; } public int getSM() { return SM; } public int getAge() { return age; } public int getST() { return ST; } public int getDX() { return DX; } public int getIQ() { return IQ; } public int getHT() { return HT; } public int getHP() { return HP; } public int getFP() { return FP; } public int getWill() { return Will; } public int getPER() { return PER; } public float getSpeed() { return speed; } public int getMove() { return move; } public Vector<Language> getLanguages() { return playerLanguages; } public Vector<CharactersSkill> getSkills() { return playerSkills; } public Vector<CulturalFamiliarity> getCultures() { return playerCultures; } public AppearanceModifier getAppearanceMod() { return playerAppearance; } public Vector<CharactersAdvantage> getAdvantages() { return playerAdvantages; } public void addSkill(String skillName, int relativeLevel) { this.playerSkills.addElement(new CharactersSkill(skillName, relativeLevel)); } public void setSkills(Vector<CharactersSkill> newSkills) { this.playerSkills = newSkills; } public void addAdvantage(String advantageName) { this.playerAdvantages.addElement(new CharactersAdvantage(advantageName)); } public void setAdvantages(Vector<CharactersAdvantage> newAdvantages) { this.playerAdvantages = newAdvantages; } public void setName(String name) { this.name = name; } public void setPlayer(String player) { this.player = player; } public void setHeight(String height) { this.height = height; } public void setWeight(String weight) { this.weight = weight; } public void setAppearance(String appearance) { this.appearance = appearance; } public void setSM(int SM) { this.SM = SM; } public void setAge(int age) { this.age = age; } public void setST(int ST) { this.ST = ST; } public void setDX(int DX) { this.DX = DX; } public void setIQ(int IQ) { this.IQ = IQ; } public void setHT(int HT) { this.HT = HT; } public void setHP(int HP) { this.HP = HP; } public void setFP(int FP) { this.FP = FP; } public void setWill(int Will) { this.Will = Will; } public void setPER(int PER) { this.PER = PER; } public void setSpeed(float speed) { this.speed = speed; } public void setMove(int move) { this.move = move; } public void addLanguage(String lang, String written, String spoken) { Language.Fluency s = Language.Fluency.NONE; Language.Fluency w = Language.Fluency.NONE; switch(spoken.toUpperCase()) { case "NONE": s = Language.Fluency.NONE; break; case "BROKEN": s = Language.Fluency.BROKEN; break; case "ACCENTED": s = Language.Fluency.ACCENTED; break; case "NATIVE": s = Language.Fluency.NATIVE; break; } switch(written.toUpperCase()) { case "NONE": w = Language.Fluency.NONE; break; case "BROKEN": w = Language.Fluency.BROKEN; break; case "ACCENTED": w = Language.Fluency.ACCENTED; break; case "NATIVE": w = Language.Fluency.NATIVE; break; } playerLanguages.add(new Language(lang, w, s)); } public void addCulture(String culture) { playerCultures.add(new CulturalFamiliarity(culture)); } public void setAppearanceMod(int appropriate, int other) { playerAppearance = new AppearanceModifier(appropriate, other); } //Just to help me test reading the XML file public String toString() { /* String output = "Name: " + name + "\r\n"; output += "Player: " + player + "\r\n"; output += "Height: " + height + "\r\n"; output += "Weight: " + weight + "\r\n"; output += "Appearance: " + appearance + "\r\n"; output += "SM: " + SM + "\r\n"; output += "Age: " + age + "\r\n"; output += "ST: " + ST + "\r\n"; output += "DX: " + DX + "\r\n"; output += "IQ: " + IQ + "\r\n"; output += "HT: " + HT + "\r\n"; output += "Will: " + Will + "\r\n"; output += "PER: " + PER + "\r\n"; output += "Basic Speed: " + speed + "\r\n"; output += "Basic Move: " + move + "\r\n"; for(int i = 0 ; i < playerSkills.size() ; i++) output += playerSkills.get(i).getSkillName() + " at " + playerSkills.get(i).getLevel() + "\r\n"; for(int i = 0 ; i < playerAdvantages.size() ; i++) output += playerAdvantages.get(i).toString() + "\r\n"; for(int i = 0 ; i < playerLanguages.size() ; i++) output += playerLanguages.get(i).toString() + "\r\n"; for(int i = 0 ; i < playerCultures.size() ; i++) output += playerCultures.get(i).toString() + "\r\n"; output += playerAppearance.toString() + "\r\n"; for(int i = 0 ; i < playerReputations.size() ; i++) output += playerReputations.get(i).toString() + "\r\n"; for(int i = 0 ; i < playerStatuses.size() ; i++) output += playerStatuses.get(i).toString() + "\r\n"; return output; */ return name; } public int getTL() { return TL; } public void setTL(int tL) { TL = tL; } public boolean has(String name, int minimum) { for(CharactersAdvantage adv : playerAdvantages) { if(adv.getAdvantageName().equals(name)) { return true; } } for(CharactersSkill skill : playerSkills) { if(skill.getSkillName().equals(name)) { if(skill.getLevel() >= minimum) { return true; } else { return false; } } } return false; } }
10,908
0.630349
0.623843
489
20.316973
23.362524
144
false
false
0
0
0
0
0
0
1.944785
false
false
13
c4100f105462ec7d73b98118c11b39d7b01d9278
29,626,684,449,232
e8ed3c743980a74946a9b35ba3efa3f37b2d0d53
/Live/src/main/java/com/frank/live/stream/VideoStream.java
3a67fc8ba52f78747ec4fcba05694b22eb0bb65b
[]
no_license
pj567/FFmpegAndroid
https://github.com/pj567/FFmpegAndroid
df37b644ea576c1a22958067f5d03cc7ad1256c9
1a9f81ec2fef9d34f3b99424b969dcd4afe198c5
refs/heads/master
2023-03-15T14:52:15.616000
2022-10-25T09:59:18
2022-10-25T09:59:18
557,616,877
1
0
null
true
2022-10-26T01:49:11
2022-10-26T01:49:10
2022-10-26T01:17:01
2022-10-25T09:59:29
151,472
0
0
0
null
false
false
package com.frank.live.stream; import android.app.Activity; import android.content.Context; import android.hardware.Camera; import android.view.SurfaceHolder; import android.view.View; import com.frank.live.camera.CameraHelper; import com.frank.live.listener.OnFrameDataCallback; import com.frank.live.param.VideoParam; public class VideoStream extends VideoStreamBase implements Camera.PreviewCallback, CameraHelper.OnChangedSizeListener { private final OnFrameDataCallback mCallback; private final CameraHelper cameraHelper; private final int mBitrate; private final int mFrameRate; private boolean isLiving; private int previewWidth; private int previewHeight; private int rotateDegree = 90; public VideoStream(OnFrameDataCallback callback, View view, VideoParam videoParam, Context context) { mCallback = callback; mBitrate = videoParam.getBitRate(); mFrameRate = videoParam.getFrameRate(); cameraHelper = new CameraHelper((Activity) context, videoParam.getCameraId(), videoParam.getWidth(), videoParam.getHeight()); cameraHelper.setPreviewCallback(this); cameraHelper.setOnChangedSizeListener(this); } @Override public void setPreviewDisplay(SurfaceHolder surfaceHolder) { cameraHelper.setPreviewDisplay(surfaceHolder); } @Override public void switchCamera() { cameraHelper.switchCamera(); } @Override public void startLive() { isLiving = true; } @Override public void stopLive() { isLiving = false; } @Override public void release() { cameraHelper.release(); } @Override public void onPreviewFrame(byte[] data, Camera camera) { if (isLiving && mCallback != null) { mCallback.onVideoFrame(data, 1); } } @Override public void onChanged(int w, int h) { previewWidth = w; previewHeight = h; updateVideoCodecInfo(w, h, rotateDegree); } @Override public void onPreviewDegreeChanged(int degree) { updateVideoCodecInfo(previewWidth, previewHeight, degree); } private void updateVideoCodecInfo(int width, int height, int degree) { if (degree == 90 || degree == 270) { int temp = width; width = height; height = temp; } if (mCallback != null) { mCallback.onVideoCodecInfo(width, height, mFrameRate, mBitrate); } } }
UTF-8
Java
2,705
java
VideoStream.java
Java
[]
null
[]
package com.frank.live.stream; import android.app.Activity; import android.content.Context; import android.hardware.Camera; import android.view.SurfaceHolder; import android.view.View; import com.frank.live.camera.CameraHelper; import com.frank.live.listener.OnFrameDataCallback; import com.frank.live.param.VideoParam; public class VideoStream extends VideoStreamBase implements Camera.PreviewCallback, CameraHelper.OnChangedSizeListener { private final OnFrameDataCallback mCallback; private final CameraHelper cameraHelper; private final int mBitrate; private final int mFrameRate; private boolean isLiving; private int previewWidth; private int previewHeight; private int rotateDegree = 90; public VideoStream(OnFrameDataCallback callback, View view, VideoParam videoParam, Context context) { mCallback = callback; mBitrate = videoParam.getBitRate(); mFrameRate = videoParam.getFrameRate(); cameraHelper = new CameraHelper((Activity) context, videoParam.getCameraId(), videoParam.getWidth(), videoParam.getHeight()); cameraHelper.setPreviewCallback(this); cameraHelper.setOnChangedSizeListener(this); } @Override public void setPreviewDisplay(SurfaceHolder surfaceHolder) { cameraHelper.setPreviewDisplay(surfaceHolder); } @Override public void switchCamera() { cameraHelper.switchCamera(); } @Override public void startLive() { isLiving = true; } @Override public void stopLive() { isLiving = false; } @Override public void release() { cameraHelper.release(); } @Override public void onPreviewFrame(byte[] data, Camera camera) { if (isLiving && mCallback != null) { mCallback.onVideoFrame(data, 1); } } @Override public void onChanged(int w, int h) { previewWidth = w; previewHeight = h; updateVideoCodecInfo(w, h, rotateDegree); } @Override public void onPreviewDegreeChanged(int degree) { updateVideoCodecInfo(previewWidth, previewHeight, degree); } private void updateVideoCodecInfo(int width, int height, int degree) { if (degree == 90 || degree == 270) { int temp = width; width = height; height = temp; } if (mCallback != null) { mCallback.onVideoCodecInfo(width, height, mFrameRate, mBitrate); } } }
2,705
0.621811
0.618854
95
27.473684
21.542048
83
false
false
0
0
0
0
0
0
0.610526
false
false
13
54366797a26192786e31de1767c62a66fbebbe2f
32,495,722,624,624
7eb360dc1067ee4d7b646d5598bb53a1d2baec6c
/src/main/java/de/doridian/yiffbukkit/warp/commands/WarpCommand.java
2aebb0cdcbf96594ecc79e027e0ea646c3d5e91e
[]
no_license
KingBowser/YiffBukkit
https://github.com/KingBowser/YiffBukkit
466c9d0593eddbb4692a8aa119dd3934477189b7
4d4f1ac920a16258d6d2bd9d5da3368c2a3c7dc3
refs/heads/master
2021-01-18T11:28:44.540000
2014-05-09T23:32:56
2014-05-09T23:32:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.doridian.yiffbukkit.warp.commands; import de.doridian.yiffbukkit.core.util.PlayerHelper; import de.doridian.yiffbukkit.main.YiffBukkitCommandException; import de.doridian.yiffbukkit.main.commands.system.ICommand; import de.doridian.yiffbukkit.main.commands.system.ICommand.Help; import de.doridian.yiffbukkit.main.commands.system.ICommand.Names; import de.doridian.yiffbukkit.main.commands.system.ICommand.Permission; import de.doridian.yiffbukkit.main.commands.system.ICommand.Usage; import de.doridian.yiffbukkit.warp.WarpDescriptor; import de.doridian.yiffbukkit.warp.WarpException; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry; import java.util.UUID; @Names("warp") @Help("Teleports you to the specified warp point.") @Usage("<warp point name>|+ <command>[ <args>] - see /setwarp") @Permission("yiffbukkit.warp.warp") public class WarpCommand extends ICommand { @Override public void run(CommandSender commandSender, String[] args, String argStr) throws YiffBukkitCommandException { if (args.length == 0) { //warp final StringBuilder sb = new StringBuilder("Available warps: "); boolean first = true; final Collection<WarpDescriptor> values = plugin.warpEngine.getWarps().values(); final WarpDescriptor[] valueArray = values.toArray(new WarpDescriptor[values.size()]); final Location location = getCommandSenderLocation(commandSender, false, null); if (location != null) { final Vector playerPos = location.toVector(); Arrays.sort(valueArray, 0, valueArray.length, new Comparator<WarpDescriptor>() { public int compare(WarpDescriptor lhs, WarpDescriptor rhs) { return -Double.compare(lhs.location.toVector().distanceSquared(playerPos), rhs.location.toVector().distanceSquared(playerPos)); } }); } for (WarpDescriptor warp : valueArray) { if (warp.isHidden) continue; final int rank = warp.checkAccess(commandSender); if (rank < 1) continue; if (!first) sb.append(", "); if (rank == 2) { // TODO: use actual rank, not checkAccess sb.append("\u00a77@\u00a7f"); } else if (rank >= 2) { sb.append("\u00a77#\u00a7f"); } sb.append(warp.name); first = false; } PlayerHelper.sendDirectedMessage(commandSender, sb.toString()); return; } if (args[0].equals("help")) { //warp help PlayerHelper.sendDirectedMessage(commandSender, "/warp <warp point name> [<command>[ <args>]]"); PlayerHelper.sendDirectedMessage(commandSender, "commands:"); PlayerHelper.sendDirectedMessage(commandSender, "without arguments - teleport to warp"); PlayerHelper.sendDirectedMessage(commandSender, "info - Shows information"); PlayerHelper.sendDirectedMessage(commandSender, "changeowner <new owner> - Transfers ownership"); PlayerHelper.sendDirectedMessage(commandSender, "public|private - Change public access"); PlayerHelper.sendDirectedMessage(commandSender, "hide|show - Change warp visibility in warp list"); PlayerHelper.sendDirectedMessage(commandSender, "addguest <name> - Grant guest access (can teleport)"); PlayerHelper.sendDirectedMessage(commandSender, "addop <name> - Grant op access (can add guests)"); PlayerHelper.sendDirectedMessage(commandSender, "deny <name> - Deny access"); PlayerHelper.sendDirectedMessage(commandSender, "move - Move the warp to your current position"); PlayerHelper.sendDirectedMessage(commandSender, "remove - Deletes the warp. This cannot be undone!"); return; } try { final WarpDescriptor warp = plugin.warpEngine.getWarp(commandSender, args[0]); if (args.length == 1) { //warp <warp point name> if (playerHelper.isPlayerJailed(asPlayer(commandSender))) throw new YiffBukkitCommandException("You are jailed!"); plugin.playerHelper.teleportWithHistory(asPlayer(commandSender), warp.location); return; } final String command = args[1].toLowerCase(); final int rank = warp.checkAccess(commandSender); switch (command) { case "chown": case "changeowner": //warp <warp point name> changeowner <new owner> final UUID newOwnerName = playerHelper.matchPlayerSingle(args[2]).getUniqueId(); if (newOwnerName == null) throw new WarpException("No unique player found for '" + args[2] + "'"); warp.setOwner(commandSender, newOwnerName); PlayerHelper.sendDirectedMessage(commandSender, "Transferred ownership of warp \u00a79" + warp.name + "\u00a7f to " + newOwnerName + "."); break; case "hide": //warp <warp point name> public if (rank < 3) throw new WarpException("Permission denied"); warp.isHidden = true; PlayerHelper.sendDirectedMessage(commandSender, "Hiding warp \u00a79" + warp.name + "\u00a7f in warp list."); break; case "show": case "unhide": //warp <warp point name> public if (rank < 3) throw new WarpException("Permission denied"); warp.isHidden = true; PlayerHelper.sendDirectedMessage(commandSender, "Showing warp \u00a79" + warp.name + "\u00a7f in warp list."); break; case "public": case "unlock": //warp <warp point name> public if (rank < 2) throw new WarpException("Permission denied"); warp.isPublic = true; PlayerHelper.sendDirectedMessage(commandSender, "Set warp \u00a79" + warp.name + "\u00a7f to public."); break; case "private": case "lock": //warp <warp point name> private warp.isPublic = false; PlayerHelper.sendDirectedMessage(commandSender, "Set warp \u00a79" + warp.name + "\u00a7f to private."); break; case "deny": { //warp <warp point name> deny <name> final Player target = playerHelper.matchPlayerSingle(args[2], false); warp.setAccess(commandSender, target, 0); PlayerHelper.sendDirectedMessage(commandSender, "Revoked " + target.getName() + "'s access to warp \u00a79" + warp.name + "\u00a7f."); break; } case "addguest": { //warp <warp point name> addguest <name> final Player target = playerHelper.matchPlayerSingle(args[2], false); warp.setAccess(commandSender, target, 1); PlayerHelper.sendDirectedMessage(commandSender, "Granted " + target.getName() + " guest access to warp \u00a79" + warp.name + "\u00a7f."); break; } case "addop": { //warp <warp point name> addop <name> final Player target = playerHelper.matchPlayerSingle(args[2], false); warp.setAccess(commandSender, target, 2); PlayerHelper.sendDirectedMessage(commandSender, "Granted " + target.getName() + " op access to warp \u00a79" + warp.name + "\u00a7f."); break; } case "move": //warp <warp point name> move if (rank < 3) throw new WarpException("You need to be the warp's owner to do this."); warp.location = getCommandSenderLocation(commandSender, false).clone(); PlayerHelper.sendDirectedMessage(commandSender, "Moved warp \u00a79" + warp.name + "\u00a7f to your current location."); break; case "info": //warp <warp point name> info final Vector warpPosition = warp.location.toVector(); PlayerHelper.sendDirectedMessage(commandSender, "Warp \u00a79" + warp.name + "\u00a7f is owned by " + warp.getOwner()); if (warp.isPublic) PlayerHelper.sendDirectedMessage(commandSender, "Warp is public"); else PlayerHelper.sendDirectedMessage(commandSender, "Warp is private"); final StringBuilder sb = new StringBuilder("Access list: "); boolean first = true; for (Entry<UUID, Integer> entry : warp.getRanks().entrySet()) { if (!first) sb.append(", "); if (entry.getValue() >= 2) sb.append('@'); sb.append(playerHelper.getPlayerByUUID(entry.getKey()).getName()); first = false; } PlayerHelper.sendDirectedMessage(commandSender, sb.toString()); String msg = "This warp is "; final Location location = getCommandSenderLocation(commandSender, false, null); if (location != null) { final long unitsFromYou = Math.round(warpPosition.distance(location.toVector())); msg += unitsFromYou + "m from you and "; } final long unitsFromSpawn = Math.round(warpPosition.distance(warp.location.getWorld().getSpawnLocation().toVector())); msg += unitsFromSpawn + "m from the spawn."; PlayerHelper.sendDirectedMessage(commandSender, msg); break; case "remove": plugin.warpEngine.removeWarp(commandSender, warp.name); PlayerHelper.sendDirectedMessage(commandSender, "Removed warp \u00a79" + warp.name + "\u00a7f."); break; default: throw new WarpException("Unknown /warp command."); } plugin.warpEngine.SaveWarps(); } catch (ArrayIndexOutOfBoundsException e) { PlayerHelper.sendDirectedMessage(commandSender, "Not enough arguments."); } } }
UTF-8
Java
8,934
java
WarpCommand.java
Java
[]
null
[]
package de.doridian.yiffbukkit.warp.commands; import de.doridian.yiffbukkit.core.util.PlayerHelper; import de.doridian.yiffbukkit.main.YiffBukkitCommandException; import de.doridian.yiffbukkit.main.commands.system.ICommand; import de.doridian.yiffbukkit.main.commands.system.ICommand.Help; import de.doridian.yiffbukkit.main.commands.system.ICommand.Names; import de.doridian.yiffbukkit.main.commands.system.ICommand.Permission; import de.doridian.yiffbukkit.main.commands.system.ICommand.Usage; import de.doridian.yiffbukkit.warp.WarpDescriptor; import de.doridian.yiffbukkit.warp.WarpException; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry; import java.util.UUID; @Names("warp") @Help("Teleports you to the specified warp point.") @Usage("<warp point name>|+ <command>[ <args>] - see /setwarp") @Permission("yiffbukkit.warp.warp") public class WarpCommand extends ICommand { @Override public void run(CommandSender commandSender, String[] args, String argStr) throws YiffBukkitCommandException { if (args.length == 0) { //warp final StringBuilder sb = new StringBuilder("Available warps: "); boolean first = true; final Collection<WarpDescriptor> values = plugin.warpEngine.getWarps().values(); final WarpDescriptor[] valueArray = values.toArray(new WarpDescriptor[values.size()]); final Location location = getCommandSenderLocation(commandSender, false, null); if (location != null) { final Vector playerPos = location.toVector(); Arrays.sort(valueArray, 0, valueArray.length, new Comparator<WarpDescriptor>() { public int compare(WarpDescriptor lhs, WarpDescriptor rhs) { return -Double.compare(lhs.location.toVector().distanceSquared(playerPos), rhs.location.toVector().distanceSquared(playerPos)); } }); } for (WarpDescriptor warp : valueArray) { if (warp.isHidden) continue; final int rank = warp.checkAccess(commandSender); if (rank < 1) continue; if (!first) sb.append(", "); if (rank == 2) { // TODO: use actual rank, not checkAccess sb.append("\u00a77@\u00a7f"); } else if (rank >= 2) { sb.append("\u00a77#\u00a7f"); } sb.append(warp.name); first = false; } PlayerHelper.sendDirectedMessage(commandSender, sb.toString()); return; } if (args[0].equals("help")) { //warp help PlayerHelper.sendDirectedMessage(commandSender, "/warp <warp point name> [<command>[ <args>]]"); PlayerHelper.sendDirectedMessage(commandSender, "commands:"); PlayerHelper.sendDirectedMessage(commandSender, "without arguments - teleport to warp"); PlayerHelper.sendDirectedMessage(commandSender, "info - Shows information"); PlayerHelper.sendDirectedMessage(commandSender, "changeowner <new owner> - Transfers ownership"); PlayerHelper.sendDirectedMessage(commandSender, "public|private - Change public access"); PlayerHelper.sendDirectedMessage(commandSender, "hide|show - Change warp visibility in warp list"); PlayerHelper.sendDirectedMessage(commandSender, "addguest <name> - Grant guest access (can teleport)"); PlayerHelper.sendDirectedMessage(commandSender, "addop <name> - Grant op access (can add guests)"); PlayerHelper.sendDirectedMessage(commandSender, "deny <name> - Deny access"); PlayerHelper.sendDirectedMessage(commandSender, "move - Move the warp to your current position"); PlayerHelper.sendDirectedMessage(commandSender, "remove - Deletes the warp. This cannot be undone!"); return; } try { final WarpDescriptor warp = plugin.warpEngine.getWarp(commandSender, args[0]); if (args.length == 1) { //warp <warp point name> if (playerHelper.isPlayerJailed(asPlayer(commandSender))) throw new YiffBukkitCommandException("You are jailed!"); plugin.playerHelper.teleportWithHistory(asPlayer(commandSender), warp.location); return; } final String command = args[1].toLowerCase(); final int rank = warp.checkAccess(commandSender); switch (command) { case "chown": case "changeowner": //warp <warp point name> changeowner <new owner> final UUID newOwnerName = playerHelper.matchPlayerSingle(args[2]).getUniqueId(); if (newOwnerName == null) throw new WarpException("No unique player found for '" + args[2] + "'"); warp.setOwner(commandSender, newOwnerName); PlayerHelper.sendDirectedMessage(commandSender, "Transferred ownership of warp \u00a79" + warp.name + "\u00a7f to " + newOwnerName + "."); break; case "hide": //warp <warp point name> public if (rank < 3) throw new WarpException("Permission denied"); warp.isHidden = true; PlayerHelper.sendDirectedMessage(commandSender, "Hiding warp \u00a79" + warp.name + "\u00a7f in warp list."); break; case "show": case "unhide": //warp <warp point name> public if (rank < 3) throw new WarpException("Permission denied"); warp.isHidden = true; PlayerHelper.sendDirectedMessage(commandSender, "Showing warp \u00a79" + warp.name + "\u00a7f in warp list."); break; case "public": case "unlock": //warp <warp point name> public if (rank < 2) throw new WarpException("Permission denied"); warp.isPublic = true; PlayerHelper.sendDirectedMessage(commandSender, "Set warp \u00a79" + warp.name + "\u00a7f to public."); break; case "private": case "lock": //warp <warp point name> private warp.isPublic = false; PlayerHelper.sendDirectedMessage(commandSender, "Set warp \u00a79" + warp.name + "\u00a7f to private."); break; case "deny": { //warp <warp point name> deny <name> final Player target = playerHelper.matchPlayerSingle(args[2], false); warp.setAccess(commandSender, target, 0); PlayerHelper.sendDirectedMessage(commandSender, "Revoked " + target.getName() + "'s access to warp \u00a79" + warp.name + "\u00a7f."); break; } case "addguest": { //warp <warp point name> addguest <name> final Player target = playerHelper.matchPlayerSingle(args[2], false); warp.setAccess(commandSender, target, 1); PlayerHelper.sendDirectedMessage(commandSender, "Granted " + target.getName() + " guest access to warp \u00a79" + warp.name + "\u00a7f."); break; } case "addop": { //warp <warp point name> addop <name> final Player target = playerHelper.matchPlayerSingle(args[2], false); warp.setAccess(commandSender, target, 2); PlayerHelper.sendDirectedMessage(commandSender, "Granted " + target.getName() + " op access to warp \u00a79" + warp.name + "\u00a7f."); break; } case "move": //warp <warp point name> move if (rank < 3) throw new WarpException("You need to be the warp's owner to do this."); warp.location = getCommandSenderLocation(commandSender, false).clone(); PlayerHelper.sendDirectedMessage(commandSender, "Moved warp \u00a79" + warp.name + "\u00a7f to your current location."); break; case "info": //warp <warp point name> info final Vector warpPosition = warp.location.toVector(); PlayerHelper.sendDirectedMessage(commandSender, "Warp \u00a79" + warp.name + "\u00a7f is owned by " + warp.getOwner()); if (warp.isPublic) PlayerHelper.sendDirectedMessage(commandSender, "Warp is public"); else PlayerHelper.sendDirectedMessage(commandSender, "Warp is private"); final StringBuilder sb = new StringBuilder("Access list: "); boolean first = true; for (Entry<UUID, Integer> entry : warp.getRanks().entrySet()) { if (!first) sb.append(", "); if (entry.getValue() >= 2) sb.append('@'); sb.append(playerHelper.getPlayerByUUID(entry.getKey()).getName()); first = false; } PlayerHelper.sendDirectedMessage(commandSender, sb.toString()); String msg = "This warp is "; final Location location = getCommandSenderLocation(commandSender, false, null); if (location != null) { final long unitsFromYou = Math.round(warpPosition.distance(location.toVector())); msg += unitsFromYou + "m from you and "; } final long unitsFromSpawn = Math.round(warpPosition.distance(warp.location.getWorld().getSpawnLocation().toVector())); msg += unitsFromSpawn + "m from the spawn."; PlayerHelper.sendDirectedMessage(commandSender, msg); break; case "remove": plugin.warpEngine.removeWarp(commandSender, warp.name); PlayerHelper.sendDirectedMessage(commandSender, "Removed warp \u00a79" + warp.name + "\u00a7f."); break; default: throw new WarpException("Unknown /warp command."); } plugin.warpEngine.SaveWarps(); } catch (ArrayIndexOutOfBoundsException e) { PlayerHelper.sendDirectedMessage(commandSender, "Not enough arguments."); } } }
8,934
0.706291
0.693642
251
34.593624
35.55225
142
false
false
0
0
0
0
0
0
3.258964
false
false
13
4392bbc57a0de0464f294f4677c064f85ce1beb8
22,256,520,593,511
e7093a987492b23298c927399724e218dd103bc0
/src/test/java/com/rex/practice/dao/mapper/AccountMapperTest.java
07d1d4ad1e734a92b08f912b1709f10d9eb6f488
[]
no_license
CH0817/my-practices
https://github.com/CH0817/my-practices
5d30b2a646df32f3815ca2e7a82b1ba08dfdcc40
9da2e1a8e458a8d086640a0155a63e8632574188
refs/heads/master
2023-07-26T11:55:01.769000
2022-04-29T05:26:25
2022-04-29T05:26:25
223,359,894
0
0
null
false
2023-07-07T21:55:54
2019-11-22T08:38:28
2022-04-29T05:26:30
2023-07-07T21:55:54
13,843
0
0
2
CSS
false
false
package com.rex.practice.dao.mapper; import com.rex.practice.dao.mapper.base.BaseMapperTest; import com.rex.practice.dao.model.Account; import com.rex.practice.model.easyui.grid.AccountGridVo; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @Sql({"/db/data/data-dev-user.sql", "/db/data/data-dev-account_type.sql", "/db/data/data-dev-account.sql"}) public class AccountMapperTest extends BaseMapperTest { @Autowired private AccountMapper mapper; @Test public void insertSelective() { Date today = new Date(); Account entity = new Account(); entity.setName("測試帳號"); entity.setUserId("a"); entity.setAccountTypeId("a"); entity.setMoney(new BigDecimal(100000)); entity.setRemoved(Boolean.TRUE); entity.setCreateDate(today); entity.setUpdateDate(today); int executeCount = mapper.insertSelective(entity); logger.info("id: {}", entity.getId()); assertFalse(StringUtils.isEmpty(entity.getId())); assertEquals(32, entity.getId().length()); assertEquals(1, executeCount); } @Test public void selectAll() { assertEquals(5, mapper.selectAll("a").size()); } @Test public void selectByPrimaryKey() { assertEquals("a", mapper.selectByPrimaryKey("a").getId()); } @Test public void updateByPrimaryKey() { Account entity = mapper.selectByPrimaryKey("a"); entity.setUpdateDate(new Date()); int executeCount = mapper.updateSelectiveByPrimaryKey(entity); assertEquals(1, executeCount); } @Test public void selectForGrid() { List<AccountGridVo> entities = mapper.selectForGrid("a"); assertEquals(5, entities.size()); assertEquals("玉山", entities.get(0).getName()); assertEquals(0, new BigDecimal(1000).compareTo(entities.get(0).getMoney())); assertEquals("b", entities.get(0).getAccount_type_id()); } @Test public void updateToDeleteByIds() { assertEquals(2, mapper.updateToDeleteByIds(new String[]{"a", "b"}, "a")); } }
UTF-8
Java
2,409
java
AccountMapperTest.java
Java
[ { "context": "t entity = new Account();\n entity.setName(\"測試帳號\");\n entity.setUserId(\"a\");\n entity.", "end": 904, "score": 0.999140739440918, "start": 900, "tag": "NAME", "value": "測試帳號" } ]
null
[]
package com.rex.practice.dao.mapper; import com.rex.practice.dao.mapper.base.BaseMapperTest; import com.rex.practice.dao.model.Account; import com.rex.practice.model.easyui.grid.AccountGridVo; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @Sql({"/db/data/data-dev-user.sql", "/db/data/data-dev-account_type.sql", "/db/data/data-dev-account.sql"}) public class AccountMapperTest extends BaseMapperTest { @Autowired private AccountMapper mapper; @Test public void insertSelective() { Date today = new Date(); Account entity = new Account(); entity.setName("測試帳號"); entity.setUserId("a"); entity.setAccountTypeId("a"); entity.setMoney(new BigDecimal(100000)); entity.setRemoved(Boolean.TRUE); entity.setCreateDate(today); entity.setUpdateDate(today); int executeCount = mapper.insertSelective(entity); logger.info("id: {}", entity.getId()); assertFalse(StringUtils.isEmpty(entity.getId())); assertEquals(32, entity.getId().length()); assertEquals(1, executeCount); } @Test public void selectAll() { assertEquals(5, mapper.selectAll("a").size()); } @Test public void selectByPrimaryKey() { assertEquals("a", mapper.selectByPrimaryKey("a").getId()); } @Test public void updateByPrimaryKey() { Account entity = mapper.selectByPrimaryKey("a"); entity.setUpdateDate(new Date()); int executeCount = mapper.updateSelectiveByPrimaryKey(entity); assertEquals(1, executeCount); } @Test public void selectForGrid() { List<AccountGridVo> entities = mapper.selectForGrid("a"); assertEquals(5, entities.size()); assertEquals("玉山", entities.get(0).getName()); assertEquals(0, new BigDecimal(1000).compareTo(entities.get(0).getMoney())); assertEquals("b", entities.get(0).getAccount_type_id()); } @Test public void updateToDeleteByIds() { assertEquals(2, mapper.updateToDeleteByIds(new String[]{"a", "b"}, "a")); } }
2,409
0.67501
0.666249
74
31.391891
24.487072
107
false
false
0
0
0
0
0
0
0.743243
false
false
13
2228636e371e69109de2f0b211a41feeacd1a836
36,077,725,302,134
4b13c1b4877bd9ced4352ab58b4aa890a06c2d60
/spring-web/src/main/java/com/webcohesion/enunciate/modules/spring_web/model/RequestMapping.java
16c01410d259aa5042bd23ee878127996883462a
[ "Apache-2.0" ]
permissive
stoicflame/enunciate
https://github.com/stoicflame/enunciate
e1866a8be2e634d8c98adee853179b81df80a20e
446c86328a4eb6b7d1453fec7436c45552418d41
refs/heads/master
2023-09-04T19:24:44.788000
2023-04-28T00:36:40
2023-04-28T02:51:03
1,707,059
464
206
NOASSERTION
false
2023-08-15T17:40:53
2011-05-05T15:54:15
2023-07-19T11:21:42
2023-08-15T17:40:52
36,340
474
207
63
Java
false
false
/** * Copyright © 2006-2016 Web Cohesion (info@webcohesion.com) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webcohesion.enunciate.modules.spring_web.model; import com.webcohesion.enunciate.facets.Facet; import com.webcohesion.enunciate.facets.HasFacets; import com.webcohesion.enunciate.javac.decorations.DecoratedProcessingEnvironment; import com.webcohesion.enunciate.javac.decorations.TypeMirrorDecorator; import com.webcohesion.enunciate.javac.decorations.element.DecoratedExecutableElement; import com.webcohesion.enunciate.javac.decorations.type.DecoratedDeclaredType; import com.webcohesion.enunciate.javac.decorations.type.DecoratedTypeMirror; import com.webcohesion.enunciate.javac.decorations.type.TypeMirrorUtils; import com.webcohesion.enunciate.javac.decorations.type.TypeVariableContext; import com.webcohesion.enunciate.javac.javadoc.JavaDoc; import com.webcohesion.enunciate.javac.javadoc.ParamDocComment; import com.webcohesion.enunciate.javac.javadoc.ReturnDocComment; import com.webcohesion.enunciate.javac.javadoc.StaticDocComment; import com.webcohesion.enunciate.metadata.rs.*; import com.webcohesion.enunciate.modules.spring_web.EnunciateSpringWebContext; import com.webcohesion.enunciate.modules.spring_web.model.util.RSParamDocComment; import com.webcohesion.enunciate.modules.spring_web.model.util.ReturnWrappedDocComment; import com.webcohesion.enunciate.util.AnnotationUtils; import com.webcohesion.enunciate.util.JAXDocletUtil; import com.webcohesion.enunciate.util.TypeHintUtils; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.annotation.security.RolesAllowed; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.io.InputStream; import java.io.Reader; import java.lang.annotation.IncompleteAnnotationException; import java.util.*; import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A JAX-RS resource method. * * @author Ryan Heaton */ public class RequestMapping extends DecoratedExecutableElement implements HasFacets, PathContext { private static final Pattern CONTEXT_PARAM_PATTERN = Pattern.compile("\\{([^\\}]+)\\}"); private final EnunciateSpringWebContext context; private final List<PathSegment> pathSegments; private final String label; private final Set<String> httpMethods; private final Set<String> consumesMediaTypes; private final Set<String> producesMediaTypes; private final SpringController parent; private final Set<RequestParameter> requestParameters = new TreeSet<RequestParameter>(); private final ResourceEntityParameter entityParameter; private final Map<String, Object> metaData = new HashMap<String, Object>(); private final List<ResponseCode> statusCodes = new ArrayList<ResponseCode>(); private final List<ResponseCode> warnings = new ArrayList<ResponseCode>(); private final Map<String, String> responseHeaders = new HashMap<String, String>(); private final ResourceRepresentationMetadata representationMetadata; private final Set<Facet> facets = new TreeSet<Facet>(); public RequestMapping(List<PathSegment> pathSegments, org.springframework.web.bind.annotation.RequestMapping mapping, ExecutableElement delegate, SpringController parent, TypeVariableContext variableContext, EnunciateSpringWebContext context) { super(delegate, context.getContext().getProcessingEnvironment()); this.context = context; this.pathSegments = pathSegments; //initialize first with all methods. EnumSet<RequestMethod> httpMethods = EnumSet.allOf(RequestMethod.class); if (mapping.method().length > 0) { httpMethods.retainAll(Arrays.asList(mapping.method())); } httpMethods.retainAll(parent.getApplicableMethods()); if (httpMethods.isEmpty()) { throw new IllegalStateException(parent.getQualifiedName() + "." + getSimpleName() + ": no applicable request methods."); } this.httpMethods = new TreeSet<String>(); for (RequestMethod httpMethod : httpMethods) { this.httpMethods.add(httpMethod.name()); } Set<String> consumes = new TreeSet<String>(); if (mapping.consumes().length > 0) { for (String mediaType : mapping.consumes()) { if (mediaType.startsWith("!")) { continue; } int colonIndex = mediaType.indexOf(';'); if (colonIndex > 0) { mediaType = mediaType.substring(0, colonIndex); } consumes.add(mediaType); } if (consumes.isEmpty()) { consumes.add("*/*"); } } else { consumes = parent.getConsumesMime(); } this.consumesMediaTypes = consumes; Set<String> produces = new TreeSet<String>(); if (mapping.produces().length > 0) { for (String mediaType : mapping.produces()) { if (mediaType.startsWith("!")) { continue; } int colonIndex = mediaType.indexOf(';'); if (colonIndex > 0) { mediaType = mediaType.substring(0, colonIndex); } produces.add(mediaType); } if (produces.isEmpty()) { produces.add("*/*"); } } else { produces = parent.getProducesMime(); } this.producesMediaTypes = produces; String label = null; ResourceLabel resourceLabel = delegate.getAnnotation(ResourceLabel.class); if (resourceLabel != null) { label = resourceLabel.value(); if ("##default".equals(label)) { label = null; } } ResourceEntityParameter entityParameter = null; ResourceRepresentationMetadata outputPayload = null; Set<SpringControllerAdvice> advice = this.context.getAdvice(); for (SpringControllerAdvice controllerAdvice : advice) { List<RequestMappingAdvice> requestAdvice = controllerAdvice.findRequestMappingAdvice(this); for (RequestMappingAdvice mappingAdvice : requestAdvice) { entityParameter = mappingAdvice.getEntityParameter(); outputPayload = mappingAdvice.getRepresentationMetadata(); requestParameters.addAll(mappingAdvice.getRequestParameters()); statusCodes.addAll(mappingAdvice.getStatusCodes()); warnings.addAll(mappingAdvice.getWarnings()); this.responseHeaders.putAll(mappingAdvice.getResponseHeaders()); } } for (VariableElement parameterDeclaration : getParameters()) { if (AnnotationUtils.isIgnored(parameterDeclaration)) { continue; } if (isImplicitUntypedRequestBody(parameterDeclaration.asType()) && entityParameter == null) { DecoratedProcessingEnvironment env = context.getContext().getProcessingEnvironment(); entityParameter = new ResourceEntityParameter(this, TypeMirrorUtils.objectType(env), env); } else if (parameterDeclaration.getAnnotation(RequestBody.class) != null) { entityParameter = new ResourceEntityParameter(parameterDeclaration, variableContext, context); } else { requestParameters.addAll(RequestParameterFactory.getRequestParameters(this, parameterDeclaration, this)); } } DecoratedTypeMirror<?> returnType; TypeHint hintInfo = getAnnotation(TypeHint.class); JavaDoc localDoc = new JavaDoc(getDocComment(), null, null, this.env); if (hintInfo != null) { returnType = (DecoratedTypeMirror) TypeHintUtils.getTypeHint(hintInfo, this.env, null); if (returnType != null) { returnType.setDeferredDocComment(new ReturnDocComment(this)); } } else { returnType = (DecoratedTypeMirror) getReturnType(); if (returnType instanceof DecoratedDeclaredType && (returnType.isInstanceOf(Callable.class) || returnType.isInstanceOf("org.springframework.web.context.request.async.DeferredResult") || returnType.isInstanceOf("org.springframework.util.concurrent.ListenableFuture"))) { //attempt unwrap callable and deferred results. List<? extends TypeMirror> typeArgs = ((DecoratedDeclaredType) returnType).getTypeArguments(); returnType = (typeArgs != null && typeArgs.size() == 1) ? (DecoratedTypeMirror<?>) TypeMirrorDecorator.decorate(typeArgs.get(0), this.env) : TypeMirrorUtils.objectType(this.env); } boolean returnsResponseBody = getAnnotation(ResponseBody.class) != null || AnnotationUtils.getMetaAnnotation(ResponseBody.class, parent) != null; if (returnType instanceof DecoratedDeclaredType && returnType.isInstanceOf("org.springframework.http.HttpEntity")) { DecoratedDeclaredType entity = (DecoratedDeclaredType) returnType; List<? extends TypeMirror> typeArgs = entity.getTypeArguments(); returnType = (typeArgs != null && typeArgs.size() == 1) ? (DecoratedTypeMirror<?>) TypeMirrorDecorator.decorate(typeArgs.get(0), this.env) : TypeMirrorUtils.objectType(this.env); } else if (!returnsResponseBody) { //doesn't return response body; no way to tell what's being returned. returnType = TypeMirrorUtils.objectType(this.env); } if (returnType.isInstanceOf("org.springframework.core.io.Resource") || isImplicitUntypedEntityBody(returnType)) { //generic spring resource returnType = TypeMirrorUtils.objectType(this.env); } DecoratedTypeMirror returnWrapped = JAXDocletUtil.getReturnWrapped(getDocComment(), this.env, getContext().getContext().getLogger()); if (returnWrapped != null) { returnWrapped.setDeferredDocComment(new ReturnWrappedDocComment(this)); returnType = returnWrapped; } //now resolve any type variables. returnType = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(variableContext.resolveTypeVariables(returnType, this.env), this.env); returnType.setDeferredDocComment(new ReturnDocComment(this)); } outputPayload = returnType == null || returnType.isVoid() || returnType.isInstanceOf(Void.class) ? outputPayload : new ResourceRepresentationMetadata(returnType); JavaDoc.JavaDocTagList doclets = localDoc.get("RequestHeader"); //support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690 if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; requestParameters.add(new ExplicitRequestParameter(this, doc, header, ResourceParameterType.HEADER, context)); } } List<JavaDoc.JavaDocTagList> inheritedDoclets = AnnotationUtils.getJavaDocTags("RequestHeader", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; requestParameters.add(new ExplicitRequestParameter(this, doc, header, ResourceParameterType.HEADER, context)); } } RequestHeaders requestHeaders = getAnnotation(RequestHeaders.class); if (requestHeaders != null) { for (RequestHeader header : requestHeaders.value()) { requestParameters.add(new ExplicitRequestParameter(this, header.description(), header.name(), ResourceParameterType.HEADER, context)); } } List<RequestHeaders> inheritedRequestHeaders = AnnotationUtils.getAnnotations(RequestHeaders.class, parent, true); for (RequestHeaders inheritedRequestHeader : inheritedRequestHeaders) { for (RequestHeader header : inheritedRequestHeader.value()) { requestParameters.add(new ExplicitRequestParameter(this, header.description(), header.name(), ResourceParameterType.HEADER, context)); } } String[] headers = mapping.headers(); for (String header : headers) { //now add any "narrowing" headers that haven't been already captured. if (!contains(requestParameters, header, ResourceParameterType.HEADER)) { requestParameters.add(new ExplicitRequestParameter(this, "", header, ResourceParameterType.HEADER, false, ResourceParameterConstraints.REQUIRED, context)); } } StatusCodes codes = getAnnotation(StatusCodes.class); if (codes != null) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : codes.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); for (ResponseHeader header : code.additionalHeaders()) { rc.setAdditionalHeader(header.name(), header.description()); } rc.setType((DecoratedTypeMirror) TypeHintUtils.getTypeHint(code.type(), this.env, null)); statusCodes.add(rc); } } List<StatusCodes> inheritedStatusCodes = AnnotationUtils.getAnnotations(StatusCodes.class, parent, true); for (StatusCodes inheritedStatusCode : inheritedStatusCodes) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : inheritedStatusCode.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); for (ResponseHeader header : code.additionalHeaders()) { rc.setAdditionalHeader(header.name(), header.description()); } rc.setType((DecoratedTypeMirror) TypeHintUtils.getTypeHint(code.type(), this.env, null)); statusCodes.add(rc); } } doclets = localDoc.get("HTTP"); if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); statusCodes.add(rc); } catch (NumberFormatException e) { //fall through... } } } inheritedDoclets = AnnotationUtils.getJavaDocTags("HTTP", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); statusCodes.add(rc); } catch (NumberFormatException e) { //fall through... } } } processResponseStatus(); Warnings warningInfo = getAnnotation(Warnings.class); if (warningInfo != null) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : warningInfo.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); warnings.add(rc); } } List<Warnings> inheritedWarnings = AnnotationUtils.getAnnotations(Warnings.class, parent, true); for (Warnings inheritedWarning : inheritedWarnings) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : inheritedWarning.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); warnings.add(rc); } } doclets = localDoc.get("HTTPWarning"); if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); warnings.add(rc); } catch (NumberFormatException e) { //fall through... } } } inheritedDoclets = AnnotationUtils.getJavaDocTags("HTTPWarning", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); warnings.add(rc); } catch (NumberFormatException e) { //fall through... } } } ResponseHeaders responseHeaders = getAnnotation(ResponseHeaders.class); if (responseHeaders != null) { for (ResponseHeader header : responseHeaders.value()) { this.responseHeaders.put(header.name(), header.description()); } } List<ResponseHeaders> inheritedResponseHeaders = AnnotationUtils.getAnnotations(ResponseHeaders.class, parent, true); for (ResponseHeaders inheritedResponseHeader : inheritedResponseHeaders) { for (ResponseHeader header : inheritedResponseHeader.value()) { this.responseHeaders.put(header.name(), header.description()); } } doclets = localDoc.get("ResponseHeader"); if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; this.responseHeaders.put(header, doc); } } inheritedDoclets = AnnotationUtils.getJavaDocTags("ResponseHeader", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; this.responseHeaders.put(header, doc); } } if (outputPayload == null && getJavaDoc().get("responseExample") != null) { //if no response was found but a response example is supplied, create a dummy response output. DecoratedProcessingEnvironment env = context.getContext().getProcessingEnvironment(); outputPayload = new ResourceRepresentationMetadata(TypeMirrorUtils.objectType(env), new StaticDocComment("")); } if (entityParameter == null && getJavaDoc().get("requestExample") != null) { //if no entity parameter was found, but a request example is supplied, create a dummy entity parameter. DecoratedProcessingEnvironment env = context.getContext().getProcessingEnvironment(); entityParameter = new ResourceEntityParameter(this, TypeMirrorUtils.objectType(env), env); } this.entityParameter = entityParameter; this.label = label; this.parent = parent; this.representationMetadata = outputPayload; this.facets.addAll(Facet.gatherFacets(delegate, context.getContext())); this.facets.addAll(parent.getFacets()); } private static boolean contains(Set<RequestParameter> requestParameters, String name, ResourceParameterType type) { String typeName = type.name().toLowerCase(); for (RequestParameter requestParameter : requestParameters) { if (name.equals(requestParameter.getParameterName()) && (typeName.equals(requestParameter.getTypeName()) || "custom".equals(requestParameter.getTypeName()))) { return true; } } return false; } private boolean hasStatusCode(int value) { for (ResponseCode rc : statusCodes) { if (rc.getCode() == value) { return true; } } return false; } private void processResponseStatus() { ResponseStatus responseStatus = getAnnotation(ResponseStatus.class); if (responseStatus == null) { return; } HttpStatus code = responseStatus.value(); if (code == HttpStatus.INTERNAL_SERVER_ERROR) { try { code = responseStatus.code(); } catch (IncompleteAnnotationException e) { //fall through; 'responseStatus.code' was added in 4.2. } } if (hasStatusCode(code.value())) { return; } ResponseCode rc = new ResponseCode(this); rc.setCode(code.value()); String reason = responseStatus.reason(); if (!reason.isEmpty()) { rc.setCondition(reason); } statusCodes.add(rc); } @Override protected ParamDocComment createParamDocComment(VariableElement param) { return new RSParamDocComment(this, param.getSimpleName().toString()); } public EnunciateSpringWebContext getContext() { return context; } /** * The HTTP methods for invoking the method. * * @return The HTTP methods for invoking the method. */ public Set<String> getHttpMethods() { return httpMethods; } /** * Get the path components for this resource method. * * @return The path components. */ public List<PathSegment> getPathSegments() { return this.pathSegments; } @Override public boolean isUrlEncodedFormPost() { return (this.httpMethods.contains("POST") && this.consumesMediaTypes.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE)); } /** * Builds the full URI path to this resource method. * * @return the full URI path to this resource method. */ public String getFullpath() { StringBuilder builder = new StringBuilder(); for (PathSegment pathSegment : getPathSegments()) { builder.append(pathSegment.getValue()); } return builder.toString(); } /** * The servlet pattern that can be applied to access this resource method. * * @return The servlet pattern that can be applied to access this resource method. */ public String getServletPattern() { StringBuilder builder = new StringBuilder(); String fullPath = getFullpath(); Matcher pathParamMatcher = CONTEXT_PARAM_PATTERN.matcher(fullPath); if (pathParamMatcher.find()) { builder.append(fullPath, 0, pathParamMatcher.start()).append("*"); } else { builder.append(fullPath); } return builder.toString(); } /** * The label for this resource method, if it exists. * * @return The subpath for this resource method, if it exists. */ public String getLabel() { return label; } /** * The resource that holds this resource method. * * @return The resource that holds this resource method. */ public SpringController getParent() { return parent; } /** * The MIME types that are consumed by this method. * * @return The MIME types that are consumed by this method. */ public Set<String> getConsumesMediaTypes() { return consumesMediaTypes; } /** * The MIME types that are produced by this method. * * @return The MIME types that are produced by this method. */ public Set<String> getProducesMediaTypes() { return producesMediaTypes; } /** * The list of resource parameters that this method requires to be invoked. * * @return The list of resource parameters that this method requires to be invoked. */ public Set<RequestParameter> getRequestParameters() { return this.requestParameters; } /** * The entity parameter. * * @return The entity parameter, or null if none. */ public ResourceEntityParameter getEntityParameter() { return entityParameter; } /** * The output payload for this resource. * * @return The output payload for this resource. */ public ResourceRepresentationMetadata getRepresentationMetadata() { return this.representationMetadata; } /** * The potential status codes. * * @return The potential status codes. */ public List<? extends ResponseCode> getStatusCodes() { return this.statusCodes; } /** * The potential warnings. * * @return The potential warnings. */ public List<? extends ResponseCode> getWarnings() { return this.warnings; } /** * The metadata associated with this resource. * * @return The metadata associated with this resource. */ public Map<String, Object> getMetaData() { return Collections.unmodifiableMap(this.metaData); } /** * Put metadata associated with this resource. * * @param name The name of the metadata. * @param data The data. */ public void putMetaData(String name, Object data) { this.metaData.put(name, data); } /** * The response headers that are expected on this resource method. * * @return The response headers that are expected on this resource method. */ public Map<String, String> getResponseHeaders() { return responseHeaders; } /** * The facets here applicable. * * @return The facets here applicable. */ public Set<Facet> getFacets() { return facets; } /** * The security roles for this method. * * @return The security roles for this method. */ public Set<String> getSecurityRoles() { TreeSet<String> roles = new TreeSet<String>(); RolesAllowed rolesAllowed = getAnnotation(RolesAllowed.class); if (rolesAllowed != null) { Collections.addAll(roles, rolesAllowed.value()); } SpringController parent = getParent(); if (parent != null) { roles.addAll(parent.getSecurityRoles()); } return roles; } private boolean isImplicitUntypedRequestBody(TypeMirror parameterType) { DecoratedTypeMirror<?> type = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(parameterType, env); return isImplicitUntypedEntityBody(type) || type .isInstanceOf("javax.servlet.ServletRequest") || type.isInstanceOf("javax.servlet.http.HttpServletRequest"); } private boolean isImplicitUntypedEntityBody(DecoratedTypeMirror<?> type) { return type.isInstanceOf(InputStream.class) || type.isInstanceOf(Reader.class); } }
UTF-8
Java
27,521
java
RequestMapping.java
Java
[ { "context": "/**\n * Copyright © 2006-2016 Web Cohesion (info@webcohesion.com)\n * <p>\n * Licensed under the Apache License, Ver", "end": 63, "score": 0.9999275803565979, "start": 43, "tag": "EMAIL", "value": "info@webcohesion.com" }, { "context": "n;\n\n/**\n * A JAX-RS resource m...
null
[]
/** * Copyright © 2006-2016 Web Cohesion (<EMAIL>) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webcohesion.enunciate.modules.spring_web.model; import com.webcohesion.enunciate.facets.Facet; import com.webcohesion.enunciate.facets.HasFacets; import com.webcohesion.enunciate.javac.decorations.DecoratedProcessingEnvironment; import com.webcohesion.enunciate.javac.decorations.TypeMirrorDecorator; import com.webcohesion.enunciate.javac.decorations.element.DecoratedExecutableElement; import com.webcohesion.enunciate.javac.decorations.type.DecoratedDeclaredType; import com.webcohesion.enunciate.javac.decorations.type.DecoratedTypeMirror; import com.webcohesion.enunciate.javac.decorations.type.TypeMirrorUtils; import com.webcohesion.enunciate.javac.decorations.type.TypeVariableContext; import com.webcohesion.enunciate.javac.javadoc.JavaDoc; import com.webcohesion.enunciate.javac.javadoc.ParamDocComment; import com.webcohesion.enunciate.javac.javadoc.ReturnDocComment; import com.webcohesion.enunciate.javac.javadoc.StaticDocComment; import com.webcohesion.enunciate.metadata.rs.*; import com.webcohesion.enunciate.modules.spring_web.EnunciateSpringWebContext; import com.webcohesion.enunciate.modules.spring_web.model.util.RSParamDocComment; import com.webcohesion.enunciate.modules.spring_web.model.util.ReturnWrappedDocComment; import com.webcohesion.enunciate.util.AnnotationUtils; import com.webcohesion.enunciate.util.JAXDocletUtil; import com.webcohesion.enunciate.util.TypeHintUtils; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.annotation.security.RolesAllowed; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.io.InputStream; import java.io.Reader; import java.lang.annotation.IncompleteAnnotationException; import java.util.*; import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A JAX-RS resource method. * * @author <NAME> */ public class RequestMapping extends DecoratedExecutableElement implements HasFacets, PathContext { private static final Pattern CONTEXT_PARAM_PATTERN = Pattern.compile("\\{([^\\}]+)\\}"); private final EnunciateSpringWebContext context; private final List<PathSegment> pathSegments; private final String label; private final Set<String> httpMethods; private final Set<String> consumesMediaTypes; private final Set<String> producesMediaTypes; private final SpringController parent; private final Set<RequestParameter> requestParameters = new TreeSet<RequestParameter>(); private final ResourceEntityParameter entityParameter; private final Map<String, Object> metaData = new HashMap<String, Object>(); private final List<ResponseCode> statusCodes = new ArrayList<ResponseCode>(); private final List<ResponseCode> warnings = new ArrayList<ResponseCode>(); private final Map<String, String> responseHeaders = new HashMap<String, String>(); private final ResourceRepresentationMetadata representationMetadata; private final Set<Facet> facets = new TreeSet<Facet>(); public RequestMapping(List<PathSegment> pathSegments, org.springframework.web.bind.annotation.RequestMapping mapping, ExecutableElement delegate, SpringController parent, TypeVariableContext variableContext, EnunciateSpringWebContext context) { super(delegate, context.getContext().getProcessingEnvironment()); this.context = context; this.pathSegments = pathSegments; //initialize first with all methods. EnumSet<RequestMethod> httpMethods = EnumSet.allOf(RequestMethod.class); if (mapping.method().length > 0) { httpMethods.retainAll(Arrays.asList(mapping.method())); } httpMethods.retainAll(parent.getApplicableMethods()); if (httpMethods.isEmpty()) { throw new IllegalStateException(parent.getQualifiedName() + "." + getSimpleName() + ": no applicable request methods."); } this.httpMethods = new TreeSet<String>(); for (RequestMethod httpMethod : httpMethods) { this.httpMethods.add(httpMethod.name()); } Set<String> consumes = new TreeSet<String>(); if (mapping.consumes().length > 0) { for (String mediaType : mapping.consumes()) { if (mediaType.startsWith("!")) { continue; } int colonIndex = mediaType.indexOf(';'); if (colonIndex > 0) { mediaType = mediaType.substring(0, colonIndex); } consumes.add(mediaType); } if (consumes.isEmpty()) { consumes.add("*/*"); } } else { consumes = parent.getConsumesMime(); } this.consumesMediaTypes = consumes; Set<String> produces = new TreeSet<String>(); if (mapping.produces().length > 0) { for (String mediaType : mapping.produces()) { if (mediaType.startsWith("!")) { continue; } int colonIndex = mediaType.indexOf(';'); if (colonIndex > 0) { mediaType = mediaType.substring(0, colonIndex); } produces.add(mediaType); } if (produces.isEmpty()) { produces.add("*/*"); } } else { produces = parent.getProducesMime(); } this.producesMediaTypes = produces; String label = null; ResourceLabel resourceLabel = delegate.getAnnotation(ResourceLabel.class); if (resourceLabel != null) { label = resourceLabel.value(); if ("##default".equals(label)) { label = null; } } ResourceEntityParameter entityParameter = null; ResourceRepresentationMetadata outputPayload = null; Set<SpringControllerAdvice> advice = this.context.getAdvice(); for (SpringControllerAdvice controllerAdvice : advice) { List<RequestMappingAdvice> requestAdvice = controllerAdvice.findRequestMappingAdvice(this); for (RequestMappingAdvice mappingAdvice : requestAdvice) { entityParameter = mappingAdvice.getEntityParameter(); outputPayload = mappingAdvice.getRepresentationMetadata(); requestParameters.addAll(mappingAdvice.getRequestParameters()); statusCodes.addAll(mappingAdvice.getStatusCodes()); warnings.addAll(mappingAdvice.getWarnings()); this.responseHeaders.putAll(mappingAdvice.getResponseHeaders()); } } for (VariableElement parameterDeclaration : getParameters()) { if (AnnotationUtils.isIgnored(parameterDeclaration)) { continue; } if (isImplicitUntypedRequestBody(parameterDeclaration.asType()) && entityParameter == null) { DecoratedProcessingEnvironment env = context.getContext().getProcessingEnvironment(); entityParameter = new ResourceEntityParameter(this, TypeMirrorUtils.objectType(env), env); } else if (parameterDeclaration.getAnnotation(RequestBody.class) != null) { entityParameter = new ResourceEntityParameter(parameterDeclaration, variableContext, context); } else { requestParameters.addAll(RequestParameterFactory.getRequestParameters(this, parameterDeclaration, this)); } } DecoratedTypeMirror<?> returnType; TypeHint hintInfo = getAnnotation(TypeHint.class); JavaDoc localDoc = new JavaDoc(getDocComment(), null, null, this.env); if (hintInfo != null) { returnType = (DecoratedTypeMirror) TypeHintUtils.getTypeHint(hintInfo, this.env, null); if (returnType != null) { returnType.setDeferredDocComment(new ReturnDocComment(this)); } } else { returnType = (DecoratedTypeMirror) getReturnType(); if (returnType instanceof DecoratedDeclaredType && (returnType.isInstanceOf(Callable.class) || returnType.isInstanceOf("org.springframework.web.context.request.async.DeferredResult") || returnType.isInstanceOf("org.springframework.util.concurrent.ListenableFuture"))) { //attempt unwrap callable and deferred results. List<? extends TypeMirror> typeArgs = ((DecoratedDeclaredType) returnType).getTypeArguments(); returnType = (typeArgs != null && typeArgs.size() == 1) ? (DecoratedTypeMirror<?>) TypeMirrorDecorator.decorate(typeArgs.get(0), this.env) : TypeMirrorUtils.objectType(this.env); } boolean returnsResponseBody = getAnnotation(ResponseBody.class) != null || AnnotationUtils.getMetaAnnotation(ResponseBody.class, parent) != null; if (returnType instanceof DecoratedDeclaredType && returnType.isInstanceOf("org.springframework.http.HttpEntity")) { DecoratedDeclaredType entity = (DecoratedDeclaredType) returnType; List<? extends TypeMirror> typeArgs = entity.getTypeArguments(); returnType = (typeArgs != null && typeArgs.size() == 1) ? (DecoratedTypeMirror<?>) TypeMirrorDecorator.decorate(typeArgs.get(0), this.env) : TypeMirrorUtils.objectType(this.env); } else if (!returnsResponseBody) { //doesn't return response body; no way to tell what's being returned. returnType = TypeMirrorUtils.objectType(this.env); } if (returnType.isInstanceOf("org.springframework.core.io.Resource") || isImplicitUntypedEntityBody(returnType)) { //generic spring resource returnType = TypeMirrorUtils.objectType(this.env); } DecoratedTypeMirror returnWrapped = JAXDocletUtil.getReturnWrapped(getDocComment(), this.env, getContext().getContext().getLogger()); if (returnWrapped != null) { returnWrapped.setDeferredDocComment(new ReturnWrappedDocComment(this)); returnType = returnWrapped; } //now resolve any type variables. returnType = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(variableContext.resolveTypeVariables(returnType, this.env), this.env); returnType.setDeferredDocComment(new ReturnDocComment(this)); } outputPayload = returnType == null || returnType.isVoid() || returnType.isInstanceOf(Void.class) ? outputPayload : new ResourceRepresentationMetadata(returnType); JavaDoc.JavaDocTagList doclets = localDoc.get("RequestHeader"); //support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690 if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; requestParameters.add(new ExplicitRequestParameter(this, doc, header, ResourceParameterType.HEADER, context)); } } List<JavaDoc.JavaDocTagList> inheritedDoclets = AnnotationUtils.getJavaDocTags("RequestHeader", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; requestParameters.add(new ExplicitRequestParameter(this, doc, header, ResourceParameterType.HEADER, context)); } } RequestHeaders requestHeaders = getAnnotation(RequestHeaders.class); if (requestHeaders != null) { for (RequestHeader header : requestHeaders.value()) { requestParameters.add(new ExplicitRequestParameter(this, header.description(), header.name(), ResourceParameterType.HEADER, context)); } } List<RequestHeaders> inheritedRequestHeaders = AnnotationUtils.getAnnotations(RequestHeaders.class, parent, true); for (RequestHeaders inheritedRequestHeader : inheritedRequestHeaders) { for (RequestHeader header : inheritedRequestHeader.value()) { requestParameters.add(new ExplicitRequestParameter(this, header.description(), header.name(), ResourceParameterType.HEADER, context)); } } String[] headers = mapping.headers(); for (String header : headers) { //now add any "narrowing" headers that haven't been already captured. if (!contains(requestParameters, header, ResourceParameterType.HEADER)) { requestParameters.add(new ExplicitRequestParameter(this, "", header, ResourceParameterType.HEADER, false, ResourceParameterConstraints.REQUIRED, context)); } } StatusCodes codes = getAnnotation(StatusCodes.class); if (codes != null) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : codes.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); for (ResponseHeader header : code.additionalHeaders()) { rc.setAdditionalHeader(header.name(), header.description()); } rc.setType((DecoratedTypeMirror) TypeHintUtils.getTypeHint(code.type(), this.env, null)); statusCodes.add(rc); } } List<StatusCodes> inheritedStatusCodes = AnnotationUtils.getAnnotations(StatusCodes.class, parent, true); for (StatusCodes inheritedStatusCode : inheritedStatusCodes) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : inheritedStatusCode.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); for (ResponseHeader header : code.additionalHeaders()) { rc.setAdditionalHeader(header.name(), header.description()); } rc.setType((DecoratedTypeMirror) TypeHintUtils.getTypeHint(code.type(), this.env, null)); statusCodes.add(rc); } } doclets = localDoc.get("HTTP"); if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); statusCodes.add(rc); } catch (NumberFormatException e) { //fall through... } } } inheritedDoclets = AnnotationUtils.getJavaDocTags("HTTP", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); statusCodes.add(rc); } catch (NumberFormatException e) { //fall through... } } } processResponseStatus(); Warnings warningInfo = getAnnotation(Warnings.class); if (warningInfo != null) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : warningInfo.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); warnings.add(rc); } } List<Warnings> inheritedWarnings = AnnotationUtils.getAnnotations(Warnings.class, parent, true); for (Warnings inheritedWarning : inheritedWarnings) { for (com.webcohesion.enunciate.metadata.rs.ResponseCode code : inheritedWarning.value()) { ResponseCode rc = new ResponseCode(this); rc.setCode(code.code()); rc.setCondition(code.condition()); warnings.add(rc); } } doclets = localDoc.get("HTTPWarning"); if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); warnings.add(rc); } catch (NumberFormatException e) { //fall through... } } } inheritedDoclets = AnnotationUtils.getJavaDocTags("HTTPWarning", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; try { ResponseCode rc = new ResponseCode(this); rc.setCode(Integer.parseInt(code)); rc.setCondition(doc); warnings.add(rc); } catch (NumberFormatException e) { //fall through... } } } ResponseHeaders responseHeaders = getAnnotation(ResponseHeaders.class); if (responseHeaders != null) { for (ResponseHeader header : responseHeaders.value()) { this.responseHeaders.put(header.name(), header.description()); } } List<ResponseHeaders> inheritedResponseHeaders = AnnotationUtils.getAnnotations(ResponseHeaders.class, parent, true); for (ResponseHeaders inheritedResponseHeader : inheritedResponseHeaders) { for (ResponseHeader header : inheritedResponseHeader.value()) { this.responseHeaders.put(header.name(), header.description()); } } doclets = localDoc.get("ResponseHeader"); if (doclets != null) { for (String doclet : doclets) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; this.responseHeaders.put(header, doc); } } inheritedDoclets = AnnotationUtils.getJavaDocTags("ResponseHeader", parent); for (JavaDoc.JavaDocTagList inheritedDoclet : inheritedDoclets) { for (String doclet : inheritedDoclet) { int firstspace = JavaDoc.indexOfFirstWhitespace(doclet); String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet; String doc = ((firstspace > 0) && (firstspace + 1 < doclet.length())) ? doclet.substring(firstspace + 1) : ""; this.responseHeaders.put(header, doc); } } if (outputPayload == null && getJavaDoc().get("responseExample") != null) { //if no response was found but a response example is supplied, create a dummy response output. DecoratedProcessingEnvironment env = context.getContext().getProcessingEnvironment(); outputPayload = new ResourceRepresentationMetadata(TypeMirrorUtils.objectType(env), new StaticDocComment("")); } if (entityParameter == null && getJavaDoc().get("requestExample") != null) { //if no entity parameter was found, but a request example is supplied, create a dummy entity parameter. DecoratedProcessingEnvironment env = context.getContext().getProcessingEnvironment(); entityParameter = new ResourceEntityParameter(this, TypeMirrorUtils.objectType(env), env); } this.entityParameter = entityParameter; this.label = label; this.parent = parent; this.representationMetadata = outputPayload; this.facets.addAll(Facet.gatherFacets(delegate, context.getContext())); this.facets.addAll(parent.getFacets()); } private static boolean contains(Set<RequestParameter> requestParameters, String name, ResourceParameterType type) { String typeName = type.name().toLowerCase(); for (RequestParameter requestParameter : requestParameters) { if (name.equals(requestParameter.getParameterName()) && (typeName.equals(requestParameter.getTypeName()) || "custom".equals(requestParameter.getTypeName()))) { return true; } } return false; } private boolean hasStatusCode(int value) { for (ResponseCode rc : statusCodes) { if (rc.getCode() == value) { return true; } } return false; } private void processResponseStatus() { ResponseStatus responseStatus = getAnnotation(ResponseStatus.class); if (responseStatus == null) { return; } HttpStatus code = responseStatus.value(); if (code == HttpStatus.INTERNAL_SERVER_ERROR) { try { code = responseStatus.code(); } catch (IncompleteAnnotationException e) { //fall through; 'responseStatus.code' was added in 4.2. } } if (hasStatusCode(code.value())) { return; } ResponseCode rc = new ResponseCode(this); rc.setCode(code.value()); String reason = responseStatus.reason(); if (!reason.isEmpty()) { rc.setCondition(reason); } statusCodes.add(rc); } @Override protected ParamDocComment createParamDocComment(VariableElement param) { return new RSParamDocComment(this, param.getSimpleName().toString()); } public EnunciateSpringWebContext getContext() { return context; } /** * The HTTP methods for invoking the method. * * @return The HTTP methods for invoking the method. */ public Set<String> getHttpMethods() { return httpMethods; } /** * Get the path components for this resource method. * * @return The path components. */ public List<PathSegment> getPathSegments() { return this.pathSegments; } @Override public boolean isUrlEncodedFormPost() { return (this.httpMethods.contains("POST") && this.consumesMediaTypes.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE)); } /** * Builds the full URI path to this resource method. * * @return the full URI path to this resource method. */ public String getFullpath() { StringBuilder builder = new StringBuilder(); for (PathSegment pathSegment : getPathSegments()) { builder.append(pathSegment.getValue()); } return builder.toString(); } /** * The servlet pattern that can be applied to access this resource method. * * @return The servlet pattern that can be applied to access this resource method. */ public String getServletPattern() { StringBuilder builder = new StringBuilder(); String fullPath = getFullpath(); Matcher pathParamMatcher = CONTEXT_PARAM_PATTERN.matcher(fullPath); if (pathParamMatcher.find()) { builder.append(fullPath, 0, pathParamMatcher.start()).append("*"); } else { builder.append(fullPath); } return builder.toString(); } /** * The label for this resource method, if it exists. * * @return The subpath for this resource method, if it exists. */ public String getLabel() { return label; } /** * The resource that holds this resource method. * * @return The resource that holds this resource method. */ public SpringController getParent() { return parent; } /** * The MIME types that are consumed by this method. * * @return The MIME types that are consumed by this method. */ public Set<String> getConsumesMediaTypes() { return consumesMediaTypes; } /** * The MIME types that are produced by this method. * * @return The MIME types that are produced by this method. */ public Set<String> getProducesMediaTypes() { return producesMediaTypes; } /** * The list of resource parameters that this method requires to be invoked. * * @return The list of resource parameters that this method requires to be invoked. */ public Set<RequestParameter> getRequestParameters() { return this.requestParameters; } /** * The entity parameter. * * @return The entity parameter, or null if none. */ public ResourceEntityParameter getEntityParameter() { return entityParameter; } /** * The output payload for this resource. * * @return The output payload for this resource. */ public ResourceRepresentationMetadata getRepresentationMetadata() { return this.representationMetadata; } /** * The potential status codes. * * @return The potential status codes. */ public List<? extends ResponseCode> getStatusCodes() { return this.statusCodes; } /** * The potential warnings. * * @return The potential warnings. */ public List<? extends ResponseCode> getWarnings() { return this.warnings; } /** * The metadata associated with this resource. * * @return The metadata associated with this resource. */ public Map<String, Object> getMetaData() { return Collections.unmodifiableMap(this.metaData); } /** * Put metadata associated with this resource. * * @param name The name of the metadata. * @param data The data. */ public void putMetaData(String name, Object data) { this.metaData.put(name, data); } /** * The response headers that are expected on this resource method. * * @return The response headers that are expected on this resource method. */ public Map<String, String> getResponseHeaders() { return responseHeaders; } /** * The facets here applicable. * * @return The facets here applicable. */ public Set<Facet> getFacets() { return facets; } /** * The security roles for this method. * * @return The security roles for this method. */ public Set<String> getSecurityRoles() { TreeSet<String> roles = new TreeSet<String>(); RolesAllowed rolesAllowed = getAnnotation(RolesAllowed.class); if (rolesAllowed != null) { Collections.addAll(roles, rolesAllowed.value()); } SpringController parent = getParent(); if (parent != null) { roles.addAll(parent.getSecurityRoles()); } return roles; } private boolean isImplicitUntypedRequestBody(TypeMirror parameterType) { DecoratedTypeMirror<?> type = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(parameterType, env); return isImplicitUntypedEntityBody(type) || type .isInstanceOf("javax.servlet.ServletRequest") || type.isInstanceOf("javax.servlet.http.HttpServletRequest"); } private boolean isImplicitUntypedEntityBody(DecoratedTypeMirror<?> type) { return type.isInstanceOf(InputStream.class) || type.isInstanceOf(Reader.class); } }
27,503
0.695058
0.692551
718
37.32869
36.503109
275
false
false
0
0
0
0
0
0
0.558496
false
false
13
2067a988c2f74536ceb7a30f5ce72507d1cd42df
35,983,236,024,938
630d6f8f45e4de9062f717bf892cf5e760bf96b6
/JavaClass/projects/chapter08/zuul-with-enums-v2/TransporterRoom.java
1733c2eea2a8913124060272b63406a9da49b49e
[]
no_license
WMFuentes/School
https://github.com/WMFuentes/School
0a67e8b8c0995dbce71c33485c3265aaff9ac974
8069f091b97a7308cbc1546a760f69a92e0b3068
refs/heads/master
2020-07-31T12:10:30.756000
2019-12-04T01:19:33
2019-12-04T01:19:33
210,599,295
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Subclass of Room called TransporterRoom. * * @author William Fuentes * @version Final Project 11/29/19 */ public class TransporterRoom extends Room { /** * Constructor for objects of class TransporterRoom */ public TransporterRoom(String description) { // initialise instance variables super(description); } }
UTF-8
Java
370
java
TransporterRoom.java
Java
[ { "context": "ass of Room called TransporterRoom. \n *\n * @author William Fuentes\n * @version Final Project 11/29/19\n */\npublic cla", "end": 78, "score": 0.999842643737793, "start": 63, "tag": "NAME", "value": "William Fuentes" } ]
null
[]
/** * Subclass of Room called TransporterRoom. * * @author <NAME> * @version Final Project 11/29/19 */ public class TransporterRoom extends Room { /** * Constructor for objects of class TransporterRoom */ public TransporterRoom(String description) { // initialise instance variables super(description); } }
361
0.651351
0.635135
19
18.473684
18.669899
55
false
false
0
0
0
0
0
0
0.052632
false
false
13
0243704ee7e23331faa6f6d5d214b1e72f6b7528
33,981,781,283,925
bce7035efa355836b6445f525c87813fbb5839c0
/src/internaltools/api/src/test/java/com/ihg/it/pfm/api/cra/BasicSupport.java
57eefd41bcceb9a410a88cf331f5318032d7239d
[]
no_license
balanzer/cra
https://github.com/balanzer/cra
5cb8fa2b53f89c2f1a3bd5a33738f2f42942975c
250f0b6c38cfacd7461233613bd44e1a7938f09a
refs/heads/master
2021-01-15T22:46:19.925000
2017-08-16T19:18:00
2017-08-16T19:18:00
99,910,873
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.ihg.it.pfm.api.cra; import java.util.HashMap; import java.util.Map; /** * @author varathm * */ public class BasicSupport { protected static final String NAME = "name"; protected static final String DESC = "desc"; static Map<String, String> campaignValues = new HashMap<>(); static { campaignValues.put(NAME, "UT campaign Name"); campaignValues.put(DESC, "UT Desc"); } }
UTF-8
Java
438
java
BasicSupport.java
Java
[ { "context": "til.HashMap;\nimport java.util.Map;\n\n/**\n * @author varathm\n *\n */\npublic class BasicSupport {\n\n protected", "end": 115, "score": 0.9993570446968079, "start": 108, "tag": "USERNAME", "value": "varathm" } ]
null
[]
/** * */ package com.ihg.it.pfm.api.cra; import java.util.HashMap; import java.util.Map; /** * @author varathm * */ public class BasicSupport { protected static final String NAME = "name"; protected static final String DESC = "desc"; static Map<String, String> campaignValues = new HashMap<>(); static { campaignValues.put(NAME, "UT campaign Name"); campaignValues.put(DESC, "UT Desc"); } }
438
0.636986
0.636986
25
16.52
19.92008
64
false
false
0
0
0
0
0
0
0.44
false
false
13
844a096557448f3903640c8879bee23d70433b27
35,433,480,218,550
d2f0eb442d42233049d9e8ae396b5e244fa353dc
/Proyecto_IngSoftware/IngenieriaSoftware/src/modelos/DlgIngresoRegistro.java
4da2b81a197c5e17ce67b2634986e822be3704fb
[]
no_license
SpawnQQ/Java_netbeans
https://github.com/SpawnQQ/Java_netbeans
b4d2b29732b82e1d69a30a546176810507c72c85
4f1edf6fd805475662722c0c96f34048ac5a7027
refs/heads/master
2020-01-23T22:05:21.009000
2017-05-03T03:56:21
2017-05-03T03:56:21
74,613,897
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modelos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; import modelos.Registro; import servicios.Conexion; import servicios.Registro_servicio; /** * * @author Ahri */ public class DlgIngresoRegistro extends javax.swing.JDialog { public static boolean isValidDate(String inDate) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); try { dateFormat.parse(inDate.trim()); } catch (Exception e) { return false; } return true; } /** * Creates new form DlgIngresoRegistro */ public static String fechaActual() { Date fecha = new Date(); SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/YYYY"); return formatoFecha.format(fecha); } public DlgIngresoRegistro(javax.swing.JDialog parent, boolean modal) { super(parent, modal); initComponents(); this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtId_registro = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); txtFechaAA = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); txtDescripcion = new javax.swing.JTextArea(); jLabel6 = new javax.swing.JLabel(); txtStock = new javax.swing.JTextField(); txtFechaMM = new javax.swing.JTextField(); txtFechaDD = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); btnGuardar = new javax.swing.JButton(); btnLimpiar = new javax.swing.JButton(); btnVolver = new javax.swing.JButton(); btnFechaActual = new javax.swing.JButton(); cmbMedida = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setForeground(new java.awt.Color(51, 51, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Ingreso de los registros"); jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jLabel2.setText("ID del registro"); txtId_registro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtId_registroActionPerformed(evt); } }); jLabel3.setText("Medicamento"); jLabel4.setText("Fecha"); txtFechaAA.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtFechaAA.setText("AAAA"); txtFechaAA.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFechaAAFocusGained(evt); } }); txtFechaAA.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtFechaAAMouseClicked(evt); } }); txtFechaAA.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtFechaAAActionPerformed(evt); } }); jLabel5.setText("Medida"); txtDescripcion.setColumns(20); txtDescripcion.setRows(5); jScrollPane1.setViewportView(txtDescripcion); jLabel6.setText("Stock"); txtFechaMM.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtFechaMM.setText("MM"); txtFechaMM.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFechaMMFocusGained(evt); } }); txtFechaMM.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtFechaMMMouseClicked(evt); } }); txtFechaDD.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtFechaDD.setText("DD"); txtFechaDD.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFechaDDFocusGained(evt); } }); txtFechaDD.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtFechaDDMouseClicked(evt); } }); jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("/"); jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("/"); btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1446613046_floppy.png"))); // NOI18N btnGuardar.setToolTipText("Guardar registro"); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } }); btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1446609695_edit-clear.png"))); // NOI18N btnLimpiar.setToolTipText("Limpiar casillas de texto"); btnLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLimpiarActionPerformed(evt); } }); btnVolver.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1446609011_go-back.png"))); // NOI18N btnVolver.setToolTipText("Volver"); btnVolver.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnVolverMouseClicked(evt); } }); btnFechaActual.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1447540901_calendar.png"))); // NOI18N btnFechaActual.setToolTipText("Insertar fecha actual"); btnFechaActual.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFechaActualActionPerformed(evt); } }); cmbMedida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione medida del medicamento", "sin medida", "100ml", "125ml", "250ml", "500ml", "1000ml" })); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(btnGuardar) .addGap(18, 18, 18) .addComponent(btnLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnVolver, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtId_registro) .addComponent(jScrollPane1) .addComponent(txtStock, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtFechaAA, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(txtFechaMM, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE) .addComponent(txtFechaDD, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnFechaActual, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(cmbMedida, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(45, 45, 45)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtId_registro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(49, 49, 49) .addComponent(jLabel3)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtFechaMM) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnFechaActual) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtFechaDD, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtFechaAA) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel7) .addComponent(jLabel8)))) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(cmbMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnVolver, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnLimpiar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(26, 26, 26)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtId_registroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtId_registroActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtId_registroActionPerformed private void txtFechaAAMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaAAMouseClicked // TODO add your handling code here: txtFechaAA.setText(null); String vacio = ""; if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaAAMouseClicked private void txtFechaMMMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaMMMouseClicked // TODO add your handling code here: txtFechaMM.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaMMMouseClicked private void txtFechaDDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaDDMouseClicked // TODO add your handling code here: txtFechaDD.setText(null); txtFechaDD.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } }//GEN-LAST:event_txtFechaDDMouseClicked private void btnVolverMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVolverMouseClicked // TODO add your handling code here: this.setVisible(false); }//GEN-LAST:event_btnVolverMouseClicked private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed // TODO add your handling code here: Registro registro = new Registro(); Registro_servicio rs = new Registro_servicio(); Conexion con = new Conexion(); Connection reg = con.obtenerConexion(); int id_registro, stock, aux = 0; String nombre, fecha, medida; id_registro = Integer.parseInt(txtId_registro.getText()); nombre = txtDescripcion.getText(); fecha = txtFechaAA.getText() + "-" + txtFechaMM.getText() + "-" + txtFechaDD.getText(); medida = cmbMedida.getSelectedItem().toString(); stock = Integer.parseInt(txtStock.getText()); registro = new Registro(id_registro, nombre, fecha, medida, stock); String aux5 = txtId_registro.getText().trim(); String aux2 = txtDescripcion.getText().trim(); String ano = txtFechaAA.getText().trim(); String mes = txtFechaMM.getText().trim(); String dia = txtFechaDD.getText().trim(); String aux13 = cmbMedida.getSelectedItem().toString(); String aux15 = txtStock.getText(); String ano1 = txtFechaAA.getText(); String mes1 = txtFechaMM.getText(); String dia1= txtFechaDD.getText(); String fechas = ano1+'-'+mes1+'-'+dia1; if (isValidDate(fechas)) { if(aux13== "Seleccione medida del medicamento"||aux5.length()== 0||aux2.length()== 0||ano.length()== 0||dia.length()== 0||mes.length()== 0||aux15.length()== 0){ JOptionPane.showMessageDialog(this,"Cada campo debe ser llenado","Error",JOptionPane.ERROR_MESSAGE); }else{ try { PreparedStatement consulta = reg.prepareStatement("SELECT * FROM registro"); ResultSet resultado = consulta.executeQuery(); while (resultado.next()) { if (resultado.getInt("id_registro") == id_registro) { aux=1; } else { if (resultado.getString("nombre").equals(nombre) && resultado.getString("medida").equals(medida)) { aux = 2; } } } } catch (SQLException ex) { } if (aux == 0) { rs.guardar(reg, registro); JOptionPane.showMessageDialog(this, "Se guardo su registro correctamente"); this.setVisible(false); } else { if(aux==2){ JOptionPane.showMessageDialog(this, "Ya se encuentra el NOMBRE y MEDIDA del medicamento registrado en nuestras bases de datos"); cmbMedida.setSelectedItem("Seleccione medida del medicamento"); cmbMedida.requestFocus();}else{ if(aux==1){ JOptionPane.showMessageDialog(this, "Ya se encuentra el CODIGO del medicamento registrado en nuestras bases de datos"); txtId_registro.setText(null); txtId_registro.requestFocus(); } } } }}else{JOptionPane.showMessageDialog(this,"Error en la fecha","Error",JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnGuardarActionPerformed private void txtFechaAAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFechaAAActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtFechaAAActionPerformed private void txtFechaAAFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFechaAAFocusGained // TODO add your handling code here: txtFechaAA.setText(null); String vacio = ""; if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaAAFocusGained private void txtFechaMMFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFechaMMFocusGained // TODO add your handling code here: txtFechaMM.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaMMFocusGained private void txtFechaDDFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFechaDDFocusGained // TODO add your handling code here: txtFechaDD.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } }//GEN-LAST:event_txtFechaDDFocusGained private void btnFechaActualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFechaActualActionPerformed // TODO add your handling code here: String[] fecha = fechaActual().split("/"); txtFechaDD.setText(fecha[0]); txtFechaMM.setText(fecha[1]); txtFechaAA.setText(fecha[2]); }//GEN-LAST:event_btnFechaActualActionPerformed private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed // TODO add your handling code here: txtId_registro.setText(null); txtDescripcion.setText(null); cmbMedida.setSelectedItem("Seleccione medida del medicamento"); txtStock.setText(null); txtId_registro.requestFocus(); }//GEN-LAST:event_btnLimpiarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { DlgIngresoRegistro dialog = new DlgIngresoRegistro(new javax.swing.JDialog(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnFechaActual; private javax.swing.JButton btnGuardar; private javax.swing.JButton btnLimpiar; private javax.swing.JButton btnVolver; private javax.swing.JComboBox cmbMedida; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea txtDescripcion; private javax.swing.JTextField txtFechaAA; private javax.swing.JTextField txtFechaDD; private javax.swing.JTextField txtFechaMM; private javax.swing.JTextField txtId_registro; private javax.swing.JTextField txtStock; // End of variables declaration//GEN-END:variables }
UTF-8
Java
26,169
java
DlgIngresoRegistro.java
Java
[ { "context": "rt servicios.Registro_servicio;\n\n/**\n *\n * @author Ahri\n */\npublic class DlgIngresoRegistro extends javax", "end": 524, "score": 0.9938409328460693, "start": 520, "tag": "NAME", "value": "Ahri" } ]
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 modelos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; import modelos.Registro; import servicios.Conexion; import servicios.Registro_servicio; /** * * @author Ahri */ public class DlgIngresoRegistro extends javax.swing.JDialog { public static boolean isValidDate(String inDate) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); try { dateFormat.parse(inDate.trim()); } catch (Exception e) { return false; } return true; } /** * Creates new form DlgIngresoRegistro */ public static String fechaActual() { Date fecha = new Date(); SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/YYYY"); return formatoFecha.format(fecha); } public DlgIngresoRegistro(javax.swing.JDialog parent, boolean modal) { super(parent, modal); initComponents(); this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtId_registro = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); txtFechaAA = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); txtDescripcion = new javax.swing.JTextArea(); jLabel6 = new javax.swing.JLabel(); txtStock = new javax.swing.JTextField(); txtFechaMM = new javax.swing.JTextField(); txtFechaDD = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); btnGuardar = new javax.swing.JButton(); btnLimpiar = new javax.swing.JButton(); btnVolver = new javax.swing.JButton(); btnFechaActual = new javax.swing.JButton(); cmbMedida = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setForeground(new java.awt.Color(51, 51, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Ingreso de los registros"); jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jLabel2.setText("ID del registro"); txtId_registro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtId_registroActionPerformed(evt); } }); jLabel3.setText("Medicamento"); jLabel4.setText("Fecha"); txtFechaAA.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtFechaAA.setText("AAAA"); txtFechaAA.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFechaAAFocusGained(evt); } }); txtFechaAA.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtFechaAAMouseClicked(evt); } }); txtFechaAA.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtFechaAAActionPerformed(evt); } }); jLabel5.setText("Medida"); txtDescripcion.setColumns(20); txtDescripcion.setRows(5); jScrollPane1.setViewportView(txtDescripcion); jLabel6.setText("Stock"); txtFechaMM.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtFechaMM.setText("MM"); txtFechaMM.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFechaMMFocusGained(evt); } }); txtFechaMM.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtFechaMMMouseClicked(evt); } }); txtFechaDD.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtFechaDD.setText("DD"); txtFechaDD.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFechaDDFocusGained(evt); } }); txtFechaDD.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtFechaDDMouseClicked(evt); } }); jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("/"); jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("/"); btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1446613046_floppy.png"))); // NOI18N btnGuardar.setToolTipText("Guardar registro"); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } }); btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1446609695_edit-clear.png"))); // NOI18N btnLimpiar.setToolTipText("Limpiar casillas de texto"); btnLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLimpiarActionPerformed(evt); } }); btnVolver.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1446609011_go-back.png"))); // NOI18N btnVolver.setToolTipText("Volver"); btnVolver.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnVolverMouseClicked(evt); } }); btnFechaActual.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/1447540901_calendar.png"))); // NOI18N btnFechaActual.setToolTipText("Insertar fecha actual"); btnFechaActual.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFechaActualActionPerformed(evt); } }); cmbMedida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione medida del medicamento", "sin medida", "100ml", "125ml", "250ml", "500ml", "1000ml" })); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(btnGuardar) .addGap(18, 18, 18) .addComponent(btnLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnVolver, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtId_registro) .addComponent(jScrollPane1) .addComponent(txtStock, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtFechaAA, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(txtFechaMM, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE) .addComponent(txtFechaDD, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnFechaActual, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(cmbMedida, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(45, 45, 45)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtId_registro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(49, 49, 49) .addComponent(jLabel3)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtFechaMM) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnFechaActual) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtFechaDD, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtFechaAA) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel7) .addComponent(jLabel8)))) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(cmbMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnVolver, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnLimpiar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(26, 26, 26)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtId_registroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtId_registroActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtId_registroActionPerformed private void txtFechaAAMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaAAMouseClicked // TODO add your handling code here: txtFechaAA.setText(null); String vacio = ""; if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaAAMouseClicked private void txtFechaMMMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaMMMouseClicked // TODO add your handling code here: txtFechaMM.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaMMMouseClicked private void txtFechaDDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaDDMouseClicked // TODO add your handling code here: txtFechaDD.setText(null); txtFechaDD.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } }//GEN-LAST:event_txtFechaDDMouseClicked private void btnVolverMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVolverMouseClicked // TODO add your handling code here: this.setVisible(false); }//GEN-LAST:event_btnVolverMouseClicked private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed // TODO add your handling code here: Registro registro = new Registro(); Registro_servicio rs = new Registro_servicio(); Conexion con = new Conexion(); Connection reg = con.obtenerConexion(); int id_registro, stock, aux = 0; String nombre, fecha, medida; id_registro = Integer.parseInt(txtId_registro.getText()); nombre = txtDescripcion.getText(); fecha = txtFechaAA.getText() + "-" + txtFechaMM.getText() + "-" + txtFechaDD.getText(); medida = cmbMedida.getSelectedItem().toString(); stock = Integer.parseInt(txtStock.getText()); registro = new Registro(id_registro, nombre, fecha, medida, stock); String aux5 = txtId_registro.getText().trim(); String aux2 = txtDescripcion.getText().trim(); String ano = txtFechaAA.getText().trim(); String mes = txtFechaMM.getText().trim(); String dia = txtFechaDD.getText().trim(); String aux13 = cmbMedida.getSelectedItem().toString(); String aux15 = txtStock.getText(); String ano1 = txtFechaAA.getText(); String mes1 = txtFechaMM.getText(); String dia1= txtFechaDD.getText(); String fechas = ano1+'-'+mes1+'-'+dia1; if (isValidDate(fechas)) { if(aux13== "Seleccione medida del medicamento"||aux5.length()== 0||aux2.length()== 0||ano.length()== 0||dia.length()== 0||mes.length()== 0||aux15.length()== 0){ JOptionPane.showMessageDialog(this,"Cada campo debe ser llenado","Error",JOptionPane.ERROR_MESSAGE); }else{ try { PreparedStatement consulta = reg.prepareStatement("SELECT * FROM registro"); ResultSet resultado = consulta.executeQuery(); while (resultado.next()) { if (resultado.getInt("id_registro") == id_registro) { aux=1; } else { if (resultado.getString("nombre").equals(nombre) && resultado.getString("medida").equals(medida)) { aux = 2; } } } } catch (SQLException ex) { } if (aux == 0) { rs.guardar(reg, registro); JOptionPane.showMessageDialog(this, "Se guardo su registro correctamente"); this.setVisible(false); } else { if(aux==2){ JOptionPane.showMessageDialog(this, "Ya se encuentra el NOMBRE y MEDIDA del medicamento registrado en nuestras bases de datos"); cmbMedida.setSelectedItem("Seleccione medida del medicamento"); cmbMedida.requestFocus();}else{ if(aux==1){ JOptionPane.showMessageDialog(this, "Ya se encuentra el CODIGO del medicamento registrado en nuestras bases de datos"); txtId_registro.setText(null); txtId_registro.requestFocus(); } } } }}else{JOptionPane.showMessageDialog(this,"Error en la fecha","Error",JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnGuardarActionPerformed private void txtFechaAAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFechaAAActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtFechaAAActionPerformed private void txtFechaAAFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFechaAAFocusGained // TODO add your handling code here: txtFechaAA.setText(null); String vacio = ""; if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaAAFocusGained private void txtFechaMMFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFechaMMFocusGained // TODO add your handling code here: txtFechaMM.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaDD.getText().equals(vacio)) { txtFechaDD.setText("DD"); } }//GEN-LAST:event_txtFechaMMFocusGained private void txtFechaDDFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFechaDDFocusGained // TODO add your handling code here: txtFechaDD.setText(null); String vacio = ""; if (txtFechaAA.getText().equals(vacio)) { txtFechaAA.setText("AAAA"); } if (txtFechaMM.getText().equals(vacio)) { txtFechaMM.setText("MM"); } }//GEN-LAST:event_txtFechaDDFocusGained private void btnFechaActualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFechaActualActionPerformed // TODO add your handling code here: String[] fecha = fechaActual().split("/"); txtFechaDD.setText(fecha[0]); txtFechaMM.setText(fecha[1]); txtFechaAA.setText(fecha[2]); }//GEN-LAST:event_btnFechaActualActionPerformed private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed // TODO add your handling code here: txtId_registro.setText(null); txtDescripcion.setText(null); cmbMedida.setSelectedItem("Seleccione medida del medicamento"); txtStock.setText(null); txtId_registro.requestFocus(); }//GEN-LAST:event_btnLimpiarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DlgIngresoRegistro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { DlgIngresoRegistro dialog = new DlgIngresoRegistro(new javax.swing.JDialog(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnFechaActual; private javax.swing.JButton btnGuardar; private javax.swing.JButton btnLimpiar; private javax.swing.JButton btnVolver; private javax.swing.JComboBox cmbMedida; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea txtDescripcion; private javax.swing.JTextField txtFechaAA; private javax.swing.JTextField txtFechaDD; private javax.swing.JTextField txtFechaMM; private javax.swing.JTextField txtId_registro; private javax.swing.JTextField txtStock; // End of variables declaration//GEN-END:variables }
26,169
0.641828
0.631549
539
47.551022
37.556866
179
false
false
0
0
0
0
0
0
0.686456
false
false
13
5bdc91c71ecd8c2a056cdb09ecdeea08a4d0ff50
33,913,061,811,889
5d1c10b92b0807f690b1eb5faf307b0668294a97
/lecture09/src/main/java/ru/atom/lecture09/reflection/FirstServiceImplementation.java
90f42f409d1a566f3d502605e6ef4b6e21e99ca7
[ "MIT" ]
permissive
elBroom/atom
https://github.com/elBroom/atom
e1db9c1cfc319adfbdc1631d8498ea59177ff44a
796dc5e90183ac3336f45019fe78360f9054683c
refs/heads/master
2021-01-20T13:55:24.776000
2017-05-18T17:19:48
2017-05-18T17:19:48
82,720,540
2
0
null
true
2017-02-21T19:50:00
2017-02-21T19:50:00
2017-02-21T19:11:04
2017-02-21T17:47:33
37,993
0
0
0
null
null
null
package ru.atom.lecture09.reflection; /** * @author Alpi * @since 13.11.16 */ public class FirstServiceImplementation implements Service { @Override public void serve() { System.out.println("First service serve()"); } }
UTF-8
Java
244
java
FirstServiceImplementation.java
Java
[ { "context": "kage ru.atom.lecture09.reflection;\n\n/**\n * @author Alpi\n * @since 13.11.16\n */\npublic class FirstServiceI", "end": 58, "score": 0.9943981170654297, "start": 54, "tag": "NAME", "value": "Alpi" } ]
null
[]
package ru.atom.lecture09.reflection; /** * @author Alpi * @since 13.11.16 */ public class FirstServiceImplementation implements Service { @Override public void serve() { System.out.println("First service serve()"); } }
244
0.668033
0.635246
12
19.333334
19.524914
60
false
false
0
0
0
0
0
0
0.166667
false
false
13
2e12af61d0542babd93ea9e16e3bc4cac1ea7004
20,959,440,459,241
838f326f56ffe6e49cb7a16cd4a5ec6415054cf5
/src/test/java/libai/common/MatrixTest.java
99088b55cc9127ffe9bafbeb4c0c24be83a609f4
[]
no_license
kronenthaler/libai
https://github.com/kronenthaler/libai
1dc611e510d87bb16bca7771f2a6cb2c9f961b52
4e64006e4084e19798c2a1f1becb491a0d90735f
refs/heads/master
2022-10-21T02:01:12.190000
2021-10-12T11:30:01
2021-10-12T11:30:01
7,753,784
2
4
null
false
2022-10-14T14:19:10
2013-01-22T14:30:50
2021-10-12T11:30:04
2022-10-11T16:39:33
2,281
4
1
9
Java
false
false
/* * MIT License * * Copyright (c) 2016 Federico Vera <https://github.com/dktcoding> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package libai.common; import libai.common.functions.Function; import libai.common.matrix.Column; import libai.common.matrix.Matrix; import libai.common.matrix.Row; import org.junit.Test; import java.util.HashMap; import java.util.Random; import static org.junit.Assert.*; /** * @author Federico Vera {@literal <dktcoding [at] gmail>} */ public class MatrixTest { private static final double DELTA = 1e-12; public final double[] a1_data = { -0.007765831782573, -0.008486990926655, -0.009829972068673, 0.000304058679693, -0.002138442736117, 0.007523070921871, 0.005449501255788, 0.005930977488527, 0.005607489427692, 0.002720446955797, }; public final double[] b1_data = { -0.007765831782573, -0.008486990926655, -0.009829972068673, 0.000304058679693, -0.002138442736117, 0.007523070921871, 0.005449501255788, 0.005930977488527, 0.005607489427692, 0.002720446955797, }; public final double[] d1_data = { 0.000154421532520, -0.000014637731259, -0.000078861505907, 0.000023086622987, }; public final double[] a2_data = { -0.007253997338875, -0.009757740181475, 0.009202997305386, 0.009821458200041, 0.006434371877310, 0.008282702832958, -0.008951885947104, -0.005934105911485, -0.006161133826338, -0.002859944646273, }; public final double[] b2_data = { -0.007253997338875, -0.009757740181475, 0.009202997305386, 0.009821458200041, 0.006434371877310, 0.008282702832958, -0.008951885947104, -0.005934105911485, -0.006161133826338, -0.002859944646273, }; public final double[] d2_data = {0.000600483207479}; public double[] a3_data = { 0.008836540313295, 0.005681073763455, 0.006258204252537, 0.008306752574195, 0.000227322631636, -0.002351919190952, -0.002525625167333, -0.006263386710295, 0.002164190369792, -0.006667604294500, }; public double[] b3_data = { 0.001482773049231, -0.001347142606673, 0.007705866269837, 0.009591078927415, -0.000875775794850, -0.007544329405404, -0.005619909996736, -0.001928699595623, -0.006332203264881, -0.001393287402837, }; public double result = 1.7274931467510147E-4; @Test(expected = IllegalArgumentException.class) public void testConstructorFail1() { Matrix m = new Matrix(-5, 5, false); assertNull(m); } @Test(expected = IllegalArgumentException.class) public void testConstructorFail2() { Matrix m = new Matrix(5, -5, false); assertNull(m); } @Test(expected = IllegalArgumentException.class) public void testConstructorFail4() { Matrix m = new Matrix(5, 5, null); assertNull(m); } @Test(expected = NullPointerException.class) public void testConstructorCopyFail() { Matrix m = new Matrix(null); assertNull(m); } @Test(expected = IllegalArgumentException.class) public void testConstructorFail5() { Matrix m = new Matrix(5, 5, new double[5 * 4]); assertNull(m); } @Test public void testConstructorNotIdentity1() { Matrix m = new Matrix(5, 5, false); for (int i = 0; i < m.getRows(); i++) { assertArrayEquals(new double[]{0, 0, 0, 0, 0}, m.getRow(i), DELTA); } } @Test public void testConstructorNotIdentity2() { Matrix m = new Matrix(15, 5, false); for (int i = 0; i < m.getRows(); i++) { for (int j = 0; j < m.getColumns(); j++) { assertEquals(0, m.position(i, j), DELTA); } } } @Test public void testConstructorIdentity1() { Matrix m = new Matrix(5, 5, true); for (int i = 0; i < m.getRows(); i++) { double[] test = new double[5]; test[i] = 1; assertArrayEquals(test, m.getRow(i), DELTA); } } @Test public void testConstructorIdentity2() { Matrix m = new Matrix(15, 5, true); for (int i = 0; i < m.getColumns(); i++) { double[] test = new double[5]; test[i] = 1; assertArrayEquals(test, m.getRow(i), DELTA); } } @Test public void testConstructorIdentity3() { Matrix m = new Matrix(5, 15, true); for (int i = 0; i < m.getRows(); i++) { double[] test = new double[15]; test[i] = 1; assertArrayEquals(test, m.getRow(i), DELTA); } } @Test public void testMatrixRandom() { Matrix a = Matrix.random(50, 100, true); Matrix b = Matrix.random(50, 100, false); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testMatrixRandom2() { Random rand1 = new Random(0); Random rand2 = new Random(0); Matrix a = Matrix.random(50, 100, true, rand1); Matrix b = Matrix.random(50, 100, false, rand2); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testMatrixRandom3() { Random rand = new Random(0); Matrix a = Matrix.random(50, 100, true, rand); Matrix b = Matrix.random(50, 100, true, rand); assertNotEquals(a, b); a = Matrix.random(50, 100, true, new Random(0)); b = Matrix.random(50, 100, true, new Random(0)); assertEquals(a, b); } @Test public void testRandomIntInt() { Matrix a = Matrix.random(50, 100); Matrix b = Matrix.random(50, 100); assertNotEquals(a, b); } @Test public void testMultiplyDoubleMatrix() { Matrix a = Matrix.random(10, 40); Matrix b = new Matrix(10, 40); Matrix c = new Matrix(10, 40); a.multiply(0, b); assertNotEquals(a, b); assertEquals(b, c); a.multiply(1, b); assertEquals(a, b); a.multiply(2, b); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { assertEquals(2 * a.position(i, j), b.position(i, j), DELTA); } } } @Test public void testMultiplyMatrixMatrix() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); Matrix c = new Matrix(10, 10, true); a.multiply(b, c); assertEquals(a, b); assertEquals(a, c); a.multiply(a, a); assertEquals(a, a); } @Test public void testMultiplyMatrixMatrix1() { Matrix a = new Matrix(10, 10, true); Matrix b = Matrix.random(10, 40); Matrix c = new Matrix(10, 40); a.multiply(b, c); assertEquals(b, c); assertNotEquals(a, c); } @Test public void testMultiplyMatrixMatrix2() { //d1_data was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Matrix(2, 5, a1_data); Matrix b = new Matrix(5, 2, b1_data); Matrix c = new Matrix(2, 2); Matrix d = new Matrix(2, 2, d1_data); a.multiply(b, c); assertEquals(c, d); } @Test public void testMultiplyMatrixMatrix3() { //d2_data was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Row a = new Row(10, a2_data); Column b = new Column(10, b2_data); Matrix c = new Column(1); Matrix d = new Column(1, d2_data); a.multiply(b, c); assertEquals(c, d); } @Test public void testApply() { Function f = new Function() { @Override public double eval(double x) { return 0; } @Override public Function getDerivate() { return null; } }; Matrix a = Matrix.random(10, 10); Matrix b = new Matrix(10, 10); Matrix c = new Matrix(10, 10); a.apply(f, b); assertEquals(c, b); } @Test public void testApply1() { Function f = new Function() { @Override public double eval(double x) { return x; } @Override public Function getDerivate() { return null; } }; Matrix a = Matrix.random(10, 10); Matrix b = new Matrix(10, 10); a.apply(f, b); assertEquals(a, b); } @Test public void testApply2() { Function f = new Function() { @Override public double eval(double x) { return x == 1 ? 0 : 1; } @Override public Function getDerivate() { return null; } }; Matrix a = new Matrix(5, 5, true); Matrix b = new Matrix(5, 5); a.apply(f, b); assertArrayEquals(new double[]{0, 1, 1, 1, 1}, b.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 1, 1, 1}, b.getRow(1), DELTA); assertArrayEquals(new double[]{1, 1, 0, 1, 1}, b.getRow(2), DELTA); assertArrayEquals(new double[]{1, 1, 1, 0, 1}, b.getRow(3), DELTA); assertArrayEquals(new double[]{1, 1, 1, 1, 0}, b.getRow(4), DELTA); } @Test public void testCopy() { Matrix a = Matrix.random(5, 10); Matrix b = new Matrix(5, 10); assertNotEquals(a, b); a.copy(b); assertEquals(a, b); a.position(0, 0, 0); assertNotEquals(a, b); } @Test public void testCopy1() { Matrix a = Matrix.random(10, 5); Matrix b = new Matrix(10, 5); assertNotEquals(a, b); a.copy(b); assertEquals(a, b); a.position(0, 0, 0); assertNotEquals(a, b); } @Test public void testTransposeMatrix() { Matrix a = new Matrix(5, 15, true); Matrix b = new Matrix(15, 5, true); a.transpose(b); assertNotEquals(a, b); assertEquals(a, b.transpose()); assertEquals(a.getColumns(), b.getRows()); assertEquals(a.getRows(), b.getColumns()); } @Test public void testTranspose() { Matrix a = new Matrix(5, 5, true); Matrix b = new Matrix(5, 5, true); Matrix c = new Matrix(5, 5, true); a.transpose(b); assertEquals(a, b); a.fill(); assertNotEquals(a, b); a.transpose(b); b.transpose(c); assertEquals(a, c); assertNotEquals(a, b); } @Test public void testSetValue() { Matrix a = Matrix.random(10, 15); Matrix b = Matrix.random(10, 15); assertNotEquals(a, b); a.setValue(Math.PI); b.setValue(Math.PI); assertEquals(a, b); a.setValue(0); assertEquals(a, new Matrix(10, 15)); } @Test public void testIncrement() { Random rand = new Random(); Matrix m = new Matrix(15, 5, false); m.fill(true, rand); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { double inc = rand.nextDouble() * 2 - 1; double prev = m.position(i, j); m.increment(i, j, inc); assertEquals(prev, m.position(i, j) - inc, DELTA); assertNotEquals(prev, m.position(i, j), DELTA); } } } @Test public void testScale() { Random rand = new Random(); Matrix m = new Matrix(15, 5, false); m.fill(true, rand); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { double inc = rand.nextDouble() * 2 - 1; double prev = m.position(i, j); m.scale(i, j, inc); assertEquals(prev, m.position(i, j) / inc, DELTA); assertNotEquals(prev, m.position(i, j), DELTA); } } } @Test public void testSwap() { Matrix m = new Matrix(5, 5, true); double[] prev_row = m.getRow(3); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, prev_row, DELTA); m.swap(0, 3); assertArrayEquals(prev_row, m.getRow(0), DELTA); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, m.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 0, 0, 0}, m.getRow(3), DELTA); } @Test public void testSwap1() { Matrix m = new Matrix(15, 5, true); double[] prev_row = m.getRow(3); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, prev_row, DELTA); m.swap(0, 3); assertArrayEquals(prev_row, m.getRow(0), DELTA); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, m.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 0, 0, 0}, m.getRow(3), DELTA); } @Test public void testSwap2() { Matrix m = new Matrix(5, 10, true); double[] prev_row = m.getRow(3); assertArrayEquals(new double[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, prev_row, DELTA); m.swap(0, 3); assertArrayEquals(prev_row, m.getRow(0), DELTA); assertArrayEquals(new double[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, m.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, m.getRow(3), DELTA); } @Test public void testEquals() { Matrix a = Matrix.random(10, 10); Matrix b = new Matrix(10, 10); Row c = new Row(10); a.copy(b); assertEquals(a, b); b.position(1, 1, 1); assertNotEquals(a, b); assertNotEquals(a, c); assertNotEquals(b, c); assertEquals(a, a); assertEquals(b, b); assertEquals(c, c); } @Test public void testEquals1() { Matrix a = new Column(10); Matrix b = new Row(10); assertNotEquals(a, b); b = b.transpose(); assertEquals(a, b); } @Test public void testEquals2() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); assertEquals(a, b); b = b.transpose(); assertEquals(a, b); } @Test public void testEquals3() { Matrix a = new Matrix(10, 10, true); assertNotEquals(a, null); assertNotEquals(a, new Object()); } @Test public void testGetRows() { Matrix m = new Matrix(20, 10); assertEquals(20, m.getRows()); } @Test public void testGetColumns() { Matrix m = new Matrix(20, 10); assertEquals(10, m.getColumns()); } @Test public void testPosition() { Matrix a = new Matrix(5, 5); Matrix b = new Matrix(5, 5, true); assertNotEquals(a, b); a.position(0, 0, 1); a.position(1, 1, 1); a.position(2, 2, 1); a.position(3, 3, 1); a.position(4, 4, 1); assertEquals(a, b); } @Test public void testPosition1() { Matrix a = Matrix.random(2, 5); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getRow(0), DELTA); a.position(0, 0, 1); a.position(0, 1, 2); a.position(0, 2, 3); a.position(0, 3, 4); a.position(0, 4, 5); assertArrayEquals(new double[]{1, 2, 3, 4, 5}, a.getRow(0), DELTA); } @Test public void testPosition2() { Matrix a = Matrix.random(5, 1); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getCol(0), DELTA); a.position(0, 0, 1); a.position(1, 0, 2); a.position(2, 0, 3); a.position(3, 0, 4); a.position(4, 0, 5); assertArrayEquals(new double[]{1, 2, 3, 4, 5}, a.getCol(0), DELTA); } @Test public void testPosition3() { Matrix a = new Matrix(10, 10, true); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { assertEquals(i == j ? 1 : 0, a.position(i, j), DELTA); } } } @Test public void testPosition4() { Matrix a = Matrix.random(5, 1); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getCol(0), DELTA); a.position(0, 0, 1); a.position(1, 0, 2); a.position(2, 0, 3); a.position(3, 0, 4); a.position(4, 0, 5); assertEquals(1, a.position(0, 0), DELTA); assertEquals(2, a.position(1, 0), DELTA); assertEquals(3, a.position(2, 0), DELTA); assertEquals(4, a.position(3, 0), DELTA); assertEquals(5, a.position(4, 0), DELTA); } @Test public void testPosition5() { Matrix a = Matrix.random(1, 5); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getRow(0), DELTA); a.position(0, 0, 1); a.position(0, 1, 2); a.position(0, 2, 3); a.position(0, 3, 4); a.position(0, 4, 5); assertEquals(1, a.position(0, 0), DELTA); assertEquals(2, a.position(0, 1), DELTA); assertEquals(3, a.position(0, 2), DELTA); assertEquals(4, a.position(0, 3), DELTA); assertEquals(5, a.position(0, 4), DELTA); } @Test public void testAdd() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); assertEquals(a, b); a.add(a, b); assertNotEquals(a, b); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { assertEquals(i == j ? 2 : 0, b.position(i, j), DELTA); } } } @Test public void testAdd1() { Matrix a = Matrix.random(5, 15); Matrix b = new Matrix(5, 15, true); Matrix c = new Matrix(5, 15); a.add(b, c); assertNotEquals(a, b); assertNotEquals(b, c); assertNotEquals(a, c); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { double av = a.position(i, j); assertEquals(i == j ? av + 1 : av, c.position(i, j), DELTA); } } } @Test public void testSubtract() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); assertEquals(a, b); a.subtract(a, b); assertNotEquals(a, b); assertEquals(new Matrix(10, 10), b); } @Test public void testSubtract1() { Matrix a = Matrix.random(5, 15); Matrix b = new Matrix(5, 15, true); Matrix c = new Matrix(5, 15); a.subtract(b, c); assertNotEquals(a, b); assertNotEquals(b, c); assertNotEquals(a, c); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { double av = a.position(i, j); assertEquals(i == j ? av - 1 : av, c.position(i, j), DELTA); } } } @Test public void testFillBooleanRandom() { Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true); assertNotEquals(a, b); b.fill(true); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertTrue(hasNegativeB); hasNegativeA = false; hasNegativeB = false; a.fill(false); b.fill(false); assertNotEquals(a, b); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertFalse(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testFillBooleanRandom2() { Random rand1 = new Random(0); Random rand2 = new Random(0); Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true, rand1); assertNotEquals(a, b); b.fill(true, rand2); assertEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertTrue(hasNegativeB); hasNegativeA = false; hasNegativeB = false; a.fill(false, rand1); b.fill(false, rand2); assertEquals(a, b); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertFalse(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testFillBooleanRandom3() { Random rand = new Random(0); Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true, rand); assertNotEquals(a, b); b.fill(true, rand); assertNotEquals(a, b); } @Test public void testFillBooleanRandom4() { Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true); assertNotEquals(a, b); b.fill(true); assertNotEquals(a, b); } @Test public void testFill() { Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(); assertNotEquals(a, b); b.fill(); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertTrue(hasNegativeB); } @Test(expected = IllegalArgumentException.class) public void testDotProductError1() { Matrix a = new Matrix(2, 10, a3_data); assertNull(a); } @Test(expected = IllegalArgumentException.class) public void testDotProductError2() { Matrix b = new Matrix(10, 2, b3_data); assertNull(b); } @Test public void testDotProduct() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Row(10, a3_data); Matrix b = new Row(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testDotProduct1() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Column(10, a3_data); Matrix b = new Column(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testDotProduct2() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Row(10, a3_data); Matrix b = new Column(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testDotProduct3() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Column(10, a3_data); Matrix b = new Row(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testSetGetRow() { Matrix a = Matrix.random(3, 5); double[] row = new double[]{1, 2, 3, 4, 5}; assertArrayNotEquals(row, a.getRow(0), DELTA); assertArrayNotEquals(row, a.getRow(1), DELTA); assertArrayNotEquals(row, a.getRow(2), DELTA); a.setRow(2, row); assertArrayNotEquals(row, a.getRow(0), DELTA); assertArrayNotEquals(row, a.getRow(1), DELTA); assertArrayEquals(row, a.getRow(2), DELTA); } @Test public void testGetCol() { Matrix a = Matrix.random(10, 15); assertArrayEquals(a.getCol(12), a.transpose().getRow(12), DELTA); for (int i = 0; i < 10; i++) { a.position(i, 9, 0); } assertArrayEquals(new double[10], a.getCol(9), DELTA); for (int i = 0; i < 10; i++) { a.position(i, 3, i); } assertArrayEquals(new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, a.getCol(3), DELTA); } @Test public void testSubtractAndCopy() { Matrix a = Matrix.random(5, 10); Matrix b = Matrix.random(5, 10); Matrix c = Matrix.random(5, 10); Matrix d = Matrix.random(5, 10); assertNotEquals(a, d); a.subtractAndCopy(b, c, d); assertEquals(a, d); a.subtract(b, d); assertEquals(c, d); a.subtractAndCopy(a, b, c); assertEquals(a, c); assertEquals(new Matrix(5, 10), b); } @Test public void testMultiplyAndAdd() { Matrix a = Matrix.random(10, 20); Matrix b = Matrix.random(10, 20); Matrix c = new Matrix(10, 20); Matrix d = new Matrix(10, 20); assertNotEquals(a, b); assertNotEquals(a, c); a.multiplyAndAdd(0, b, c); assertEquals(b, c); double scale = Math.random(); a.multiply(scale, d); d.add(b, d); a.multiplyAndAdd(scale, b, c); assertEquals(c, d); } @Test public void testApplyInIdentity() { Function f = new Function() { @Override public double eval(double x) { return 0; } @Override public Function getDerivate() { return null; } }; Matrix a = Matrix.random(10, 10); Matrix b = new Column(10); b.applyInIdentity(f, a); for (int i = 0; i < a.getRows(); i++) { assertEquals(0, a.position(i, i), DELTA); } b.setValue(5); f = new Function() { @Override public double eval(double x) { return x; } @Override public Function getDerivate() { return null; } }; b.applyInIdentity(f, a); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { if (i == j) { assertEquals(5, a.position(i, j), DELTA); } else { assertNotEquals(5, a.position(i, j), DELTA); } } } } @Test(expected = IllegalArgumentException.class) public void testDotProductThisNotRow() { Matrix a = Matrix.random(2, 10); Matrix b = Matrix.random(1, 20); a.dotProduct(b); } @Test(expected = IllegalArgumentException.class) public void testDotProductThisNotColumn() { Matrix a = Matrix.random(10, 2); Matrix b = Matrix.random(1, 20); a.dotProduct(b); } @Test(expected = IllegalArgumentException.class) public void testDotProductOtherNotRow() { Matrix a = Matrix.random(1, 20); Matrix b = Matrix.random(2, 10); a.dotProduct(b); } @Test(expected = IllegalArgumentException.class) public void testDotProductOtherNotColumn() { Matrix a = Matrix.random(1, 20); Matrix b = Matrix.random(10, 2); a.dotProduct(b); } @Test public void testHashCode() { Matrix a = Matrix.random(10, 10); Matrix b = Matrix.random(10, 10); Matrix c = Matrix.random(10, 5); Matrix d = Matrix.random(5, 10); HashMap<Matrix, Matrix> map = new HashMap<>(4); map.put(a, a); map.put(b, b); map.put(c, c); map.put(d, d); assertTrue(a == map.get(a)); assertTrue(b == map.get(b)); assertTrue(c == map.get(c)); assertTrue(d == map.get(d)); } @Test public void testHashCode2() { Matrix a = Matrix.random(10, 10); assertEquals(a.hashCode(), a.hashCode()); Matrix b = new Matrix(10, 10); a.copy(b); assertEquals(a.hashCode(), b.hashCode()); b.position(0, 0, b.position(0, 0) + 1); assertNotEquals(a.hashCode(), b.hashCode()); } @Test public void testToString() { Matrix a = new Column(2); assertEquals("0.00000000 \n0.00000000 \n\n", a.toString()); a = new Row(2); assertEquals("0.00000000 0.00000000 \n\n", a.toString()); } private void assertArrayNotEquals(double[] a, double[] b, double DELTA) { try { assertArrayEquals(a, b, DELTA); throw new AssertionError("Both arrays are equal!"); } catch (AssertionError ignoreMe) { } } }
UTF-8
Java
25,988
java
MatrixTest.java
Java
[ { "context": "/*\n * MIT License\n *\n * Copyright (c) 2016 Federico Vera <https://github.com/dktcoding>\n *\n * Permission i", "end": 56, "score": 0.9998849034309387, "start": 43, "tag": "NAME", "value": "Federico Vera" }, { "context": "yright (c) 2016 Federico Vera <https://github....
null
[]
/* * MIT License * * Copyright (c) 2016 <NAME> <https://github.com/dktcoding> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package libai.common; import libai.common.functions.Function; import libai.common.matrix.Column; import libai.common.matrix.Matrix; import libai.common.matrix.Row; import org.junit.Test; import java.util.HashMap; import java.util.Random; import static org.junit.Assert.*; /** * @author <NAME> {@literal <dktcoding [at] gmail>} */ public class MatrixTest { private static final double DELTA = 1e-12; public final double[] a1_data = { -0.007765831782573, -0.008486990926655, -0.009829972068673, 0.000304058679693, -0.002138442736117, 0.007523070921871, 0.005449501255788, 0.005930977488527, 0.005607489427692, 0.002720446955797, }; public final double[] b1_data = { -0.007765831782573, -0.008486990926655, -0.009829972068673, 0.000304058679693, -0.002138442736117, 0.007523070921871, 0.005449501255788, 0.005930977488527, 0.005607489427692, 0.002720446955797, }; public final double[] d1_data = { 0.000154421532520, -0.000014637731259, -0.000078861505907, 0.000023086622987, }; public final double[] a2_data = { -0.007253997338875, -0.009757740181475, 0.009202997305386, 0.009821458200041, 0.006434371877310, 0.008282702832958, -0.008951885947104, -0.005934105911485, -0.006161133826338, -0.002859944646273, }; public final double[] b2_data = { -0.007253997338875, -0.009757740181475, 0.009202997305386, 0.009821458200041, 0.006434371877310, 0.008282702832958, -0.008951885947104, -0.005934105911485, -0.006161133826338, -0.002859944646273, }; public final double[] d2_data = {0.000600483207479}; public double[] a3_data = { 0.008836540313295, 0.005681073763455, 0.006258204252537, 0.008306752574195, 0.000227322631636, -0.002351919190952, -0.002525625167333, -0.006263386710295, 0.002164190369792, -0.006667604294500, }; public double[] b3_data = { 0.001482773049231, -0.001347142606673, 0.007705866269837, 0.009591078927415, -0.000875775794850, -0.007544329405404, -0.005619909996736, -0.001928699595623, -0.006332203264881, -0.001393287402837, }; public double result = 1.7274931467510147E-4; @Test(expected = IllegalArgumentException.class) public void testConstructorFail1() { Matrix m = new Matrix(-5, 5, false); assertNull(m); } @Test(expected = IllegalArgumentException.class) public void testConstructorFail2() { Matrix m = new Matrix(5, -5, false); assertNull(m); } @Test(expected = IllegalArgumentException.class) public void testConstructorFail4() { Matrix m = new Matrix(5, 5, null); assertNull(m); } @Test(expected = NullPointerException.class) public void testConstructorCopyFail() { Matrix m = new Matrix(null); assertNull(m); } @Test(expected = IllegalArgumentException.class) public void testConstructorFail5() { Matrix m = new Matrix(5, 5, new double[5 * 4]); assertNull(m); } @Test public void testConstructorNotIdentity1() { Matrix m = new Matrix(5, 5, false); for (int i = 0; i < m.getRows(); i++) { assertArrayEquals(new double[]{0, 0, 0, 0, 0}, m.getRow(i), DELTA); } } @Test public void testConstructorNotIdentity2() { Matrix m = new Matrix(15, 5, false); for (int i = 0; i < m.getRows(); i++) { for (int j = 0; j < m.getColumns(); j++) { assertEquals(0, m.position(i, j), DELTA); } } } @Test public void testConstructorIdentity1() { Matrix m = new Matrix(5, 5, true); for (int i = 0; i < m.getRows(); i++) { double[] test = new double[5]; test[i] = 1; assertArrayEquals(test, m.getRow(i), DELTA); } } @Test public void testConstructorIdentity2() { Matrix m = new Matrix(15, 5, true); for (int i = 0; i < m.getColumns(); i++) { double[] test = new double[5]; test[i] = 1; assertArrayEquals(test, m.getRow(i), DELTA); } } @Test public void testConstructorIdentity3() { Matrix m = new Matrix(5, 15, true); for (int i = 0; i < m.getRows(); i++) { double[] test = new double[15]; test[i] = 1; assertArrayEquals(test, m.getRow(i), DELTA); } } @Test public void testMatrixRandom() { Matrix a = Matrix.random(50, 100, true); Matrix b = Matrix.random(50, 100, false); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testMatrixRandom2() { Random rand1 = new Random(0); Random rand2 = new Random(0); Matrix a = Matrix.random(50, 100, true, rand1); Matrix b = Matrix.random(50, 100, false, rand2); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testMatrixRandom3() { Random rand = new Random(0); Matrix a = Matrix.random(50, 100, true, rand); Matrix b = Matrix.random(50, 100, true, rand); assertNotEquals(a, b); a = Matrix.random(50, 100, true, new Random(0)); b = Matrix.random(50, 100, true, new Random(0)); assertEquals(a, b); } @Test public void testRandomIntInt() { Matrix a = Matrix.random(50, 100); Matrix b = Matrix.random(50, 100); assertNotEquals(a, b); } @Test public void testMultiplyDoubleMatrix() { Matrix a = Matrix.random(10, 40); Matrix b = new Matrix(10, 40); Matrix c = new Matrix(10, 40); a.multiply(0, b); assertNotEquals(a, b); assertEquals(b, c); a.multiply(1, b); assertEquals(a, b); a.multiply(2, b); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { assertEquals(2 * a.position(i, j), b.position(i, j), DELTA); } } } @Test public void testMultiplyMatrixMatrix() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); Matrix c = new Matrix(10, 10, true); a.multiply(b, c); assertEquals(a, b); assertEquals(a, c); a.multiply(a, a); assertEquals(a, a); } @Test public void testMultiplyMatrixMatrix1() { Matrix a = new Matrix(10, 10, true); Matrix b = Matrix.random(10, 40); Matrix c = new Matrix(10, 40); a.multiply(b, c); assertEquals(b, c); assertNotEquals(a, c); } @Test public void testMultiplyMatrixMatrix2() { //d1_data was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Matrix(2, 5, a1_data); Matrix b = new Matrix(5, 2, b1_data); Matrix c = new Matrix(2, 2); Matrix d = new Matrix(2, 2, d1_data); a.multiply(b, c); assertEquals(c, d); } @Test public void testMultiplyMatrixMatrix3() { //d2_data was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Row a = new Row(10, a2_data); Column b = new Column(10, b2_data); Matrix c = new Column(1); Matrix d = new Column(1, d2_data); a.multiply(b, c); assertEquals(c, d); } @Test public void testApply() { Function f = new Function() { @Override public double eval(double x) { return 0; } @Override public Function getDerivate() { return null; } }; Matrix a = Matrix.random(10, 10); Matrix b = new Matrix(10, 10); Matrix c = new Matrix(10, 10); a.apply(f, b); assertEquals(c, b); } @Test public void testApply1() { Function f = new Function() { @Override public double eval(double x) { return x; } @Override public Function getDerivate() { return null; } }; Matrix a = Matrix.random(10, 10); Matrix b = new Matrix(10, 10); a.apply(f, b); assertEquals(a, b); } @Test public void testApply2() { Function f = new Function() { @Override public double eval(double x) { return x == 1 ? 0 : 1; } @Override public Function getDerivate() { return null; } }; Matrix a = new Matrix(5, 5, true); Matrix b = new Matrix(5, 5); a.apply(f, b); assertArrayEquals(new double[]{0, 1, 1, 1, 1}, b.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 1, 1, 1}, b.getRow(1), DELTA); assertArrayEquals(new double[]{1, 1, 0, 1, 1}, b.getRow(2), DELTA); assertArrayEquals(new double[]{1, 1, 1, 0, 1}, b.getRow(3), DELTA); assertArrayEquals(new double[]{1, 1, 1, 1, 0}, b.getRow(4), DELTA); } @Test public void testCopy() { Matrix a = Matrix.random(5, 10); Matrix b = new Matrix(5, 10); assertNotEquals(a, b); a.copy(b); assertEquals(a, b); a.position(0, 0, 0); assertNotEquals(a, b); } @Test public void testCopy1() { Matrix a = Matrix.random(10, 5); Matrix b = new Matrix(10, 5); assertNotEquals(a, b); a.copy(b); assertEquals(a, b); a.position(0, 0, 0); assertNotEquals(a, b); } @Test public void testTransposeMatrix() { Matrix a = new Matrix(5, 15, true); Matrix b = new Matrix(15, 5, true); a.transpose(b); assertNotEquals(a, b); assertEquals(a, b.transpose()); assertEquals(a.getColumns(), b.getRows()); assertEquals(a.getRows(), b.getColumns()); } @Test public void testTranspose() { Matrix a = new Matrix(5, 5, true); Matrix b = new Matrix(5, 5, true); Matrix c = new Matrix(5, 5, true); a.transpose(b); assertEquals(a, b); a.fill(); assertNotEquals(a, b); a.transpose(b); b.transpose(c); assertEquals(a, c); assertNotEquals(a, b); } @Test public void testSetValue() { Matrix a = Matrix.random(10, 15); Matrix b = Matrix.random(10, 15); assertNotEquals(a, b); a.setValue(Math.PI); b.setValue(Math.PI); assertEquals(a, b); a.setValue(0); assertEquals(a, new Matrix(10, 15)); } @Test public void testIncrement() { Random rand = new Random(); Matrix m = new Matrix(15, 5, false); m.fill(true, rand); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { double inc = rand.nextDouble() * 2 - 1; double prev = m.position(i, j); m.increment(i, j, inc); assertEquals(prev, m.position(i, j) - inc, DELTA); assertNotEquals(prev, m.position(i, j), DELTA); } } } @Test public void testScale() { Random rand = new Random(); Matrix m = new Matrix(15, 5, false); m.fill(true, rand); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { double inc = rand.nextDouble() * 2 - 1; double prev = m.position(i, j); m.scale(i, j, inc); assertEquals(prev, m.position(i, j) / inc, DELTA); assertNotEquals(prev, m.position(i, j), DELTA); } } } @Test public void testSwap() { Matrix m = new Matrix(5, 5, true); double[] prev_row = m.getRow(3); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, prev_row, DELTA); m.swap(0, 3); assertArrayEquals(prev_row, m.getRow(0), DELTA); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, m.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 0, 0, 0}, m.getRow(3), DELTA); } @Test public void testSwap1() { Matrix m = new Matrix(15, 5, true); double[] prev_row = m.getRow(3); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, prev_row, DELTA); m.swap(0, 3); assertArrayEquals(prev_row, m.getRow(0), DELTA); assertArrayEquals(new double[]{0, 0, 0, 1, 0}, m.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 0, 0, 0}, m.getRow(3), DELTA); } @Test public void testSwap2() { Matrix m = new Matrix(5, 10, true); double[] prev_row = m.getRow(3); assertArrayEquals(new double[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, prev_row, DELTA); m.swap(0, 3); assertArrayEquals(prev_row, m.getRow(0), DELTA); assertArrayEquals(new double[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, m.getRow(0), DELTA); assertArrayEquals(new double[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, m.getRow(3), DELTA); } @Test public void testEquals() { Matrix a = Matrix.random(10, 10); Matrix b = new Matrix(10, 10); Row c = new Row(10); a.copy(b); assertEquals(a, b); b.position(1, 1, 1); assertNotEquals(a, b); assertNotEquals(a, c); assertNotEquals(b, c); assertEquals(a, a); assertEquals(b, b); assertEquals(c, c); } @Test public void testEquals1() { Matrix a = new Column(10); Matrix b = new Row(10); assertNotEquals(a, b); b = b.transpose(); assertEquals(a, b); } @Test public void testEquals2() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); assertEquals(a, b); b = b.transpose(); assertEquals(a, b); } @Test public void testEquals3() { Matrix a = new Matrix(10, 10, true); assertNotEquals(a, null); assertNotEquals(a, new Object()); } @Test public void testGetRows() { Matrix m = new Matrix(20, 10); assertEquals(20, m.getRows()); } @Test public void testGetColumns() { Matrix m = new Matrix(20, 10); assertEquals(10, m.getColumns()); } @Test public void testPosition() { Matrix a = new Matrix(5, 5); Matrix b = new Matrix(5, 5, true); assertNotEquals(a, b); a.position(0, 0, 1); a.position(1, 1, 1); a.position(2, 2, 1); a.position(3, 3, 1); a.position(4, 4, 1); assertEquals(a, b); } @Test public void testPosition1() { Matrix a = Matrix.random(2, 5); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getRow(0), DELTA); a.position(0, 0, 1); a.position(0, 1, 2); a.position(0, 2, 3); a.position(0, 3, 4); a.position(0, 4, 5); assertArrayEquals(new double[]{1, 2, 3, 4, 5}, a.getRow(0), DELTA); } @Test public void testPosition2() { Matrix a = Matrix.random(5, 1); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getCol(0), DELTA); a.position(0, 0, 1); a.position(1, 0, 2); a.position(2, 0, 3); a.position(3, 0, 4); a.position(4, 0, 5); assertArrayEquals(new double[]{1, 2, 3, 4, 5}, a.getCol(0), DELTA); } @Test public void testPosition3() { Matrix a = new Matrix(10, 10, true); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { assertEquals(i == j ? 1 : 0, a.position(i, j), DELTA); } } } @Test public void testPosition4() { Matrix a = Matrix.random(5, 1); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getCol(0), DELTA); a.position(0, 0, 1); a.position(1, 0, 2); a.position(2, 0, 3); a.position(3, 0, 4); a.position(4, 0, 5); assertEquals(1, a.position(0, 0), DELTA); assertEquals(2, a.position(1, 0), DELTA); assertEquals(3, a.position(2, 0), DELTA); assertEquals(4, a.position(3, 0), DELTA); assertEquals(5, a.position(4, 0), DELTA); } @Test public void testPosition5() { Matrix a = Matrix.random(1, 5); assertArrayNotEquals(new double[]{1, 2, 3, 4, 5}, a.getRow(0), DELTA); a.position(0, 0, 1); a.position(0, 1, 2); a.position(0, 2, 3); a.position(0, 3, 4); a.position(0, 4, 5); assertEquals(1, a.position(0, 0), DELTA); assertEquals(2, a.position(0, 1), DELTA); assertEquals(3, a.position(0, 2), DELTA); assertEquals(4, a.position(0, 3), DELTA); assertEquals(5, a.position(0, 4), DELTA); } @Test public void testAdd() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); assertEquals(a, b); a.add(a, b); assertNotEquals(a, b); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { assertEquals(i == j ? 2 : 0, b.position(i, j), DELTA); } } } @Test public void testAdd1() { Matrix a = Matrix.random(5, 15); Matrix b = new Matrix(5, 15, true); Matrix c = new Matrix(5, 15); a.add(b, c); assertNotEquals(a, b); assertNotEquals(b, c); assertNotEquals(a, c); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { double av = a.position(i, j); assertEquals(i == j ? av + 1 : av, c.position(i, j), DELTA); } } } @Test public void testSubtract() { Matrix a = new Matrix(10, 10, true); Matrix b = new Matrix(10, 10, true); assertEquals(a, b); a.subtract(a, b); assertNotEquals(a, b); assertEquals(new Matrix(10, 10), b); } @Test public void testSubtract1() { Matrix a = Matrix.random(5, 15); Matrix b = new Matrix(5, 15, true); Matrix c = new Matrix(5, 15); a.subtract(b, c); assertNotEquals(a, b); assertNotEquals(b, c); assertNotEquals(a, c); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { double av = a.position(i, j); assertEquals(i == j ? av - 1 : av, c.position(i, j), DELTA); } } } @Test public void testFillBooleanRandom() { Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true); assertNotEquals(a, b); b.fill(true); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertTrue(hasNegativeB); hasNegativeA = false; hasNegativeB = false; a.fill(false); b.fill(false); assertNotEquals(a, b); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertFalse(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testFillBooleanRandom2() { Random rand1 = new Random(0); Random rand2 = new Random(0); Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true, rand1); assertNotEquals(a, b); b.fill(true, rand2); assertEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertTrue(hasNegativeB); hasNegativeA = false; hasNegativeB = false; a.fill(false, rand1); b.fill(false, rand2); assertEquals(a, b); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertFalse(hasNegativeA); assertFalse(hasNegativeB); } @Test public void testFillBooleanRandom3() { Random rand = new Random(0); Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true, rand); assertNotEquals(a, b); b.fill(true, rand); assertNotEquals(a, b); } @Test public void testFillBooleanRandom4() { Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(true); assertNotEquals(a, b); b.fill(true); assertNotEquals(a, b); } @Test public void testFill() { Matrix a = new Matrix(5, 10); Matrix b = new Matrix(5, 10); assertEquals(a, b); a.fill(); assertNotEquals(a, b); b.fill(); assertNotEquals(a, b); boolean hasNegativeA = false; boolean hasNegativeB = false; for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { hasNegativeA |= a.position(i, j) < 0; hasNegativeB |= b.position(i, j) < 0; } } assertTrue(hasNegativeA); assertTrue(hasNegativeB); } @Test(expected = IllegalArgumentException.class) public void testDotProductError1() { Matrix a = new Matrix(2, 10, a3_data); assertNull(a); } @Test(expected = IllegalArgumentException.class) public void testDotProductError2() { Matrix b = new Matrix(10, 2, b3_data); assertNull(b); } @Test public void testDotProduct() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Row(10, a3_data); Matrix b = new Row(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testDotProduct1() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Column(10, a3_data); Matrix b = new Column(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testDotProduct2() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Row(10, a3_data); Matrix b = new Column(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testDotProduct3() { //product was calculated with GNU-Octave 4.0.2 (x86_64-pc-linux-gnu) Matrix a = new Column(10, a3_data); Matrix b = new Row(10, b3_data); double product = a.dotProduct(b); assertEquals(result, product, DELTA); } @Test public void testSetGetRow() { Matrix a = Matrix.random(3, 5); double[] row = new double[]{1, 2, 3, 4, 5}; assertArrayNotEquals(row, a.getRow(0), DELTA); assertArrayNotEquals(row, a.getRow(1), DELTA); assertArrayNotEquals(row, a.getRow(2), DELTA); a.setRow(2, row); assertArrayNotEquals(row, a.getRow(0), DELTA); assertArrayNotEquals(row, a.getRow(1), DELTA); assertArrayEquals(row, a.getRow(2), DELTA); } @Test public void testGetCol() { Matrix a = Matrix.random(10, 15); assertArrayEquals(a.getCol(12), a.transpose().getRow(12), DELTA); for (int i = 0; i < 10; i++) { a.position(i, 9, 0); } assertArrayEquals(new double[10], a.getCol(9), DELTA); for (int i = 0; i < 10; i++) { a.position(i, 3, i); } assertArrayEquals(new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, a.getCol(3), DELTA); } @Test public void testSubtractAndCopy() { Matrix a = Matrix.random(5, 10); Matrix b = Matrix.random(5, 10); Matrix c = Matrix.random(5, 10); Matrix d = Matrix.random(5, 10); assertNotEquals(a, d); a.subtractAndCopy(b, c, d); assertEquals(a, d); a.subtract(b, d); assertEquals(c, d); a.subtractAndCopy(a, b, c); assertEquals(a, c); assertEquals(new Matrix(5, 10), b); } @Test public void testMultiplyAndAdd() { Matrix a = Matrix.random(10, 20); Matrix b = Matrix.random(10, 20); Matrix c = new Matrix(10, 20); Matrix d = new Matrix(10, 20); assertNotEquals(a, b); assertNotEquals(a, c); a.multiplyAndAdd(0, b, c); assertEquals(b, c); double scale = Math.random(); a.multiply(scale, d); d.add(b, d); a.multiplyAndAdd(scale, b, c); assertEquals(c, d); } @Test public void testApplyInIdentity() { Function f = new Function() { @Override public double eval(double x) { return 0; } @Override public Function getDerivate() { return null; } }; Matrix a = Matrix.random(10, 10); Matrix b = new Column(10); b.applyInIdentity(f, a); for (int i = 0; i < a.getRows(); i++) { assertEquals(0, a.position(i, i), DELTA); } b.setValue(5); f = new Function() { @Override public double eval(double x) { return x; } @Override public Function getDerivate() { return null; } }; b.applyInIdentity(f, a); for (int i = 0; i < a.getRows(); i++) { for (int j = 0; j < a.getColumns(); j++) { if (i == j) { assertEquals(5, a.position(i, j), DELTA); } else { assertNotEquals(5, a.position(i, j), DELTA); } } } } @Test(expected = IllegalArgumentException.class) public void testDotProductThisNotRow() { Matrix a = Matrix.random(2, 10); Matrix b = Matrix.random(1, 20); a.dotProduct(b); } @Test(expected = IllegalArgumentException.class) public void testDotProductThisNotColumn() { Matrix a = Matrix.random(10, 2); Matrix b = Matrix.random(1, 20); a.dotProduct(b); } @Test(expected = IllegalArgumentException.class) public void testDotProductOtherNotRow() { Matrix a = Matrix.random(1, 20); Matrix b = Matrix.random(2, 10); a.dotProduct(b); } @Test(expected = IllegalArgumentException.class) public void testDotProductOtherNotColumn() { Matrix a = Matrix.random(1, 20); Matrix b = Matrix.random(10, 2); a.dotProduct(b); } @Test public void testHashCode() { Matrix a = Matrix.random(10, 10); Matrix b = Matrix.random(10, 10); Matrix c = Matrix.random(10, 5); Matrix d = Matrix.random(5, 10); HashMap<Matrix, Matrix> map = new HashMap<>(4); map.put(a, a); map.put(b, b); map.put(c, c); map.put(d, d); assertTrue(a == map.get(a)); assertTrue(b == map.get(b)); assertTrue(c == map.get(c)); assertTrue(d == map.get(d)); } @Test public void testHashCode2() { Matrix a = Matrix.random(10, 10); assertEquals(a.hashCode(), a.hashCode()); Matrix b = new Matrix(10, 10); a.copy(b); assertEquals(a.hashCode(), b.hashCode()); b.position(0, 0, b.position(0, 0) + 1); assertNotEquals(a.hashCode(), b.hashCode()); } @Test public void testToString() { Matrix a = new Column(2); assertEquals("0.00000000 \n0.00000000 \n\n", a.toString()); a = new Row(2); assertEquals("0.00000000 0.00000000 \n\n", a.toString()); } private void assertArrayNotEquals(double[] a, double[] b, double DELTA) { try { assertArrayEquals(a, b, DELTA); throw new AssertionError("Both arrays are equal!"); } catch (AssertionError ignoreMe) { } } }
25,974
0.63437
0.555064
1,019
24.503435
19.819765
102
false
false
0
0
0
0
0
0
3.000981
false
false
13
c0bdd33042c27836aa6238eff918840cf97f6baa
34,969,623,756,779
936012136ba713738dfb1f0dec7aa4c79533c469
/src/main/java/com/zhjinyang/cn/domin/criteria/DeptCriteria.java
3e5f34de873b9ffb8fc3667c30444b737af637cb
[]
no_license
zhjinyang/crm-master
https://github.com/zhjinyang/crm-master
6be1ca950f82d3019c5bdc5f700d7c483e7dd49c
90afda9dac7e0a78c02f40d15d440f99401fce5c
refs/heads/master
2023-04-05T05:39:02.473000
2021-04-20T12:36:22
2021-04-20T12:36:22
358,253,249
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhjinyang.cn.domin.criteria; import com.zhjinyang.cn.domin.criteria.base.BaseQueryCriteria; import lombok.Data; import org.springframework.util.StringUtils; /** * @author Zjy * @date 2021/4/19 21:14 */ @Data public class DeptCriteria extends BaseQueryCriteria { private String deptName; /** * 判断是否是查询 * * @return */ public boolean isQuery() { return !StringUtils.isEmpty(this.deptName) || (!StringUtils.isEmpty(this.getStartTime()) && !StringUtils.isEmpty(this.getEndTime())); } }
UTF-8
Java
561
java
DeptCriteria.java
Java
[ { "context": ".springframework.util.StringUtils;\n\n/**\n * @author Zjy\n * @date 2021/4/19 21:14\n */\n@Data\npublic class D", "end": 189, "score": 0.9986166954040527, "start": 186, "tag": "USERNAME", "value": "Zjy" } ]
null
[]
package com.zhjinyang.cn.domin.criteria; import com.zhjinyang.cn.domin.criteria.base.BaseQueryCriteria; import lombok.Data; import org.springframework.util.StringUtils; /** * @author Zjy * @date 2021/4/19 21:14 */ @Data public class DeptCriteria extends BaseQueryCriteria { private String deptName; /** * 判断是否是查询 * * @return */ public boolean isQuery() { return !StringUtils.isEmpty(this.deptName) || (!StringUtils.isEmpty(this.getStartTime()) && !StringUtils.isEmpty(this.getEndTime())); } }
561
0.683729
0.66362
27
19.25926
29.481436
141
false
false
0
0
0
0
0
0
0.296296
false
false
13
ea005540f0b07bdcbaa227ee7ada408598469c1c
38,620,345,942,808
4aae4622a751e99eb8fe16b31599772306cb95ab
/app/src/main/java/com/codeblack/movealong/Users.java
4379acaed79cc19d571ccc8da44b28151d28990a
[]
no_license
njprasher/MoveAlong
https://github.com/njprasher/MoveAlong
d76bbe51f02a30ff09273175b7e6e42b712afcaf
5dcc58c87745f0e42912351d6ec541d0dfa84525
refs/heads/master
2021-07-06T18:31:57.470000
2019-08-19T20:43:31
2019-08-19T20:43:31
200,894,991
0
1
null
false
2020-10-25T22:48:41
2019-08-06T17:22:31
2019-08-19T20:43:40
2019-11-26T06:30:40
528
0
1
1
Java
false
false
package com.codeblack.movealong; import java.util.ArrayList; public class Users { int UId; String Name; String Email; String Gender; String Phone_number; String Password; static ArrayList<Users> userArray = new ArrayList<Users>(); public int getUId() { return UId; } public void setUId(int UId) { this.UId = UId; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getGender() { return Gender; } public void setGender(String gender) { Gender = gender; } public String getPhone_number() { return Phone_number; } public void setPhone_number(String phone_number) { Phone_number = phone_number; } public Users(String email, String password) { Email = email; Password = password; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } }
UTF-8
Java
1,208
java
Users.java
Java
[ { "context": "sword) {\n Email = email;\n Password = password;\n }\n\n public String getEmail() {\n re", "end": 917, "score": 0.9937583208084106, "start": 909, "tag": "PASSWORD", "value": "password" }, { "context": " setPassword(String password) {\n ...
null
[]
package com.codeblack.movealong; import java.util.ArrayList; public class Users { int UId; String Name; String Email; String Gender; String Phone_number; String Password; static ArrayList<Users> userArray = new ArrayList<Users>(); public int getUId() { return UId; } public void setUId(int UId) { this.UId = UId; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getGender() { return Gender; } public void setGender(String gender) { Gender = gender; } public String getPhone_number() { return Phone_number; } public void setPhone_number(String phone_number) { Phone_number = phone_number; } public Users(String email, String password) { Email = email; Password = <PASSWORD>; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getPassword() { return Password; } public void setPassword(String password) { Password = <PASSWORD>; } }
1,212
0.583609
0.583609
69
16.507246
15.75779
63
false
false
0
0
0
0
0
0
0.347826
false
false
13
8a90324b1a99c05fc4e8dc57c5d3f34c7c7a20bd
38,311,108,298,066
2b06320a5798864cb20d50a0d59d878cb8bab2a3
/dubbo-cloud-trade/src/main/java/com/lkl/dcloud/trade/service/OrderService.java
63d4912faf2b717650dd71200cf3ff8a2b432dfd
[]
no_license
sectlvy/sdubbo
https://github.com/sectlvy/sdubbo
d0b7528d9bf7a045d7c6be00dc6c234a71f5cc4f
a69c617cc44868640c8c2c12b6d006ea2f1dcb1d
refs/heads/master
2021-05-13T19:32:02.339000
2018-01-19T06:48:43
2018-01-19T06:48:43
116,895,380
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lkl.dcloud.trade.service; import java.util.Date; import java.util.concurrent.Future; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.rpc.RpcContext; import com.lkl.dcloud.trade.dao.gen.SpOrderMapper; import com.lkl.dcloud.trade.dao.gen.bean.SpOrder; import com.lkl.dcloud.user.UserCountService; import com.lkl.dcloud.user.UserService; import com.lkl.dcloud.user.vo.SpOrderCountVo; import com.lkl.dcloud.user.vo.SpUserVo; @Component public class OrderService { @Autowired SpOrderMapper spOrderMapper; //retries=2, @Reference(check=true,loadbalance="roundrobin",group="*",consumer="")//启动检查关闭,该为测试时使用,服务启动时默认用户服务已经存在 否则会报错 //retries 失败重试2次 //cluster forking 表示并行请求 UserService userService; @Reference UserCountService userCountService; @Transactional public SpOrder submitOrder(String uid){ SpOrder spOrder = new SpOrder(); spOrder.setCreateTime(new Date()); spOrder.setGoodNo(getRand("GD")); spOrder.setOrderNo(getRand("OD")); spOrder.setPriceChannel(11D); SpUserVo spUserVo = userService.getSpUser(uid); spOrder.setUserDesc(spUserVo.getUserDesc()); spOrder.setUserId(spUserVo.getUserId()); spOrder.setUserName(spUserVo.getUserName()); spOrderMapper.insert(spOrder); SpOrderCountVo spOrderCountVo = new SpOrderCountVo(); spOrderCountVo.setOrderNo(spOrder.getOrderNo());//若注释掉则会报 ConstraintViolationImpl{interpolatedMessage='订单号不能为空', spOrderCountVo.setUserId(spUserVo.getUserId()); userCountService.addOrderCount(spOrderCountVo); return spOrder; } private String getRand(String pre){ Date date = new Date(); return pre+date.getTime(); } }
UTF-8
Java
2,019
java
OrderService.java
Java
[]
null
[]
package com.lkl.dcloud.trade.service; import java.util.Date; import java.util.concurrent.Future; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.rpc.RpcContext; import com.lkl.dcloud.trade.dao.gen.SpOrderMapper; import com.lkl.dcloud.trade.dao.gen.bean.SpOrder; import com.lkl.dcloud.user.UserCountService; import com.lkl.dcloud.user.UserService; import com.lkl.dcloud.user.vo.SpOrderCountVo; import com.lkl.dcloud.user.vo.SpUserVo; @Component public class OrderService { @Autowired SpOrderMapper spOrderMapper; //retries=2, @Reference(check=true,loadbalance="roundrobin",group="*",consumer="")//启动检查关闭,该为测试时使用,服务启动时默认用户服务已经存在 否则会报错 //retries 失败重试2次 //cluster forking 表示并行请求 UserService userService; @Reference UserCountService userCountService; @Transactional public SpOrder submitOrder(String uid){ SpOrder spOrder = new SpOrder(); spOrder.setCreateTime(new Date()); spOrder.setGoodNo(getRand("GD")); spOrder.setOrderNo(getRand("OD")); spOrder.setPriceChannel(11D); SpUserVo spUserVo = userService.getSpUser(uid); spOrder.setUserDesc(spUserVo.getUserDesc()); spOrder.setUserId(spUserVo.getUserId()); spOrder.setUserName(spUserVo.getUserName()); spOrderMapper.insert(spOrder); SpOrderCountVo spOrderCountVo = new SpOrderCountVo(); spOrderCountVo.setOrderNo(spOrder.getOrderNo());//若注释掉则会报 ConstraintViolationImpl{interpolatedMessage='订单号不能为空', spOrderCountVo.setUserId(spUserVo.getUserId()); userCountService.addOrderCount(spOrderCountVo); return spOrder; } private String getRand(String pre){ Date date = new Date(); return pre+date.getTime(); } }
2,019
0.75882
0.756714
57
31.31579
23.762833
114
false
false
0
0
0
0
0
0
1.964912
false
false
13
c3c343ee447726faf7a4d6bd3e64dcf2aa455cea
22,849,226,073,355
2ec0261087d9794cb3f494feae20dc971119edcb
/src/main/java/lesson_nine/utill/Helper.java
d26925d1846f7a16762119735e926ec8ac6e09e8
[]
no_license
antnknvlnk/java_hillel_homeworks
https://github.com/antnknvlnk/java_hillel_homeworks
4e55a3e1f239f4e7871089219ea562b1622854b8
99583f202e5fad655288984511b67f820080765d
refs/heads/main
2023-04-22T23:12:46.930000
2021-05-04T22:00:31
2021-05-04T22:00:31
342,841,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lesson_nine.utill; import java.util.Optional; public class Helper { public Optional<String> optionalHelper(String email) { if (email == null || email.isEmpty() || !email.matches("^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)" + "*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$")){ return Optional.empty(); } else { return Optional.of(email); } } }
UTF-8
Java
436
java
Helper.java
Java
[]
null
[]
package lesson_nine.utill; import java.util.Optional; public class Helper { public Optional<String> optionalHelper(String email) { if (email == null || email.isEmpty() || !email.matches("^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)" + "*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$")){ return Optional.empty(); } else { return Optional.of(email); } } }
436
0.460648
0.451389
15
27.799999
31.791403
123
false
false
0
0
0
0
0
0
0.733333
false
false
13
7d87b9c4c9cd3c7fe6523176d64344d5e9f09f24
9,543,417,333,485
ca47afb55ec7beb5e82b1353541d48004b7bf455
/app/src/main/java/com/classic/simple/activity/EventBusActivity.java
f1637c9685921401c909270bd80fb2e9dea72342
[ "MIT" ]
permissive
JayColor/AndroidBasicProject
https://github.com/JayColor/AndroidBasicProject
20d69d7ad85b653e49cae8e2d32c4b2c05bca53d
b469c253319a6a4ff3b0427c986d46c7537a46c2
refs/heads/master
2021-01-22T08:29:48.351000
2016-08-05T06:39:00
2016-08-05T06:39:00
66,618,714
1
0
null
true
2016-08-26T05:17:58
2016-08-26T05:17:57
2016-08-23T12:52:59
2016-08-05T06:39:13
8,254
0
0
0
null
null
null
package com.classic.simple.activity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.Bind; import com.classic.core.utils.DataUtil; import com.classic.core.utils.DateUtil; import com.classic.simple.R; import com.classic.simple.event.EventUtil; import org.simple.eventbus.Subscriber; import org.simple.eventbus.ThreadMode; /** * AndroidEventBus示例 */ public class EventBusActivity extends AppBaseActivity { public static final String EVENT_TAG = "classic"; @Bind(R.id.eventbus_button) Button mBtnPostEventBus; @Bind(R.id.eventbus_content) TextView mContent; @Override public boolean configEventBus() { return true; } @Override public int getLayoutResId() { return R.layout.activity_eventbus; } @Override public void initView(Bundle savedInstanceState) { super.initView(savedInstanceState); mBtnPostEventBus.setOnClickListener(this); //这里偷懒,使用默认的。实际项目中建议使用ToolBar getSupportActionBar().setTitle("AndroidEventBus示例"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void viewClick(View v) { if (v.getId() == R.id.eventbus_button) { //发布一个事件 EventUtil.post(DateUtil.formatDate("HH:mm:ss.SSS", System.currentTimeMillis()), EVENT_TAG); } } /** * 接收事件 * 当用户post事件时,只有指定了EVENT_TAG的事件才会触发该函数, * ThreadMode.MAIN : 默认方法,执行在UI线程,可省略不写 * ThreadMode.ASYNC: 执行在一个独立的线程 * ThreadMode.POST : post函数在哪个线程执行,该函数就执行在哪个线程 */ @Subscriber(tag = EVENT_TAG, mode = ThreadMode.MAIN) public void updateUI(String params) { final StringBuilder sb = new StringBuilder( DataUtil.isEmpty(mContent.getText().toString()) ? "" : mContent.getText().toString()); sb.append("\n").append("收到事件 --> ").append(params); mContent.setText(sb.toString()); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } }
UTF-8
Java
2,458
java
EventBusActivity.java
Java
[]
null
[]
package com.classic.simple.activity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.Bind; import com.classic.core.utils.DataUtil; import com.classic.core.utils.DateUtil; import com.classic.simple.R; import com.classic.simple.event.EventUtil; import org.simple.eventbus.Subscriber; import org.simple.eventbus.ThreadMode; /** * AndroidEventBus示例 */ public class EventBusActivity extends AppBaseActivity { public static final String EVENT_TAG = "classic"; @Bind(R.id.eventbus_button) Button mBtnPostEventBus; @Bind(R.id.eventbus_content) TextView mContent; @Override public boolean configEventBus() { return true; } @Override public int getLayoutResId() { return R.layout.activity_eventbus; } @Override public void initView(Bundle savedInstanceState) { super.initView(savedInstanceState); mBtnPostEventBus.setOnClickListener(this); //这里偷懒,使用默认的。实际项目中建议使用ToolBar getSupportActionBar().setTitle("AndroidEventBus示例"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void viewClick(View v) { if (v.getId() == R.id.eventbus_button) { //发布一个事件 EventUtil.post(DateUtil.formatDate("HH:mm:ss.SSS", System.currentTimeMillis()), EVENT_TAG); } } /** * 接收事件 * 当用户post事件时,只有指定了EVENT_TAG的事件才会触发该函数, * ThreadMode.MAIN : 默认方法,执行在UI线程,可省略不写 * ThreadMode.ASYNC: 执行在一个独立的线程 * ThreadMode.POST : post函数在哪个线程执行,该函数就执行在哪个线程 */ @Subscriber(tag = EVENT_TAG, mode = ThreadMode.MAIN) public void updateUI(String params) { final StringBuilder sb = new StringBuilder( DataUtil.isEmpty(mContent.getText().toString()) ? "" : mContent.getText().toString()); sb.append("\n").append("收到事件 --> ").append(params); mContent.setText(sb.toString()); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } }
2,458
0.671263
0.671263
71
30.661972
23.181431
94
false
false
0
0
0
0
0
0
0.492958
false
false
13
f20a8cdf22e5c7d73c0ad129ee76a951b46aa911
13,159,779,799,334
10bd08d9809e418ced61df3ae3dc10d81255f4a1
/src/main/java/com/pitchsider/smpp/timer/EnquireLinkTimer.java
5ba6489436cd83790b3870436629424f6f6448ff
[ "Apache-2.0" ]
permissive
faisalbasra/java-smpp
https://github.com/faisalbasra/java-smpp
7bfb31e623335b04d0f48fc7b730e54798f781ab
6f38999801dfde5f0fcbf9a92af367e663a4f802
refs/heads/master
2021-01-15T08:32:15.645000
2013-10-15T07:38:38
2013-10-15T07:38:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pitchsider.smpp.timer; /** * <p> * <strong>Required SMPP Session State:</strong> Open/Unbound/Outbound/Bound_TX/Bound_RX/Bound_TRX. * <br/> * <strong>Action:</strong> An enquire_link request should be initiated. * </p> * <p>This timer specifies the time lapse allowed between operations after which a * SMPP entity should interrogate whether its’ peer still has an active session. This * timer may be active on either peer (i.e. MC or ESME). * </p> * TODO implement this timer * @author Paul Whelan */ public interface EnquireLinkTimer extends Timer { }
UTF-8
Java
596
java
EnquireLinkTimer.java
Java
[ { "context": ".\n * </p>\n * TODO implement this timer \n * @author Paul Whelan\n */\npublic interface EnquireLinkTimer \n\textends T", "end": 534, "score": 0.9998642206192017, "start": 523, "tag": "NAME", "value": "Paul Whelan" } ]
null
[]
package com.pitchsider.smpp.timer; /** * <p> * <strong>Required SMPP Session State:</strong> Open/Unbound/Outbound/Bound_TX/Bound_RX/Bound_TRX. * <br/> * <strong>Action:</strong> An enquire_link request should be initiated. * </p> * <p>This timer specifies the time lapse allowed between operations after which a * SMPP entity should interrogate whether its’ peer still has an active session. This * timer may be active on either peer (i.e. MC or ESME). * </p> * TODO implement this timer * @author <NAME> */ public interface EnquireLinkTimer extends Timer { }
591
0.705387
0.705387
20
28.700001
32.386879
102
false
false
0
0
0
0
0
0
0.1
false
false
13
da740dc8b9ca1b052e5953dfa8dc67e651a9cf5f
27,178,553,114,854
5cfaeebdc7c50ca23ee368fa372d48ed1452dfeb
/xd-courseCenter/src/main/java/com/xiaodou/course/service/product/ProductItemService.java
d45310a34177968fd137434174b6c2ff2cd152f2
[]
no_license
zdhuangelephant/xd_pro
https://github.com/zdhuangelephant/xd_pro
c8c8ff6dfcfb55aead733884909527389e2c8283
5611b036968edfff0b0b4f04f0c36968333b2c3b
refs/heads/master
2022-12-23T16:57:28.306000
2019-12-05T06:05:43
2019-12-05T06:05:43
226,020,526
0
2
null
false
2022-12-16T02:23:20
2019-12-05T05:06:27
2019-12-05T06:09:36
2022-12-16T02:23:19
383,586
0
2
66
JavaScript
false
false
package com.xiaodou.course.service.product; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.xiaodou.common.util.CommUtil; import com.xiaodou.course.model.product.ProductItemModel; import com.xiaodou.course.service.facade.ProductServiceFacade; import com.xiaodou.summer.dao.pagination.Page; /** * Created by zyp on 15/8/9. */ @Service("productItemService") public class ProductItemService { @Resource ProductServiceFacade productServiceFacade; /** * 根据Id查找 * * @param itemId * @return */ public ProductItemModel findItemById(Integer itemId) { ProductItemModel cond = new ProductItemModel(); cond.setId(itemId); return productServiceFacade.queryProductItemById(cond); } /** * item列表 * * @param ids * @return */ public List<ProductItemModel> queryItemListByIds(List<Integer> ids) { Map<String, Object> cond = new HashMap<>(); cond.put("ids", ids); cond.put("showStatus", 1); Map<String, Object> output = new HashMap<>(); CommUtil.getBasicField(output, ProductItemModel.class); Page<ProductItemModel> productItemModelPage = productServiceFacade.queryProductItemListByCondWithOutPage(cond, output); return productItemModelPage.getResult(); } /** * 根据章ID获取item列表 * * @param chapterId 章ID * @return */ public List<ProductItemModel> queryItemListByChapterId(Integer chapterId) { Map<String, Object> cond = new HashMap<>(); cond.put("parentId", chapterId); cond.put("showStatus", 1); Map<String, Object> output = new HashMap<>(); CommUtil.getBasicField(output, ProductItemModel.class); Page<ProductItemModel> productItemModelPage = productServiceFacade.queryProductItemListByCondWithOutPage(cond, output); return productItemModelPage.getResult(); } /** * 根据productId获取item列表 * * @param productId * @return */ public List<ProductItemModel> queryItemListByProductId(Integer productId) { Map<String, Object> cond = new HashMap<String, Object>(); cond.put("productId", productId); cond.put("showStatus", 1); Map<String, Object> output = new HashMap<String, Object>(); CommUtil.getBasicField(output, ProductItemModel.class); Page<ProductItemModel> categoryList = productServiceFacade.queryProductItemListByCondWithOutPage(cond, output); return categoryList.getResult(); } }
UTF-8
Java
2,540
java
ProductItemService.java
Java
[ { "context": "dou.summer.dao.pagination.Page;\n\n/**\n * Created by zyp on 15/8/9.\n */\n@Service(\"productItemService\")\npub", "end": 431, "score": 0.9996224641799927, "start": 428, "tag": "USERNAME", "value": "zyp" } ]
null
[]
package com.xiaodou.course.service.product; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.xiaodou.common.util.CommUtil; import com.xiaodou.course.model.product.ProductItemModel; import com.xiaodou.course.service.facade.ProductServiceFacade; import com.xiaodou.summer.dao.pagination.Page; /** * Created by zyp on 15/8/9. */ @Service("productItemService") public class ProductItemService { @Resource ProductServiceFacade productServiceFacade; /** * 根据Id查找 * * @param itemId * @return */ public ProductItemModel findItemById(Integer itemId) { ProductItemModel cond = new ProductItemModel(); cond.setId(itemId); return productServiceFacade.queryProductItemById(cond); } /** * item列表 * * @param ids * @return */ public List<ProductItemModel> queryItemListByIds(List<Integer> ids) { Map<String, Object> cond = new HashMap<>(); cond.put("ids", ids); cond.put("showStatus", 1); Map<String, Object> output = new HashMap<>(); CommUtil.getBasicField(output, ProductItemModel.class); Page<ProductItemModel> productItemModelPage = productServiceFacade.queryProductItemListByCondWithOutPage(cond, output); return productItemModelPage.getResult(); } /** * 根据章ID获取item列表 * * @param chapterId 章ID * @return */ public List<ProductItemModel> queryItemListByChapterId(Integer chapterId) { Map<String, Object> cond = new HashMap<>(); cond.put("parentId", chapterId); cond.put("showStatus", 1); Map<String, Object> output = new HashMap<>(); CommUtil.getBasicField(output, ProductItemModel.class); Page<ProductItemModel> productItemModelPage = productServiceFacade.queryProductItemListByCondWithOutPage(cond, output); return productItemModelPage.getResult(); } /** * 根据productId获取item列表 * * @param productId * @return */ public List<ProductItemModel> queryItemListByProductId(Integer productId) { Map<String, Object> cond = new HashMap<String, Object>(); cond.put("productId", productId); cond.put("showStatus", 1); Map<String, Object> output = new HashMap<String, Object>(); CommUtil.getBasicField(output, ProductItemModel.class); Page<ProductItemModel> categoryList = productServiceFacade.queryProductItemListByCondWithOutPage(cond, output); return categoryList.getResult(); } }
2,540
0.7176
0.7148
88
27.40909
24.107542
81
false
false
0
0
0
0
0
0
0.625
false
false
13
58d6fbe98b8b36f01bf87b7248aec5c3939f724f
13,941,463,844,357
0527194bf465356910d46323970000d1f6d79c54
/src/main/java/com/luizalabs/information/address/api/controller/AddressController.java
59eb7eb65a72611c12ff29e685e39ff38d9cd3d4
[]
no_license
lemottaa/information-address-api
https://github.com/lemottaa/information-address-api
06c4bd5bc634039a3a6bc741efba3ede68708bb6
4ef6eee05beb65c357e32b27f93eb3e94e93771f
refs/heads/master
2022-12-25T02:53:00.998000
2020-10-05T18:34:21
2020-10-05T18:34:21
300,492,511
0
0
null
false
2020-10-05T00:44:43
2020-10-02T03:41:13
2020-10-04T05:12:28
2020-10-05T00:44:43
62
0
0
0
Java
false
false
package com.luizalabs.information.address.api.controller; import java.io.IOException; import java.util.Date; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.luizalabs.information.address.api.config.AddressControllerConfig; import com.luizalabs.information.address.api.controller.base.BaseController; import com.luizalabs.information.address.api.dto.response.AddressResponseDTO; import com.luizalabs.information.address.api.dto.response.ResponseBodyDTO; import com.luizalabs.information.address.api.factory.ErrorFactory; import com.luizalabs.information.address.api.factory.ResponseBodyFactory; import com.luizalabs.information.address.api.service.AddressService; import com.luizalabs.information.address.api.validator.ZipCodeNumberValidator; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponse; @RestController @RequestMapping(AddressControllerConfig.REQUEST_MAPPING_BASE) public class AddressController extends BaseController { @Autowired private AddressService addressService; @Autowired private ZipCodeNumberValidator zipCodeValidator; @ApiOperation("Get address by zipcode") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get address was successful"), @ApiResponse(code = 400, message = "Get address was successful"), @ApiResponse(code = 404, message = "Address not found") }) @GetMapping public ResponseEntity<ResponseBodyDTO<AddressResponseDTO>> getAddressByZipCode(@Valid @NotEmpty @RequestParam(value = "zipcode", required = true) @Size(min = 0, max = 8) final String zipCode) throws IOException { final Date initialTIme = new Date(); if (Boolean.FALSE.equals(this.zipCodeValidator.isValid(zipCode))) { return buildResponse(ResponseBodyFactory.with(AddressResponseDTO.builder().build(), ErrorFactory.invalidParameter("zipcode")), HttpStatus.BAD_REQUEST, AddressControllerConfig.REQUEST_MAPPING_BASE, HttpMethod.GET, initialTIme); } return buildResponse(this.addressService.getAdressByZipCode(zipCode), HttpStatus.OK, AddressControllerConfig.REQUEST_MAPPING_BASE, HttpMethod.GET, initialTIme); } }
UTF-8
Java
2,696
java
AddressController.java
Java
[]
null
[]
package com.luizalabs.information.address.api.controller; import java.io.IOException; import java.util.Date; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.luizalabs.information.address.api.config.AddressControllerConfig; import com.luizalabs.information.address.api.controller.base.BaseController; import com.luizalabs.information.address.api.dto.response.AddressResponseDTO; import com.luizalabs.information.address.api.dto.response.ResponseBodyDTO; import com.luizalabs.information.address.api.factory.ErrorFactory; import com.luizalabs.information.address.api.factory.ResponseBodyFactory; import com.luizalabs.information.address.api.service.AddressService; import com.luizalabs.information.address.api.validator.ZipCodeNumberValidator; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponse; @RestController @RequestMapping(AddressControllerConfig.REQUEST_MAPPING_BASE) public class AddressController extends BaseController { @Autowired private AddressService addressService; @Autowired private ZipCodeNumberValidator zipCodeValidator; @ApiOperation("Get address by zipcode") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get address was successful"), @ApiResponse(code = 400, message = "Get address was successful"), @ApiResponse(code = 404, message = "Address not found") }) @GetMapping public ResponseEntity<ResponseBodyDTO<AddressResponseDTO>> getAddressByZipCode(@Valid @NotEmpty @RequestParam(value = "zipcode", required = true) @Size(min = 0, max = 8) final String zipCode) throws IOException { final Date initialTIme = new Date(); if (Boolean.FALSE.equals(this.zipCodeValidator.isValid(zipCode))) { return buildResponse(ResponseBodyFactory.with(AddressResponseDTO.builder().build(), ErrorFactory.invalidParameter("zipcode")), HttpStatus.BAD_REQUEST, AddressControllerConfig.REQUEST_MAPPING_BASE, HttpMethod.GET, initialTIme); } return buildResponse(this.addressService.getAdressByZipCode(zipCode), HttpStatus.OK, AddressControllerConfig.REQUEST_MAPPING_BASE, HttpMethod.GET, initialTIme); } }
2,696
0.817507
0.813427
61
43.213116
29.651592
90
false
false
0
0
0
0
0
0
1.754098
false
false
13
6a7e3d35e651af9dec0341f5a4db9668239ae368
704,374,658,082
ab59af50fa9a36ab42bcb3cfa6eab6e5bc58c246
/jpa-hibernate-spring/src/main/java/br/ce/qxm/repository/impl/LivroRepositoryImpl.java
7805a21e866f116641998db06273e91684a3b34d
[]
no_license
salomaosilvasantos/Treinando-Jpa-Hibernate-Spring
https://github.com/salomaosilvasantos/Treinando-Jpa-Hibernate-Spring
ead06ce15b57f61c134ced0c226f831a4ad9ccdf
b0e6cb242416feef289ee3345ef7b38f5e49e55f
refs/heads/master
2021-01-23T10:43:52.586000
2014-12-16T15:48:41
2014-12-16T15:48:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ce.qxm.repository.impl; import org.springframework.stereotype.Repository; import br.ce.qxm.model.Livro; import br.ce.qxm.repository.LivroRepository; @Repository public class LivroRepositoryImpl extends GenericRepositoryImpl<Livro> implements LivroRepository { }
UTF-8
Java
288
java
LivroRepositoryImpl.java
Java
[]
null
[]
package br.ce.qxm.repository.impl; import org.springframework.stereotype.Repository; import br.ce.qxm.model.Livro; import br.ce.qxm.repository.LivroRepository; @Repository public class LivroRepositoryImpl extends GenericRepositoryImpl<Livro> implements LivroRepository { }
288
0.802083
0.802083
11
24.181818
29.58445
98
false
false
0
0
0
0
0
0
0.363636
false
false
13
d642227ab599a35a285f3f72b85dda8cf04f4a37
20,366,734,940,383
51bc4224112c10355c3618380db9695fcc3488b0
/src/main/java/uz/mf/hujjatmf/spec/EmployeeGroupSpec.java
1b9ebd9924e491faa000103e3c646e8ea8b408e3
[]
no_license
ravshansbox/hujjatmf
https://github.com/ravshansbox/hujjatmf
da1e33a756ae60322ec2aeff1c1cd94a0a53fe90
5566ea274b0e25ae6c2d9071e1a24049bb062130
refs/heads/master
2015-09-25T06:15:28.305000
2015-09-25T03:55:44
2015-09-25T03:55:44
39,676,007
0
1
null
false
2015-08-14T10:31:56
2015-07-25T07:07:52
2015-07-25T07:10:13
2015-08-14T10:31:56
5,000
0
1
0
Java
null
null
package uz.mf.hujjatmf.spec; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import uz.mf.hujjatmf.domain.Department; import uz.mf.hujjatmf.domain.EmployeeGroup; import uz.mf.hujjatmf.domain.EmployeeGroup_; import uz.mf.hujjatmf.model.jpa.Specification; public class EmployeeGroupSpec { public static Specification<EmployeeGroup> orderByName() { return new Specification<EmployeeGroup>() { @Override public Predicate toPredicate(Root<EmployeeGroup> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { cq.orderBy(cb.asc(root.get(EmployeeGroup_.nameRu)), cb.asc(root.get(EmployeeGroup_.nameUz))); return null; } }; } public static Specification<EmployeeGroup> byOwnerDepartment(final Department ownerDepartment) { return new Specification<EmployeeGroup>() { @Override public Predicate toPredicate(Root<EmployeeGroup> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { return cb.equal(root.get(EmployeeGroup_.ownerDepartment), ownerDepartment); } }; } }
UTF-8
Java
1,255
java
EmployeeGroupSpec.java
Java
[]
null
[]
package uz.mf.hujjatmf.spec; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import uz.mf.hujjatmf.domain.Department; import uz.mf.hujjatmf.domain.EmployeeGroup; import uz.mf.hujjatmf.domain.EmployeeGroup_; import uz.mf.hujjatmf.model.jpa.Specification; public class EmployeeGroupSpec { public static Specification<EmployeeGroup> orderByName() { return new Specification<EmployeeGroup>() { @Override public Predicate toPredicate(Root<EmployeeGroup> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { cq.orderBy(cb.asc(root.get(EmployeeGroup_.nameRu)), cb.asc(root.get(EmployeeGroup_.nameUz))); return null; } }; } public static Specification<EmployeeGroup> byOwnerDepartment(final Department ownerDepartment) { return new Specification<EmployeeGroup>() { @Override public Predicate toPredicate(Root<EmployeeGroup> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { return cb.equal(root.get(EmployeeGroup_.ownerDepartment), ownerDepartment); } }; } }
1,255
0.701992
0.701992
32
38.21875
33.565918
109
false
false
0
0
0
0
0
0
0.625
false
false
13
98b99e4d376f478dba2c7f39edbbcb2c877866c9
21,483,426,441,027
7bbec5c1fb5af2d027bbcb94891ecdafee128592
/salvo/src/main/java/com/codeoftheweb/salvo/controllers/SalvoController.java
947c2b91cdcc3b57dcd2586a2acc1e0f704d822a
[]
no_license
gastonbus/salvo
https://github.com/gastonbus/salvo
44f110d6ce5298dcf404d76afd6c303abbe5ab63
a8cbf3bfdde07d76fe6abe9fcc5874937d82ef5b
refs/heads/master
2023-06-02T21:32:22.864000
2021-06-18T13:22:27
2021-06-18T13:22:27
348,810,899
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codeoftheweb.salvo.controllers; import com.codeoftheweb.salvo.models.*; import com.codeoftheweb.salvo.repositories.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @RestController @RequestMapping("/api") public class SalvoController { @Autowired private PlayerRepository playerRepository; @Autowired private GameRepository gameRepository; @Autowired private GamePlayerRepository gamePlayerRepository; @Autowired private ShipRepository shipRepository; @Autowired private SalvoRepository salvoRepository; @Autowired private ScoreRepository scoreRepository; @Autowired private PasswordEncoder passwordEncoder; @GetMapping("/players") public Set<Map<String, Object>> getPlayers() { return playerRepository.findAll().stream().map(this::makePlayerDTO).collect(toSet()); } @PostMapping("/players") public ResponseEntity<Object> register( @RequestParam String userName, @RequestParam String password ) { if (userName.isEmpty() || password.isEmpty()) { return new ResponseEntity<>("Missing data", HttpStatus.FORBIDDEN); } if (playerRepository.findByUserName(userName) != null) { return new ResponseEntity<>("Name already in use", HttpStatus.FORBIDDEN); } playerRepository.save(new Player(userName, passwordEncoder.encode(password))); return new ResponseEntity<>(HttpStatus.CREATED); } @GetMapping("/games") public Map<String, Object> getGames(Authentication authentication) { Map<String, Object> dto = new LinkedHashMap<>(); //Verify if user is authenticated or not if (!isGuest(authentication)) { Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); dto.put("player", makePlayerDTO(authenticatedPlayer)); } else { dto.put("player", null); } dto.put("games", gameRepository.findAll().stream().map(this::makeGameDTO).collect(toSet())); return dto; } //Function to create new game @PostMapping("/games") public ResponseEntity<Map<String, Object>> createGame(Authentication authentication) { if (!isGuest(authentication)) { LocalDateTime dateTime = LocalDateTime.now(); Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); //Procedure to create a new game: Game newGame = new Game(dateTime); gameRepository.save(newGame); GamePlayer newGamePlayer = new GamePlayer(dateTime, authenticatedPlayer, newGame); gamePlayerRepository.save(newGamePlayer); return new ResponseEntity<>(makeMap("gpid", newGamePlayer.getId()), HttpStatus.CREATED); } else { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } } //Function to join an existing game @PostMapping("/games/{gameId}/players") public ResponseEntity<Map<String,Object>> joinGame(@PathVariable Long gameId, Authentication authentication) { //Verify if user is authenticated or not if (isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } LocalDateTime dateTime = LocalDateTime.now(); Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<Game> optRequestedGame = gameRepository.findById(gameId); //Verify that the game exists if (optRequestedGame.isEmpty()) { return new ResponseEntity<>(makeMap("error", "The game you want to play does not exist."), HttpStatus.FORBIDDEN); } //Verify if the player is full or it have space for one more player Game requestedGame = optRequestedGame.get(); if (requestedGame.getGamePlayers().size() >= 2) { return new ResponseEntity<>(makeMap("error", "The game is full and you can't join it."), HttpStatus.FORBIDDEN); } //Verify if the existing player is not the authenticated player Optional<Player> existingPlayer = requestedGame.getPlayers().stream().findFirst(); if (!(existingPlayer.isPresent() && authenticatedPlayer.getId() != existingPlayer.get().getId())) { return new ResponseEntity<>(makeMap("error", "You are already in this game."), HttpStatus.FORBIDDEN); } //Procedure to join a game: GamePlayer newGamePlayer = new GamePlayer(dateTime, authenticatedPlayer, requestedGame); gamePlayerRepository.save(newGamePlayer); return new ResponseEntity<>(makeMap("gpid", newGamePlayer.getId()), HttpStatus.CREATED); } @GetMapping("/game_view/{gamePlayerId}") public ResponseEntity<Map<String, Object>> getGame(@PathVariable Long gamePlayerId, Authentication authentication) { //Verify if user is authenticated or not if(isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "That game does not correspond to any player."), HttpStatus.BAD_REQUEST); } //Verify if this player is playing the game requested. GamePlayer gamePlayer = optGamePlayer.get(); if(!(authenticatedPlayer.getId() == gamePlayer.getPlayer().getId())) { return new ResponseEntity<>(makeMap("error", "This is not your game. Don't try to cheat!"), HttpStatus.FORBIDDEN); } return new ResponseEntity<>(makeGameViewDTO(gamePlayer), HttpStatus.OK); /* Another way to do this: if(!isGuest(authentication)) { //Verify if user is authenticated or not Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); return optGamePlayer.map(gp -> { if(authenticatedPlayer.getId() == gp.getPlayer().getId()) { return new ResponseEntity<>(makeGameViewDTO(gp), HttpStatus.OK); } else { return new ResponseEntity<>(makeMap("error", "This is not your game. Don't try to cheat!"), HttpStatus.FORBIDDEN); } }) .orElse(new ResponseEntity<>(makeMap("error", "That game does not correspond to any player."), HttpStatus.BAD_REQUEST)); } else { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); }*/ } @PostMapping("/games/players/{gamePlayerId}/ships") public ResponseEntity<Map<String, Object>> locateShips(@PathVariable Long gamePlayerId, @RequestBody List<Ship> ships, Authentication authentication) { //Verify if user is authenticated or not if (isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "The gamePlayer requested does not exist."), HttpStatus.FORBIDDEN); } //Verify if this player is playing the game requested. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); GamePlayer gamePlayer = optGamePlayer.get(); if(authenticatedPlayer.getId() != gamePlayer.getPlayer().getId()) { return new ResponseEntity<>(makeMap("error", "This game does not correspond to this player."), HttpStatus.FORBIDDEN); } //Validate if the player has his ships placed. if (gamePlayer.getShips().size() == 5) { return new ResponseEntity<>(makeMap("error", "You've just located your ships."), HttpStatus.FORBIDDEN); } //Validate if the request contains 5 ships. if (ships.size() != 5) { return new ResponseEntity<>(makeMap("error", "The request does not contains 5 ships."), HttpStatus.FORBIDDEN); } //Save the ships corresponding to the authenticated player for this game for (Ship ship:ships) { shipRepository.save(new Ship(gamePlayer, ship.getType(), ship.getLocations())); } return new ResponseEntity<>(makeMap("gpid", gamePlayer.getId()), HttpStatus.CREATED); } @GetMapping("/games/players/{gamePlayerId}/salvoes") public ResponseEntity<Map<String, Object>> getSalvoes(@PathVariable Long gamePlayerId, Authentication authentication) { //Verify if user is authenticated or not if(isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "That game does not correspond to any player."), HttpStatus.BAD_REQUEST); } //Verify if this player is playing the game requested. GamePlayer gamePlayer = optGamePlayer.get(); if(!(authenticatedPlayer.getId() == gamePlayer.getPlayer().getId())) { return new ResponseEntity<>(makeMap("error", "This is not your game. Don't try to cheat!"), HttpStatus.FORBIDDEN); } return new ResponseEntity<>(makeGameViewDTO(gamePlayer), HttpStatus.OK); } @PostMapping("/games/players/{gamePlayerId}/salvoes") public ResponseEntity<Map<String, Object>> locateSalvoes(@PathVariable Long gamePlayerId, @RequestBody Salvo salvo, Authentication authentication) { //Verify if user is authenticated or not if (isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "The gamePlayer requested does not exist."), HttpStatus.FORBIDDEN); } //Verify if this player is playing the game requested. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); GamePlayer gamePlayer = optGamePlayer.get(); if(authenticatedPlayer.getId() != gamePlayer.getPlayer().getId()) { return new ResponseEntity<>(makeMap("error", "This game does not correspond to this player."), HttpStatus.FORBIDDEN); } //Validate if the player has not fired all the salvoes. if (gamePlayer.getSalvoes().size() > 20) { return new ResponseEntity<>(makeMap("error", "You've just fired all your salvoes."), HttpStatus.FORBIDDEN); } //Validate if the request contains 5 shots. if (salvo.getLocations().size() != 5) { return new ResponseEntity<>(makeMap("error", "The request does not contains 5 shots."), HttpStatus.FORBIDDEN); } //Validate if the opponent has shot his salvo and it is the turn of the player. if (gamePlayer.getOpponent().isEmpty()) { return new ResponseEntity<>(makeMap("error", "There is no opponent yet."), HttpStatus.FORBIDDEN); } if (gamePlayer.getSalvoes().size() - gamePlayer.getOpponent().get().getSalvoes().size() >= 1) { return new ResponseEntity<>(makeMap("error", "You must wait for your opponent to make his shots."), HttpStatus.FORBIDDEN); } if (gamePlayer.gameStatus() == GameStatus.PLACE_SALVOES) { Salvo actualSalvo = new Salvo(gamePlayer, salvo.getTurn(), salvo.getLocations()); salvoRepository.save(actualSalvo); gamePlayer.getSalvoes().add(actualSalvo); if (gamePlayer.gameStatus() == GameStatus.TIE) { scoreRepository.save(new Score(0.5, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getPlayer())); scoreRepository.save(new Score(0.5, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getOpponent().get().getPlayer())); } else if (gamePlayer.gameStatus() == GameStatus.WIN) { scoreRepository.save(new Score(1.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getPlayer())); scoreRepository.save(new Score(0.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getOpponent().get().getPlayer())); } else if (gamePlayer.gameStatus() == GameStatus.LOSE) { scoreRepository.save(new Score(0.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getPlayer())); scoreRepository.save(new Score(1.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getOpponent().get().getPlayer())); } return new ResponseEntity<>(makeMap("turn", salvo.getTurn()), HttpStatus.CREATED); } //Save the salvoes corresponding to the authenticated player for this turn in this game salvoRepository.save(new Salvo(gamePlayer, salvo.getTurn(), salvo.getLocations())); return new ResponseEntity<>(makeMap("gpid", gamePlayer.getId()), HttpStatus.CREATED); } public Map<String, Object> makeGamesDTO(Game game) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", game.getId()); dto.put("date", game.getDateTime()); dto.put("gamePlayers", game.getGamePlayers().stream().map(this::makeGamePlayerDTO).collect(toSet())); return dto; } public Map<String, Object> makeGameDTO(Game game) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", game.getId()); dto.put("date", game.getDateTime()); dto.put("gamePlayers", game.getGamePlayers().stream().map(this::makeGamePlayerDTO).collect(toSet())); return dto; } //game_view public Map<String, Object> makeGameViewDTO(GamePlayer gamePlayer) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", gamePlayer.getGame().getId()); dto.put("date", gamePlayer.getGame().getDateTime()); dto.put("gameStatus", gamePlayer.gameStatus()); dto.put("gamePlayers", gamePlayer.getGame().getGamePlayers().stream().map(this::makeGamePlayerDTO).collect(toSet())); dto.put("ships", gamePlayer.getShips().stream().map(this::makeShipDTO).collect(toSet())); dto.put("salvoes", gamePlayer.getGame().getGamePlayers().stream().flatMap(elem -> elem.getSalvoes().stream().map(this::makeSalvoDTO))); dto.put("hits", gamePlayer.getSalvoes().stream().map(this::makeHitsDTO)); dto.put("sunkShips", gamePlayer.getSalvoes().stream().map(this::makeSunkShipsDTO)); dto.put("opponentHits", gamePlayer.getOpponent().map(gp -> gp.getSalvoes().stream().map(this::makeHitsDTO).collect(toList())).orElse(new ArrayList<>())); dto.put("opponentSunks", gamePlayer.getOpponent().map(gp -> gp.getSalvoes().stream().map(this::makeSunkShipsDTO).collect(toList())).orElse(new ArrayList<>())); return dto; } //game_view/gamePlayer private Map<String, Object> makeGamePlayerDTO(GamePlayer gamePlayer) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("gpid", gamePlayer.getId()); dto.put("player", makePlayerDTO(gamePlayer.getPlayer())); dto.put("score", gamePlayer.getScore().map(Score::getScore).orElse(null)); return dto; } //game_view/gamePlayer/player private Map<String, Object> makePlayerDTO(Player player) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", player.getId()); dto.put("email", player.getUserName()); return dto; } //game_view/gamePlayer/ships private Map<String, Object> makeShipDTO(Ship ship) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("type", ship.getType()); dto.put("locations", ship.getLocations()); return dto; } //game_view/gamePlayer/salvoes private Map<String, Object> makeSalvoDTO(Salvo salvo) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("playerId", salvo.getGamePlayer().getPlayer().getId()); dto.put("turn", salvo.getTurn()); dto.put("locations", salvo.getLocations()); return dto; } //game_view/gamePlayer/hits private Map<String, Object> makeHitsDTO(Salvo salvo) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("turn", salvo.getTurn()); dto.put("locationsWithImpact", salvo.getHits()); return dto; } private Map<String, Object> makeSunkShipsDTO(Salvo salvo) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("turn", salvo.getTurn()); dto.put("ships", salvo.getSunkShips().stream().map(this::makeShipDTO)); return dto; } // public String gameStatus(GamePlayer gamePlayer) { // // if (this.isGameOver(gamePlayer)) { // return "game over"; // } else { // if (gamePlayer.getOpponent().isEmpty()) { // return "waiting for opponent to join the game"; // } // if (gamePlayer.getShips().isEmpty()) { // return "waiting for player to place ships"; // } // if (gamePlayer.getOpponent().get().getShips().isEmpty()) { // return "waiting for opponent to place ships"; // } // if (gamePlayer.getSalvoes().stream().filter(s -> s.getTurn() == gamePlayer.getSalvoes().size()).count() == 0) { // return "waiting for player salvo"; // } // if (gamePlayer.getOpponent().get().getSalvoes().stream().filter(x -> x.getTurn() == gamePlayer.getSalvoes().size()).count() == 0) { // return "waiting for opponent salvo"; // } // return "playing game"; // } // } // // Boolean isGameOver(GamePlayer gamePlayer) { // List<Long> shipsSunkByOpponent = gamePlayer.getSalvoes().stream().filter(x -> x.getTurn() == gamePlayer.getSalvoes().size()).flatMap(x -> x.getSunkShips().stream()).map(Ship::getId).collect(toList()); // List<Long> shipsSunkByPlayer = new ArrayList<>(); // if (gamePlayer.getOpponent().isPresent()) { // shipsSunkByPlayer = gamePlayer.getOpponent().get().getSalvoes().stream().filter(x -> x.getTurn() == gamePlayer.getOpponent().get().getSalvoes().size()).flatMap(x -> x.getSunkShips().stream()).map(Ship::getId).collect(toList()); // } // return shipsSunkByPlayer.size() == 5 || shipsSunkByOpponent.size() == 5; // } //Function to help find if the user is authenticated or not private boolean isGuest(Authentication authentication) { return authentication == null || authentication instanceof AnonymousAuthenticationToken; } //Function to create a Json used in responses private Map<String, Object> makeMap(String key, Object value) { Map<String, Object> map = new HashMap<>(); map.put(key, value); return map; } }
UTF-8
Java
18,711
java
SalvoController.java
Java
[ { "context": "nseEntity<Object> register(\n\t\t@RequestParam String userName,\n\t\t@RequestParam String password\n\t) {\n\n\t\tif (user", "end": 1448, "score": 0.6695155501365662, "start": 1440, "tag": "USERNAME", "value": "userName" }, { "context": " = playerRepository.findByUserNam...
null
[]
package com.codeoftheweb.salvo.controllers; import com.codeoftheweb.salvo.models.*; import com.codeoftheweb.salvo.repositories.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @RestController @RequestMapping("/api") public class SalvoController { @Autowired private PlayerRepository playerRepository; @Autowired private GameRepository gameRepository; @Autowired private GamePlayerRepository gamePlayerRepository; @Autowired private ShipRepository shipRepository; @Autowired private SalvoRepository salvoRepository; @Autowired private ScoreRepository scoreRepository; @Autowired private PasswordEncoder passwordEncoder; @GetMapping("/players") public Set<Map<String, Object>> getPlayers() { return playerRepository.findAll().stream().map(this::makePlayerDTO).collect(toSet()); } @PostMapping("/players") public ResponseEntity<Object> register( @RequestParam String userName, @RequestParam String password ) { if (userName.isEmpty() || password.isEmpty()) { return new ResponseEntity<>("Missing data", HttpStatus.FORBIDDEN); } if (playerRepository.findByUserName(userName) != null) { return new ResponseEntity<>("Name already in use", HttpStatus.FORBIDDEN); } playerRepository.save(new Player(userName, passwordEncoder.encode(password))); return new ResponseEntity<>(HttpStatus.CREATED); } @GetMapping("/games") public Map<String, Object> getGames(Authentication authentication) { Map<String, Object> dto = new LinkedHashMap<>(); //Verify if user is authenticated or not if (!isGuest(authentication)) { Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); dto.put("player", makePlayerDTO(authenticatedPlayer)); } else { dto.put("player", null); } dto.put("games", gameRepository.findAll().stream().map(this::makeGameDTO).collect(toSet())); return dto; } //Function to create new game @PostMapping("/games") public ResponseEntity<Map<String, Object>> createGame(Authentication authentication) { if (!isGuest(authentication)) { LocalDateTime dateTime = LocalDateTime.now(); Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); //Procedure to create a new game: Game newGame = new Game(dateTime); gameRepository.save(newGame); GamePlayer newGamePlayer = new GamePlayer(dateTime, authenticatedPlayer, newGame); gamePlayerRepository.save(newGamePlayer); return new ResponseEntity<>(makeMap("gpid", newGamePlayer.getId()), HttpStatus.CREATED); } else { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } } //Function to join an existing game @PostMapping("/games/{gameId}/players") public ResponseEntity<Map<String,Object>> joinGame(@PathVariable Long gameId, Authentication authentication) { //Verify if user is authenticated or not if (isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } LocalDateTime dateTime = LocalDateTime.now(); Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<Game> optRequestedGame = gameRepository.findById(gameId); //Verify that the game exists if (optRequestedGame.isEmpty()) { return new ResponseEntity<>(makeMap("error", "The game you want to play does not exist."), HttpStatus.FORBIDDEN); } //Verify if the player is full or it have space for one more player Game requestedGame = optRequestedGame.get(); if (requestedGame.getGamePlayers().size() >= 2) { return new ResponseEntity<>(makeMap("error", "The game is full and you can't join it."), HttpStatus.FORBIDDEN); } //Verify if the existing player is not the authenticated player Optional<Player> existingPlayer = requestedGame.getPlayers().stream().findFirst(); if (!(existingPlayer.isPresent() && authenticatedPlayer.getId() != existingPlayer.get().getId())) { return new ResponseEntity<>(makeMap("error", "You are already in this game."), HttpStatus.FORBIDDEN); } //Procedure to join a game: GamePlayer newGamePlayer = new GamePlayer(dateTime, authenticatedPlayer, requestedGame); gamePlayerRepository.save(newGamePlayer); return new ResponseEntity<>(makeMap("gpid", newGamePlayer.getId()), HttpStatus.CREATED); } @GetMapping("/game_view/{gamePlayerId}") public ResponseEntity<Map<String, Object>> getGame(@PathVariable Long gamePlayerId, Authentication authentication) { //Verify if user is authenticated or not if(isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "That game does not correspond to any player."), HttpStatus.BAD_REQUEST); } //Verify if this player is playing the game requested. GamePlayer gamePlayer = optGamePlayer.get(); if(!(authenticatedPlayer.getId() == gamePlayer.getPlayer().getId())) { return new ResponseEntity<>(makeMap("error", "This is not your game. Don't try to cheat!"), HttpStatus.FORBIDDEN); } return new ResponseEntity<>(makeGameViewDTO(gamePlayer), HttpStatus.OK); /* Another way to do this: if(!isGuest(authentication)) { //Verify if user is authenticated or not Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); return optGamePlayer.map(gp -> { if(authenticatedPlayer.getId() == gp.getPlayer().getId()) { return new ResponseEntity<>(makeGameViewDTO(gp), HttpStatus.OK); } else { return new ResponseEntity<>(makeMap("error", "This is not your game. Don't try to cheat!"), HttpStatus.FORBIDDEN); } }) .orElse(new ResponseEntity<>(makeMap("error", "That game does not correspond to any player."), HttpStatus.BAD_REQUEST)); } else { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); }*/ } @PostMapping("/games/players/{gamePlayerId}/ships") public ResponseEntity<Map<String, Object>> locateShips(@PathVariable Long gamePlayerId, @RequestBody List<Ship> ships, Authentication authentication) { //Verify if user is authenticated or not if (isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "The gamePlayer requested does not exist."), HttpStatus.FORBIDDEN); } //Verify if this player is playing the game requested. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); GamePlayer gamePlayer = optGamePlayer.get(); if(authenticatedPlayer.getId() != gamePlayer.getPlayer().getId()) { return new ResponseEntity<>(makeMap("error", "This game does not correspond to this player."), HttpStatus.FORBIDDEN); } //Validate if the player has his ships placed. if (gamePlayer.getShips().size() == 5) { return new ResponseEntity<>(makeMap("error", "You've just located your ships."), HttpStatus.FORBIDDEN); } //Validate if the request contains 5 ships. if (ships.size() != 5) { return new ResponseEntity<>(makeMap("error", "The request does not contains 5 ships."), HttpStatus.FORBIDDEN); } //Save the ships corresponding to the authenticated player for this game for (Ship ship:ships) { shipRepository.save(new Ship(gamePlayer, ship.getType(), ship.getLocations())); } return new ResponseEntity<>(makeMap("gpid", gamePlayer.getId()), HttpStatus.CREATED); } @GetMapping("/games/players/{gamePlayerId}/salvoes") public ResponseEntity<Map<String, Object>> getSalvoes(@PathVariable Long gamePlayerId, Authentication authentication) { //Verify if user is authenticated or not if(isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "That game does not correspond to any player."), HttpStatus.BAD_REQUEST); } //Verify if this player is playing the game requested. GamePlayer gamePlayer = optGamePlayer.get(); if(!(authenticatedPlayer.getId() == gamePlayer.getPlayer().getId())) { return new ResponseEntity<>(makeMap("error", "This is not your game. Don't try to cheat!"), HttpStatus.FORBIDDEN); } return new ResponseEntity<>(makeGameViewDTO(gamePlayer), HttpStatus.OK); } @PostMapping("/games/players/{gamePlayerId}/salvoes") public ResponseEntity<Map<String, Object>> locateSalvoes(@PathVariable Long gamePlayerId, @RequestBody Salvo salvo, Authentication authentication) { //Verify if user is authenticated or not if (isGuest(authentication)) { return new ResponseEntity<>(makeMap("error", "You are not logged in!"), HttpStatus.UNAUTHORIZED); } //Verify if this combination of game and player (gamePlayer) exists. Optional<GamePlayer> optGamePlayer = gamePlayerRepository.findById(gamePlayerId); if (optGamePlayer.isEmpty()) { return new ResponseEntity<>(makeMap("error", "The gamePlayer requested does not exist."), HttpStatus.FORBIDDEN); } //Verify if this player is playing the game requested. Player authenticatedPlayer = playerRepository.findByUserName(authentication.getName()); GamePlayer gamePlayer = optGamePlayer.get(); if(authenticatedPlayer.getId() != gamePlayer.getPlayer().getId()) { return new ResponseEntity<>(makeMap("error", "This game does not correspond to this player."), HttpStatus.FORBIDDEN); } //Validate if the player has not fired all the salvoes. if (gamePlayer.getSalvoes().size() > 20) { return new ResponseEntity<>(makeMap("error", "You've just fired all your salvoes."), HttpStatus.FORBIDDEN); } //Validate if the request contains 5 shots. if (salvo.getLocations().size() != 5) { return new ResponseEntity<>(makeMap("error", "The request does not contains 5 shots."), HttpStatus.FORBIDDEN); } //Validate if the opponent has shot his salvo and it is the turn of the player. if (gamePlayer.getOpponent().isEmpty()) { return new ResponseEntity<>(makeMap("error", "There is no opponent yet."), HttpStatus.FORBIDDEN); } if (gamePlayer.getSalvoes().size() - gamePlayer.getOpponent().get().getSalvoes().size() >= 1) { return new ResponseEntity<>(makeMap("error", "You must wait for your opponent to make his shots."), HttpStatus.FORBIDDEN); } if (gamePlayer.gameStatus() == GameStatus.PLACE_SALVOES) { Salvo actualSalvo = new Salvo(gamePlayer, salvo.getTurn(), salvo.getLocations()); salvoRepository.save(actualSalvo); gamePlayer.getSalvoes().add(actualSalvo); if (gamePlayer.gameStatus() == GameStatus.TIE) { scoreRepository.save(new Score(0.5, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getPlayer())); scoreRepository.save(new Score(0.5, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getOpponent().get().getPlayer())); } else if (gamePlayer.gameStatus() == GameStatus.WIN) { scoreRepository.save(new Score(1.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getPlayer())); scoreRepository.save(new Score(0.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getOpponent().get().getPlayer())); } else if (gamePlayer.gameStatus() == GameStatus.LOSE) { scoreRepository.save(new Score(0.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getPlayer())); scoreRepository.save(new Score(1.0, LocalDateTime.now(), gamePlayer.getGame(), gamePlayer.getOpponent().get().getPlayer())); } return new ResponseEntity<>(makeMap("turn", salvo.getTurn()), HttpStatus.CREATED); } //Save the salvoes corresponding to the authenticated player for this turn in this game salvoRepository.save(new Salvo(gamePlayer, salvo.getTurn(), salvo.getLocations())); return new ResponseEntity<>(makeMap("gpid", gamePlayer.getId()), HttpStatus.CREATED); } public Map<String, Object> makeGamesDTO(Game game) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", game.getId()); dto.put("date", game.getDateTime()); dto.put("gamePlayers", game.getGamePlayers().stream().map(this::makeGamePlayerDTO).collect(toSet())); return dto; } public Map<String, Object> makeGameDTO(Game game) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", game.getId()); dto.put("date", game.getDateTime()); dto.put("gamePlayers", game.getGamePlayers().stream().map(this::makeGamePlayerDTO).collect(toSet())); return dto; } //game_view public Map<String, Object> makeGameViewDTO(GamePlayer gamePlayer) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", gamePlayer.getGame().getId()); dto.put("date", gamePlayer.getGame().getDateTime()); dto.put("gameStatus", gamePlayer.gameStatus()); dto.put("gamePlayers", gamePlayer.getGame().getGamePlayers().stream().map(this::makeGamePlayerDTO).collect(toSet())); dto.put("ships", gamePlayer.getShips().stream().map(this::makeShipDTO).collect(toSet())); dto.put("salvoes", gamePlayer.getGame().getGamePlayers().stream().flatMap(elem -> elem.getSalvoes().stream().map(this::makeSalvoDTO))); dto.put("hits", gamePlayer.getSalvoes().stream().map(this::makeHitsDTO)); dto.put("sunkShips", gamePlayer.getSalvoes().stream().map(this::makeSunkShipsDTO)); dto.put("opponentHits", gamePlayer.getOpponent().map(gp -> gp.getSalvoes().stream().map(this::makeHitsDTO).collect(toList())).orElse(new ArrayList<>())); dto.put("opponentSunks", gamePlayer.getOpponent().map(gp -> gp.getSalvoes().stream().map(this::makeSunkShipsDTO).collect(toList())).orElse(new ArrayList<>())); return dto; } //game_view/gamePlayer private Map<String, Object> makeGamePlayerDTO(GamePlayer gamePlayer) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("gpid", gamePlayer.getId()); dto.put("player", makePlayerDTO(gamePlayer.getPlayer())); dto.put("score", gamePlayer.getScore().map(Score::getScore).orElse(null)); return dto; } //game_view/gamePlayer/player private Map<String, Object> makePlayerDTO(Player player) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("id", player.getId()); dto.put("email", player.getUserName()); return dto; } //game_view/gamePlayer/ships private Map<String, Object> makeShipDTO(Ship ship) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("type", ship.getType()); dto.put("locations", ship.getLocations()); return dto; } //game_view/gamePlayer/salvoes private Map<String, Object> makeSalvoDTO(Salvo salvo) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("playerId", salvo.getGamePlayer().getPlayer().getId()); dto.put("turn", salvo.getTurn()); dto.put("locations", salvo.getLocations()); return dto; } //game_view/gamePlayer/hits private Map<String, Object> makeHitsDTO(Salvo salvo) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("turn", salvo.getTurn()); dto.put("locationsWithImpact", salvo.getHits()); return dto; } private Map<String, Object> makeSunkShipsDTO(Salvo salvo) { Map<String, Object> dto = new LinkedHashMap<>(); dto.put("turn", salvo.getTurn()); dto.put("ships", salvo.getSunkShips().stream().map(this::makeShipDTO)); return dto; } // public String gameStatus(GamePlayer gamePlayer) { // // if (this.isGameOver(gamePlayer)) { // return "game over"; // } else { // if (gamePlayer.getOpponent().isEmpty()) { // return "waiting for opponent to join the game"; // } // if (gamePlayer.getShips().isEmpty()) { // return "waiting for player to place ships"; // } // if (gamePlayer.getOpponent().get().getShips().isEmpty()) { // return "waiting for opponent to place ships"; // } // if (gamePlayer.getSalvoes().stream().filter(s -> s.getTurn() == gamePlayer.getSalvoes().size()).count() == 0) { // return "waiting for player salvo"; // } // if (gamePlayer.getOpponent().get().getSalvoes().stream().filter(x -> x.getTurn() == gamePlayer.getSalvoes().size()).count() == 0) { // return "waiting for opponent salvo"; // } // return "playing game"; // } // } // // Boolean isGameOver(GamePlayer gamePlayer) { // List<Long> shipsSunkByOpponent = gamePlayer.getSalvoes().stream().filter(x -> x.getTurn() == gamePlayer.getSalvoes().size()).flatMap(x -> x.getSunkShips().stream()).map(Ship::getId).collect(toList()); // List<Long> shipsSunkByPlayer = new ArrayList<>(); // if (gamePlayer.getOpponent().isPresent()) { // shipsSunkByPlayer = gamePlayer.getOpponent().get().getSalvoes().stream().filter(x -> x.getTurn() == gamePlayer.getOpponent().get().getSalvoes().size()).flatMap(x -> x.getSunkShips().stream()).map(Ship::getId).collect(toList()); // } // return shipsSunkByPlayer.size() == 5 || shipsSunkByOpponent.size() == 5; // } //Function to help find if the user is authenticated or not private boolean isGuest(Authentication authentication) { return authentication == null || authentication instanceof AnonymousAuthenticationToken; } //Function to create a Json used in responses private Map<String, Object> makeMap(String key, Object value) { Map<String, Object> map = new HashMap<>(); map.put(key, value); return map; } }
18,711
0.719096
0.717653
431
42.412994
40.135517
232
false
false
0
0
0
0
0
0
2.201856
false
false
13
9da6e4a9e21460df34702390a2af5f3bf09e0ea6
14,731,737,833,687
045a38d3c4a7240e81f069508832373b0b21c6fd
/src/edu/cs3500/spreadsheets/model/Worksheet.java
4eabc5c37ed283b57c9bde8b30cf57abde603833
[]
no_license
jenright99/SpreadsheetProgram
https://github.com/jenright99/SpreadsheetProgram
875db570458adee4cc06b687a21e3bbdbb9b7d8d
c600f9f69aac6b77854654875f0ca2934654883d
refs/heads/main
2023-08-18T23:07:07.995000
2021-10-06T22:20:26
2021-10-06T22:20:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.cs3500.spreadsheets.model; import edu.cs3500.spreadsheets.sexp.Parser; import edu.cs3500.spreadsheets.sexp.SSymbol; import edu.cs3500.spreadsheets.sexp.Sexp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Represents an {@link IWorksheet} which uses {@link Coord}s to store cells and communicates values * with {@link Sexp}s. */ public class Worksheet implements IWorksheet<Coord, Sexp> { private HashMap<Coord, ICell> cells; private HashMap<Coord, Sexp> values; private HashMap<Coord, Boolean> cyclical; /** * Instantiates the cells, values, anc cyclical checking. */ public Worksheet() { this.cells = new HashMap<Coord, ICell>(); this.values = new HashMap<Coord, Sexp>(); this.cyclical = new HashMap<Coord, Boolean>(); } /** * Returns if the given Coord is referenced in the given Coordinates references. * * @param coord the coord we are searching for. * @param contents the references we are searching. * @return whether the given coord is contained in the given Coordinate references. */ private boolean checkCyclical(Coord coord, List<Coord> contents) { if (this.cyclical.containsKey(coord)) { return this.cyclical.get(coord); } else { boolean result = breadthFirstSearch(coord, contents); this.cyclical.put(coord, result); return result; } } /** * Preforms a breadth first search to see if the given {@link Coord} is in given Coordinate * references. * * @param coord the coord we are searching for. * @param contents the references we are searching. * @return whether the given coord is contained in the given Coordinate references. */ private boolean breadthFirstSearch(Coord coord, List<Coord> contents) { for (Coord c : contents) { if (c.equals(coord)) { return true; } } for (Coord c : contents) { if (this.containsCell(c) && this.checkCyclical(coord, this.cells.get(c).referencedCoords())) { return true; } } //this.cyclical.put(coord, false); return false; } @Override public void addCell(int col, int row, String contents) { this.values = new HashMap<Coord, Sexp>(); Coord newCoord = new Coord(col, row); if (this.cyclical.containsKey(newCoord)) { this.cyclical.remove(newCoord); } IFormula cellContents; try { if (contents.charAt(0) == '=') { cellContents = Parser.parse(contents.substring(1)).accept(new FormulaCreator(this)); } else { cellContents = new IdentityFormula(Parser.parse(contents)); } if (this.checkCyclical(newCoord, cellContents.referencedCoords())) { cellContents = new IdentityFormula(new SSymbol("#ERROR")); this.cyclical.put(newCoord, true); } else { this.cyclical.put(newCoord, false); } } catch (IllegalArgumentException iae) { cellContents = new IdentityFormula(new SSymbol("#ERROR")); } if (this.containsCell(newCoord)) { this.cells.replace(newCoord, new Cell(cellContents, contents)); } else { this.cells.put(newCoord, new Cell(cellContents, contents)); } } @Override public boolean containsCell(Coord coord) { return cells.containsKey(coord); } @Override public String getValueAt(int col, int row) { return this.getValueAt(new Coord(col, row)).accept(new FormatedSexpString()); } @Override public Sexp getValueAt(Coord coord) { if (this.containsCell(coord)) { if (this.values.containsKey(coord)) { return this.values.get(coord); } if (this.cyclical.containsKey(coord) && this.cyclical.get(coord)) { throw new IllegalArgumentException( "Error in cell " + coord.toString() + ": Cyclical Cell."); } Sexp newValue = this.cells.get(coord).evaluate(); this.values.put(coord, newValue); return newValue; } return new SSymbol(""); } @Override public String getContents(int col, int row) { return this.getContents(new Coord(col, row)); } @Override public String getContents(Coord coord) { if (this.cells.containsKey(coord)) { return this.cells.get(coord).originalFormula(); } return ""; } @Override public int numberOfCells() { return this.cells.size(); } @Override public void remove(int col, int row) { Coord newCoord = new Coord(col, row); if (this.containsCell(newCoord)) { this.cells.remove(newCoord); this.values = new HashMap<Coord, Sexp>(); this.cyclical.remove(newCoord); } } @Override public List<Coord> nonEmptyCoords() { return new ArrayList<Coord>(this.cells.keySet()); } }
UTF-8
Java
4,737
java
Worksheet.java
Java
[]
null
[]
package edu.cs3500.spreadsheets.model; import edu.cs3500.spreadsheets.sexp.Parser; import edu.cs3500.spreadsheets.sexp.SSymbol; import edu.cs3500.spreadsheets.sexp.Sexp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Represents an {@link IWorksheet} which uses {@link Coord}s to store cells and communicates values * with {@link Sexp}s. */ public class Worksheet implements IWorksheet<Coord, Sexp> { private HashMap<Coord, ICell> cells; private HashMap<Coord, Sexp> values; private HashMap<Coord, Boolean> cyclical; /** * Instantiates the cells, values, anc cyclical checking. */ public Worksheet() { this.cells = new HashMap<Coord, ICell>(); this.values = new HashMap<Coord, Sexp>(); this.cyclical = new HashMap<Coord, Boolean>(); } /** * Returns if the given Coord is referenced in the given Coordinates references. * * @param coord the coord we are searching for. * @param contents the references we are searching. * @return whether the given coord is contained in the given Coordinate references. */ private boolean checkCyclical(Coord coord, List<Coord> contents) { if (this.cyclical.containsKey(coord)) { return this.cyclical.get(coord); } else { boolean result = breadthFirstSearch(coord, contents); this.cyclical.put(coord, result); return result; } } /** * Preforms a breadth first search to see if the given {@link Coord} is in given Coordinate * references. * * @param coord the coord we are searching for. * @param contents the references we are searching. * @return whether the given coord is contained in the given Coordinate references. */ private boolean breadthFirstSearch(Coord coord, List<Coord> contents) { for (Coord c : contents) { if (c.equals(coord)) { return true; } } for (Coord c : contents) { if (this.containsCell(c) && this.checkCyclical(coord, this.cells.get(c).referencedCoords())) { return true; } } //this.cyclical.put(coord, false); return false; } @Override public void addCell(int col, int row, String contents) { this.values = new HashMap<Coord, Sexp>(); Coord newCoord = new Coord(col, row); if (this.cyclical.containsKey(newCoord)) { this.cyclical.remove(newCoord); } IFormula cellContents; try { if (contents.charAt(0) == '=') { cellContents = Parser.parse(contents.substring(1)).accept(new FormulaCreator(this)); } else { cellContents = new IdentityFormula(Parser.parse(contents)); } if (this.checkCyclical(newCoord, cellContents.referencedCoords())) { cellContents = new IdentityFormula(new SSymbol("#ERROR")); this.cyclical.put(newCoord, true); } else { this.cyclical.put(newCoord, false); } } catch (IllegalArgumentException iae) { cellContents = new IdentityFormula(new SSymbol("#ERROR")); } if (this.containsCell(newCoord)) { this.cells.replace(newCoord, new Cell(cellContents, contents)); } else { this.cells.put(newCoord, new Cell(cellContents, contents)); } } @Override public boolean containsCell(Coord coord) { return cells.containsKey(coord); } @Override public String getValueAt(int col, int row) { return this.getValueAt(new Coord(col, row)).accept(new FormatedSexpString()); } @Override public Sexp getValueAt(Coord coord) { if (this.containsCell(coord)) { if (this.values.containsKey(coord)) { return this.values.get(coord); } if (this.cyclical.containsKey(coord) && this.cyclical.get(coord)) { throw new IllegalArgumentException( "Error in cell " + coord.toString() + ": Cyclical Cell."); } Sexp newValue = this.cells.get(coord).evaluate(); this.values.put(coord, newValue); return newValue; } return new SSymbol(""); } @Override public String getContents(int col, int row) { return this.getContents(new Coord(col, row)); } @Override public String getContents(Coord coord) { if (this.cells.containsKey(coord)) { return this.cells.get(coord).originalFormula(); } return ""; } @Override public int numberOfCells() { return this.cells.size(); } @Override public void remove(int col, int row) { Coord newCoord = new Coord(col, row); if (this.containsCell(newCoord)) { this.cells.remove(newCoord); this.values = new HashMap<Coord, Sexp>(); this.cyclical.remove(newCoord); } } @Override public List<Coord> nonEmptyCoords() { return new ArrayList<Coord>(this.cells.keySet()); } }
4,737
0.6578
0.654
175
26.068571
25.569756
100
false
false
0
0
0
0
0
0
0.48
false
false
13
40de9e346ecc9030eabc460defdfc559ebf61cf2
31,868,657,337,614
a7bbd39832e82859abd9a6aff7b028bcc232d984
/src/WorkflowBuilder/TestComplexWorfklow.java
31629660c00b16f4cdd31f08a3fff73fe1deda0f
[ "Apache-2.0" ]
permissive
ZiyanHan/ERframework
https://github.com/ZiyanHan/ERframework
7362e2f8c43ba46188296a42d5f8bc803fef3c08
f5d5e3c363fc5029bba57b75ed1e93b72687ba60
refs/heads/master
2020-06-13T01:48:42.990000
2019-06-30T09:16:31
2019-06-30T09:16:31
194,492,908
0
0
Apache-2.0
true
2019-06-30T08:28:04
2019-06-30T08:28:04
2018-03-14T18:39:49
2018-03-14T18:39:48
14,904
0
0
0
null
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 WorkflowBuilder; import BlockProcessing.ComparisonRefinement.CardinalityNodePruning; import BlockProcessing.IBlockProcessing; import DataModel.AbstractBlock; import DataModel.SimilarityPairs; import EntityClustering.CenterClustering; import EntityClustering.IEntityClustering; import EntityClustering.UniqueMappingClustering; import EntityMatching.AbstractEntityMatching; import EntityMatching.IEntityMatching; import EntityMatching.ProfileMatcher; import Utilities.Enumerations.BlockBuildingMethod; import Utilities.Enumerations.RepresentationModel; import Utilities.Enumerations.SimilarityMetric; import Utilities.Enumerations.WeightingScheme; import java.util.Arrays; import java.util.HashSet; /** * * @author VASILIS */ public class TestComplexWorfklow { public static void main (String[] args) { //set data final String basePath = "C:\\Users\\VASILIS\\Documents\\OAEI_Datasets\\OAEI2010\\restaurant\\"; String dataset1 = basePath+"restaurant1Profiles"; String dataset2 = basePath+"restaurant2Profiles"; String datasetGroundtruth = basePath+"restaurantIdDuplicates"; if (args.length == 3) { dataset1 = args[0]; dataset2 = args[1]; datasetGroundtruth = args[2]; } String[] acceptableTypes = { // "http://www.okkam.org/ontology_person1.owl#Person", // "http://www.okkam.org/ontology_person2.owl#Person", "http://www.okkam.org/ontology_restaurant1.owl#Restaurant", "http://www.okkam.org/ontology_restaurant2.owl#Restaurant", // "http://www.bbc.co.uk/ontologies/creativework/NewsItem", // "http://www.bbc.co.uk/ontologies/creativework/BlogPost", // "http://www.bbc.co.uk/ontologies/creativework/Programme", // "http://www.bbc.co.uk/ontologies/creativework/CreativeWork" }; //set parameters BlockBuildingMethod blockingWorkflow1 = BlockBuildingMethod.STANDARD_BLOCKING; BlockBuildingMethod blockingWorkflow2 = BlockBuildingMethod.NEIGHBOR_BLOCKING; IBlockProcessing metaBlocking1 = new CardinalityNodePruning(WeightingScheme.CBS); IBlockProcessing metaBlocking2 = new CardinalityNodePruning(WeightingScheme.CBS); AbstractEntityMatching similarity = new ProfileMatcher(RepresentationModel.CHARACTER_BIGRAM_GRAPHS); IEntityClustering clustering = new UniqueMappingClustering(); AbstractComplexWorkflowBuilder complex = new ComplexWorkflow( dataset1, dataset2, datasetGroundtruth, blockingWorkflow1, blockingWorkflow2, metaBlocking1, metaBlocking2, similarity, clustering); complex.loadData(); complex.runBlocking(); complex.runMetaBlocking(); /* RepresentationModel[] repModels = { RepresentationModel.TOKEN_UNIGRAMS, RepresentationModel.CHARACTER_BIGRAMS, RepresentationModel.CHARACTER_TRIGRAMS, RepresentationModel.TOKEN_UNIGRAM_GRAPHS, RepresentationModel.CHARACTER_BIGRAM_GRAPHS, RepresentationModel.CHARACTER_TRIGRAM_GRAPHS}; double bestPrecision=0, bestRecall=0, bestFmeasure=0, bestThreshold=0; RepresentationModel bestRepresentation= null; SimilarityMetric bestSimilarityMetric = null; for (RepresentationModel repModel : repModels) { for (SimilarityMetric simMetric : SimilarityMetric.getModelCompatibleSimMetrics(repModel)) { similarity = new ProfileMatcher(repModel, simMetric); if (acceptableTypes.length > 0) { similarity.setAcceptableTypes(new HashSet<>(Arrays.asList(acceptableTypes))); } complex.setSimilarityMethod(similarity); SimilarityPairs simPairs = complex.runSimilarityComputations(); for (double sim_threshold = 0.2; sim_threshold < 0.9; sim_threshold += 0.2) { complex.setClusteringMethod(new UniqueMappingClustering()); complex.setSimilarity_threshold(sim_threshold); //System.out.println(full); complex.runClustering(simPairs); double fMeasure = complex.getFMeasure(); if (fMeasure > bestFmeasure) { bestPrecision = complex.getPrecision(); bestRecall = complex.getRecall(); bestThreshold = sim_threshold; bestFmeasure = fMeasure; bestRepresentation = repModel; bestSimilarityMetric = simMetric; } } } } System.out.println("\n\nBest results were for the settings:"); System.out.println("Representation model: "+bestRepresentation); System.out.println("Similarity metric: "+bestSimilarityMetric); System.out.println("similarity threshold: "+bestThreshold); System.out.println("Precision: "+bestPrecision); System.out.println("Recall: "+bestRecall); System.out.println("F-measure: "+bestFmeasure); */ // full.runWorkflow(); } }
UTF-8
Java
6,234
java
TestComplexWorfklow.java
Java
[ { "context": "\r\nimport java.util.HashSet;\r\n\r\n/**\r\n *\r\n * @author VASILIS\r\n */\r\npublic class TestComplexWorfklow {\r\n \r\n ", "end": 943, "score": 0.9816004037857056, "start": 936, "tag": "NAME", "value": "VASILIS" } ]
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 WorkflowBuilder; import BlockProcessing.ComparisonRefinement.CardinalityNodePruning; import BlockProcessing.IBlockProcessing; import DataModel.AbstractBlock; import DataModel.SimilarityPairs; import EntityClustering.CenterClustering; import EntityClustering.IEntityClustering; import EntityClustering.UniqueMappingClustering; import EntityMatching.AbstractEntityMatching; import EntityMatching.IEntityMatching; import EntityMatching.ProfileMatcher; import Utilities.Enumerations.BlockBuildingMethod; import Utilities.Enumerations.RepresentationModel; import Utilities.Enumerations.SimilarityMetric; import Utilities.Enumerations.WeightingScheme; import java.util.Arrays; import java.util.HashSet; /** * * @author VASILIS */ public class TestComplexWorfklow { public static void main (String[] args) { //set data final String basePath = "C:\\Users\\VASILIS\\Documents\\OAEI_Datasets\\OAEI2010\\restaurant\\"; String dataset1 = basePath+"restaurant1Profiles"; String dataset2 = basePath+"restaurant2Profiles"; String datasetGroundtruth = basePath+"restaurantIdDuplicates"; if (args.length == 3) { dataset1 = args[0]; dataset2 = args[1]; datasetGroundtruth = args[2]; } String[] acceptableTypes = { // "http://www.okkam.org/ontology_person1.owl#Person", // "http://www.okkam.org/ontology_person2.owl#Person", "http://www.okkam.org/ontology_restaurant1.owl#Restaurant", "http://www.okkam.org/ontology_restaurant2.owl#Restaurant", // "http://www.bbc.co.uk/ontologies/creativework/NewsItem", // "http://www.bbc.co.uk/ontologies/creativework/BlogPost", // "http://www.bbc.co.uk/ontologies/creativework/Programme", // "http://www.bbc.co.uk/ontologies/creativework/CreativeWork" }; //set parameters BlockBuildingMethod blockingWorkflow1 = BlockBuildingMethod.STANDARD_BLOCKING; BlockBuildingMethod blockingWorkflow2 = BlockBuildingMethod.NEIGHBOR_BLOCKING; IBlockProcessing metaBlocking1 = new CardinalityNodePruning(WeightingScheme.CBS); IBlockProcessing metaBlocking2 = new CardinalityNodePruning(WeightingScheme.CBS); AbstractEntityMatching similarity = new ProfileMatcher(RepresentationModel.CHARACTER_BIGRAM_GRAPHS); IEntityClustering clustering = new UniqueMappingClustering(); AbstractComplexWorkflowBuilder complex = new ComplexWorkflow( dataset1, dataset2, datasetGroundtruth, blockingWorkflow1, blockingWorkflow2, metaBlocking1, metaBlocking2, similarity, clustering); complex.loadData(); complex.runBlocking(); complex.runMetaBlocking(); /* RepresentationModel[] repModels = { RepresentationModel.TOKEN_UNIGRAMS, RepresentationModel.CHARACTER_BIGRAMS, RepresentationModel.CHARACTER_TRIGRAMS, RepresentationModel.TOKEN_UNIGRAM_GRAPHS, RepresentationModel.CHARACTER_BIGRAM_GRAPHS, RepresentationModel.CHARACTER_TRIGRAM_GRAPHS}; double bestPrecision=0, bestRecall=0, bestFmeasure=0, bestThreshold=0; RepresentationModel bestRepresentation= null; SimilarityMetric bestSimilarityMetric = null; for (RepresentationModel repModel : repModels) { for (SimilarityMetric simMetric : SimilarityMetric.getModelCompatibleSimMetrics(repModel)) { similarity = new ProfileMatcher(repModel, simMetric); if (acceptableTypes.length > 0) { similarity.setAcceptableTypes(new HashSet<>(Arrays.asList(acceptableTypes))); } complex.setSimilarityMethod(similarity); SimilarityPairs simPairs = complex.runSimilarityComputations(); for (double sim_threshold = 0.2; sim_threshold < 0.9; sim_threshold += 0.2) { complex.setClusteringMethod(new UniqueMappingClustering()); complex.setSimilarity_threshold(sim_threshold); //System.out.println(full); complex.runClustering(simPairs); double fMeasure = complex.getFMeasure(); if (fMeasure > bestFmeasure) { bestPrecision = complex.getPrecision(); bestRecall = complex.getRecall(); bestThreshold = sim_threshold; bestFmeasure = fMeasure; bestRepresentation = repModel; bestSimilarityMetric = simMetric; } } } } System.out.println("\n\nBest results were for the settings:"); System.out.println("Representation model: "+bestRepresentation); System.out.println("Similarity metric: "+bestSimilarityMetric); System.out.println("similarity threshold: "+bestThreshold); System.out.println("Precision: "+bestPrecision); System.out.println("Recall: "+bestRecall); System.out.println("F-measure: "+bestFmeasure); */ // full.runWorkflow(); } }
6,234
0.579403
0.573147
136
43.838234
30.114054
108
false
false
0
0
0
0
0
0
0.669118
false
false
13
60232d95ce734cbc9a0f1db3e38c08da8ea3e32c
19,653,770,356,757
a52c2ac30cd10969dbf418e49d082b9984b40bf5
/vcs-pml/pml-service/src/main/java/com/channel4/nc/services/pml/epg/dao/EpgServiceDao.java
faa4dba4dfb10aa75450533dafc0dc141bea0f87
[]
no_license
jracero/testProject
https://github.com/jracero/testProject
32bb8c687f616a403ff02a41a952f30174eb4cf7
c8f7e3d231b10c0b1c5ca685a80817ff2c377f5d
refs/heads/master
2016-08-10T14:36:16.806000
2015-11-26T14:12:34
2015-11-26T14:12:34
46,866,937
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.channel4.nc.services.pml.epg.dao; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import com.channel4.common.core.enums.Channel; import com.channel4.nc.services.pml.model.SlotData; import com.channel4.nc.services.pml.model.SlotEpisodeDTO; import com.channel4.nc.services.pml.model.SlotIndicatorData; /** * DAO service exposing available EPG DAO Service methods. * */ public interface EpgServiceDao { /** * Retrieves next programme slot details for given brand, fromDate and * fromTime * * @param brandKey * @param fromDateTime * @param repeatsOkay * @return SlotData */ SlotData findNextSlotData(Long brandKey, Date fromDateTime, boolean repeatsOkay); /** * Retrieves next programme slot details for the given brand, channel which * datetime is in the given window (fromDateTime, fromDateTime + * windowInDays) regardless the repeat flag. * * @param brandKey * @param fromDateTime * @param channelId * @param windowInDays * @return */ SlotData findNextSlotDataByChannelWithinWindow(Long brandKey, String channelId, Date fromDateTime, int windowInDays); /** * Retrieves future programme slot details for given brand, fromDate and * fromTime * * @param brandWebSafeTitle * @param fromDateTime * @return SlotData */ List<SlotData> findNextSlotsForBrandIncludeRepeats(final String brandWebSafeTitle, final Date fromDateTime); /** * Retrieves next programme slot details for given brand, channel, fromDate * and fromTime * * @param brandKey * @param channelId * @param fromDateTime * @return SlotData */ SlotData findNextSlotDataByChannel(Long brandKey, String channelId, Date fromDateTime); /** * Retrieves last programme slot details for given brand, fromDate and * fromTime * * @param brandKey * @param fromDateTime * @param earliestDateTime * @param repeatsOkay * @return SlotData */ SlotData findLastSlotData(Long brandKey, Date fromDateTime, Date earliestDateTime, boolean repeatsOkay); /** * Retrieves last programme slot details for given brand, channel, fromDate * and fromTime * * @param brandKey * @param channelId * @param fromDateTime * @return SlotData */ SlotData findLastSlotDataByChannel(Long brandKey, String channelId, Date fromDateTime); /** * Retrieves lists of slot indicators for a list of slot keys. * * @param slotKeys * @return Map<Long, List<SlotIndicatorData>> */ Map<Long, List<SlotIndicatorData>> findAllSlotIndicatorsBySlotKeys(List<Long> slotKeys); /** * Retrieves lists of simulcast rights on various platforms for a list of * slot keys. * * @param slotKeys * @return Map<Long, Set<Long>> */ Map<Long, Set<Long>> findSimulcastRightsBySlotKeys(final List<Long> slotKeys); /** * Retrieves next programme slot details for given series, fromDate and * fromTime * * @param seriesKey * @param fromDateTime * @return SlotData */ SlotData findNextSlotForSeries(Long seriesKey, Date fromDateTime); /** * Retrieves last programme slot details for given series, fromDate and * fromTime * * @param seriesKey * @param fromDateTime * @return SlotData */ SlotData findLastSlotForSeries(Long seriesKey, Date fromDateTime); /** * Retrieves all slots for a given channel and date. Note that B-S-E * information will be returned for the given 'platformKey', 'channelId' and * 'date' where available, but where this is not available the standard slot * information will be returned instead. * * @param platformKey * @param channelId * @param date * @return List<SlotData> */ List<SlotData> findAllSlots(Long platformKey, String channelId, Date date); /** * Retrieves all slots for a given channel and date and the simulcast rights * for the slots. * * @param platformKey * - a platform key. * @param channelId * - a channelId. * @param date * - a date. * * @return a list containing all the slots or an empty list there are no * slots for the given date. * * @see #findAllSlots(Long, String, Date); */ List<SlotData> findAllSlotsWithSimulcastInfo(Long platformKey, String channelId, Date date); /** * Retrieves next programme slot details for given series, channel, fromDate * and fromTime * * @param seriesKey * @param fromDateTime * @param channelId * @return SlotData */ SlotData findNextSlotForSeriesByChannel(Long seriesKey, String channelId, Date fromDateTime); /** * Retrieves last programme slot details for given series, channel, fromDate * and fromTime * * @param seriesKey * @param fromDateTime * @param channelId * * @return SlotData */ SlotData findLastSlotForSeriesByChannel(Long seriesKey, String channelId, Date fromDateTime); /** * Retrieves slots for home page with duration greater than given * minDuration * * @param platformKey * @param channelId * @param minDuration * minimum slot duration * @param maxSlots * maximum number of slots to be returned * @param fromDateTime * @return List<SlotData> */ List<SlotData> findMinimumDurationSlotsByChannel(Long platformKey, String channelId, Date fromDateTime, Integer minDuration, Integer maxSlots); /** * Retrieves currently showing programme slot details for given channel * * @param platformKey * @param channelId * @param giveTime * @return SlotData */ SlotData findNowSlotForChannel(Long platformKey, Channel channelId, Date giveTime); /** * Does this brand have a slot */ boolean findHasSlotForBrand(Long brandKey); /** * Retrieves Map with slots first broadcast information keyed by episode * programme id. * * NOTE: If an episode is repeated (i.e. More than one slots for given * programme id exist in the database), first slot is returned using slot * date and time ordering * * @param platformKey * @param programmeIds * @return Map<programmeId, SlotDTO> */ Map<String, SlotDTO> findSlotsWithFirstBroadcastInfo(Long platformKey, List<String> programmeIds); /** * Retrieves Map with all slots information keyed by episode programme id * for given programme id's, slot date's and channel name's * * NOTE: If an episode is repeated (i.e. More than one slots for given * programme id, slot date and channel exist in the database), first slot of * the day will be returned * * @param platformKey * @param programmeIds * @param slotDates * @param channelNames * @return Map<programmeId, SlotDTO> */ Map<String, SlotDTO> findAllSlots(Long platformKey, List<String> programmeIds, List<Date> slotDates, List<String> channelNames); /** * Finds next on slots from given date and time for a specific episode * * @param platformKey * @param programmeId * @param fromDateTime * @return list of next on slots */ List<SlotData> findNextSlotsForEpisode(Long platformKey, String programmeId, Date fromDateTime); /** * Finds next on slots from given date and time for a specific episode and * channel * * @param platformKey * @param programmeId * @param channelId * @param fromDateTime * @return list of next on slots */ List<SlotData> findNextSlotsForEpisodeByChannel(Long platformKey, String programmeId, String channelId, Date fromDateTime); /** * Finds last on slot information from given date and time for a specific * episode * * @param platformKey * @param programmeId * @param fromDateTime * @return last on slot */ SlotData findLastSlotForEpisode(Long platformKey, String programmeId, Date fromDateTime); /** * Finds last on slots from given date and time for a specific episode and * channel * * @param platformKey * @param programmeId * @param channelId * @param fromDateTime * @return last on slots */ SlotData findLastSlotForEpisodeByChannel(Long platformKey, String programmeId, String channelId, Date fromDateTime); /** * Finds first on slot information from given date and time for a specific * episode * * @param platformKey * @param programmeId * @param fromDateTime * @return first on slot */ SlotData findFirstOnSlotForEpisode(Long platformKey, String programmeId, Date fromDateTime); /** * Finds first on slot information from given date and time for a specific * episode and channel * * @param platformKey * @param programmeId * @param channelId * @param fromDateTime * @return first on slot */ SlotData findFirstOnSlotForEpisodeByChannel(Long platformKey, String programmeId, String channelId, Date fromDateTime); /** * Used for brand epg page atom feed * * @param platformKey * @param programmeIds * @param cutOffDate * @return */ List<SlotData> findNextSlotsForEpisodes(Long platformKey, List<String> programmeIds, Date cutOffDate); /** * Looks in the future (i.e. after currentDate) to find at most maxSlots * active and unsuspended series slots of non-flattened and active brands * whose episodes have never been aired in the past. * * @param platformKey * @param currentDate * @param maxSlots * @return at most maxSlots upcoming series slots */ List<SeriesPromotionalItemDTO> findUpcomingSeriesSlots(Long platformKey, Date currentDate, Integer maxSlots); /** * Retrieves the list of current slots for channel. * * @return A list of slots. An empty list if there're no slots for the * current time, channel or platform. */ List<SlotData> findAllNowSlotsForChannel(Long platformKey, Channel channel, Date givenTime); /** * Returns the slots, satisfying the "Coming Soon" business rules, applied * for all brand categories. * * @param platformKey * Key of the platform for which will be performed the search. * * @return A list of slots satisfying the "Coming Soon" business rule. */ List<SlotDTO> findComingSoonSlots(Long platformKey); /** * Returns the slots, satisfying the "Coming Soon" business rules selected * by brand category. * * <p> * ATTENTION: Note that the category name should be URI-compliant, i.e. no * adjustments like converting to lower case for example will take place * before querying the database. * </p> * * @param platformKey * Key of the platform for which will be performed the search. * @param brandCategoryWst * A brand category websafe title. * * @return A list of slots satisfying the "Coming Soon" business rule for a * given brand category. */ List<SlotDTO> findComingSoonSlotsByBrandCategory(Long platformKey, final String brandCategoryWst); /** * It returns the list of slots give a list of keys. * * @param platformKey * Platform key. * @param slotKeys * List of slots keys. * @return List of slots. */ List<SlotData> findSlotDataBySlotKeys(Long platformKey, List<Long> slotKeys); /** * Retrieves the next airing slot data based in current date. * * @param brandWebSafeTitle * @param fromDateTime * @return Next airing slot date, <strong>null</strong> if there're no next * airing slot data. */ SlotData findNextSlotDataByBrandSortedByTxThenChannel(final String brandWebSafeTitle, final Date fromDateTime); /** * Returns episode list representing the (default) first and second active * and non-suspended episodes (if any) of the first active and non-suspended * series (if any) for given brand (based on brand's key). * * @param brandKey * The brand key used for the selection of the episodes. * @return Returns episode list representing the (default) first and second * active and non-suspended episodes (if any) of the first active * and non-suspended series (if any) for given brand (based on * brand's key). */ List<SlotEpisodeDTO> findDefaultSlotEpisodesForBrand(final Long brandKey); /** * Retrieves the next slot/episode information for the given brand and * channel. This method also takes into account the following restrictions: * <ul> * <li>The slot datetime will be in the future (from now to infinity)</li> * </ul> * * @param brandKey * Key of the brand. * @param channel * Preferred channel of the brand. * @param currentDate * Current date. * @return Next slot/episode information. */ SlotEpisodeDTO findNextOnSlotEpisodeStrict(Long brandKey, Channel channel, Date currentDate); /** * Retrieves the next slot/episode information for the given brand. The only * additional restriction is that the slot datetime will be in the future * (from now to infinity).</br> There will not be restriction relating to * the channel. * * @param brandKey * Key of the brand. * @param currentDate * Current date. * @return Next slot/episode information. */ SlotEpisodeDTO findNextOnSlotEpisodeLenient(Long brandKey, Date currentDate); /** * Retrieves the last slot/episode information for the given brand and * channel. This method also takes into account the following restrictions: * <ul> * <li>The slot datetime will be in the past (no 6 months restriction!)</li> * </ul> * * @param brandKey * Key of the brand. * @param channel * Preferred channel of the brand. * @param currentDate * Current date. * @return Last slot/episode information. */ SlotEpisodeDTO findLastOnSlotEpisodeStrict(Long brandKey, Channel channel, Date currentDate); /** * Retrieves the last slot/episode information for the given brand and * channel. This method also takes into account the following restrictions: * <ul> * <li>The slot datetime will be in last x days (time window).</li> * </ul> * * @param brandKey * Key of the brand. * @param timeWindow * Time window (in days) to be taken into account when searching. * @return Last slot/episode information. */ SlotEpisodeDTO findLastOnSlotEpisodeLenient(Long brandKey, Date currentDate, int timeWindow); }
UTF-8
Java
15,378
java
EpgServiceDao.java
Java
[]
null
[]
package com.channel4.nc.services.pml.epg.dao; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import com.channel4.common.core.enums.Channel; import com.channel4.nc.services.pml.model.SlotData; import com.channel4.nc.services.pml.model.SlotEpisodeDTO; import com.channel4.nc.services.pml.model.SlotIndicatorData; /** * DAO service exposing available EPG DAO Service methods. * */ public interface EpgServiceDao { /** * Retrieves next programme slot details for given brand, fromDate and * fromTime * * @param brandKey * @param fromDateTime * @param repeatsOkay * @return SlotData */ SlotData findNextSlotData(Long brandKey, Date fromDateTime, boolean repeatsOkay); /** * Retrieves next programme slot details for the given brand, channel which * datetime is in the given window (fromDateTime, fromDateTime + * windowInDays) regardless the repeat flag. * * @param brandKey * @param fromDateTime * @param channelId * @param windowInDays * @return */ SlotData findNextSlotDataByChannelWithinWindow(Long brandKey, String channelId, Date fromDateTime, int windowInDays); /** * Retrieves future programme slot details for given brand, fromDate and * fromTime * * @param brandWebSafeTitle * @param fromDateTime * @return SlotData */ List<SlotData> findNextSlotsForBrandIncludeRepeats(final String brandWebSafeTitle, final Date fromDateTime); /** * Retrieves next programme slot details for given brand, channel, fromDate * and fromTime * * @param brandKey * @param channelId * @param fromDateTime * @return SlotData */ SlotData findNextSlotDataByChannel(Long brandKey, String channelId, Date fromDateTime); /** * Retrieves last programme slot details for given brand, fromDate and * fromTime * * @param brandKey * @param fromDateTime * @param earliestDateTime * @param repeatsOkay * @return SlotData */ SlotData findLastSlotData(Long brandKey, Date fromDateTime, Date earliestDateTime, boolean repeatsOkay); /** * Retrieves last programme slot details for given brand, channel, fromDate * and fromTime * * @param brandKey * @param channelId * @param fromDateTime * @return SlotData */ SlotData findLastSlotDataByChannel(Long brandKey, String channelId, Date fromDateTime); /** * Retrieves lists of slot indicators for a list of slot keys. * * @param slotKeys * @return Map<Long, List<SlotIndicatorData>> */ Map<Long, List<SlotIndicatorData>> findAllSlotIndicatorsBySlotKeys(List<Long> slotKeys); /** * Retrieves lists of simulcast rights on various platforms for a list of * slot keys. * * @param slotKeys * @return Map<Long, Set<Long>> */ Map<Long, Set<Long>> findSimulcastRightsBySlotKeys(final List<Long> slotKeys); /** * Retrieves next programme slot details for given series, fromDate and * fromTime * * @param seriesKey * @param fromDateTime * @return SlotData */ SlotData findNextSlotForSeries(Long seriesKey, Date fromDateTime); /** * Retrieves last programme slot details for given series, fromDate and * fromTime * * @param seriesKey * @param fromDateTime * @return SlotData */ SlotData findLastSlotForSeries(Long seriesKey, Date fromDateTime); /** * Retrieves all slots for a given channel and date. Note that B-S-E * information will be returned for the given 'platformKey', 'channelId' and * 'date' where available, but where this is not available the standard slot * information will be returned instead. * * @param platformKey * @param channelId * @param date * @return List<SlotData> */ List<SlotData> findAllSlots(Long platformKey, String channelId, Date date); /** * Retrieves all slots for a given channel and date and the simulcast rights * for the slots. * * @param platformKey * - a platform key. * @param channelId * - a channelId. * @param date * - a date. * * @return a list containing all the slots or an empty list there are no * slots for the given date. * * @see #findAllSlots(Long, String, Date); */ List<SlotData> findAllSlotsWithSimulcastInfo(Long platformKey, String channelId, Date date); /** * Retrieves next programme slot details for given series, channel, fromDate * and fromTime * * @param seriesKey * @param fromDateTime * @param channelId * @return SlotData */ SlotData findNextSlotForSeriesByChannel(Long seriesKey, String channelId, Date fromDateTime); /** * Retrieves last programme slot details for given series, channel, fromDate * and fromTime * * @param seriesKey * @param fromDateTime * @param channelId * * @return SlotData */ SlotData findLastSlotForSeriesByChannel(Long seriesKey, String channelId, Date fromDateTime); /** * Retrieves slots for home page with duration greater than given * minDuration * * @param platformKey * @param channelId * @param minDuration * minimum slot duration * @param maxSlots * maximum number of slots to be returned * @param fromDateTime * @return List<SlotData> */ List<SlotData> findMinimumDurationSlotsByChannel(Long platformKey, String channelId, Date fromDateTime, Integer minDuration, Integer maxSlots); /** * Retrieves currently showing programme slot details for given channel * * @param platformKey * @param channelId * @param giveTime * @return SlotData */ SlotData findNowSlotForChannel(Long platformKey, Channel channelId, Date giveTime); /** * Does this brand have a slot */ boolean findHasSlotForBrand(Long brandKey); /** * Retrieves Map with slots first broadcast information keyed by episode * programme id. * * NOTE: If an episode is repeated (i.e. More than one slots for given * programme id exist in the database), first slot is returned using slot * date and time ordering * * @param platformKey * @param programmeIds * @return Map<programmeId, SlotDTO> */ Map<String, SlotDTO> findSlotsWithFirstBroadcastInfo(Long platformKey, List<String> programmeIds); /** * Retrieves Map with all slots information keyed by episode programme id * for given programme id's, slot date's and channel name's * * NOTE: If an episode is repeated (i.e. More than one slots for given * programme id, slot date and channel exist in the database), first slot of * the day will be returned * * @param platformKey * @param programmeIds * @param slotDates * @param channelNames * @return Map<programmeId, SlotDTO> */ Map<String, SlotDTO> findAllSlots(Long platformKey, List<String> programmeIds, List<Date> slotDates, List<String> channelNames); /** * Finds next on slots from given date and time for a specific episode * * @param platformKey * @param programmeId * @param fromDateTime * @return list of next on slots */ List<SlotData> findNextSlotsForEpisode(Long platformKey, String programmeId, Date fromDateTime); /** * Finds next on slots from given date and time for a specific episode and * channel * * @param platformKey * @param programmeId * @param channelId * @param fromDateTime * @return list of next on slots */ List<SlotData> findNextSlotsForEpisodeByChannel(Long platformKey, String programmeId, String channelId, Date fromDateTime); /** * Finds last on slot information from given date and time for a specific * episode * * @param platformKey * @param programmeId * @param fromDateTime * @return last on slot */ SlotData findLastSlotForEpisode(Long platformKey, String programmeId, Date fromDateTime); /** * Finds last on slots from given date and time for a specific episode and * channel * * @param platformKey * @param programmeId * @param channelId * @param fromDateTime * @return last on slots */ SlotData findLastSlotForEpisodeByChannel(Long platformKey, String programmeId, String channelId, Date fromDateTime); /** * Finds first on slot information from given date and time for a specific * episode * * @param platformKey * @param programmeId * @param fromDateTime * @return first on slot */ SlotData findFirstOnSlotForEpisode(Long platformKey, String programmeId, Date fromDateTime); /** * Finds first on slot information from given date and time for a specific * episode and channel * * @param platformKey * @param programmeId * @param channelId * @param fromDateTime * @return first on slot */ SlotData findFirstOnSlotForEpisodeByChannel(Long platformKey, String programmeId, String channelId, Date fromDateTime); /** * Used for brand epg page atom feed * * @param platformKey * @param programmeIds * @param cutOffDate * @return */ List<SlotData> findNextSlotsForEpisodes(Long platformKey, List<String> programmeIds, Date cutOffDate); /** * Looks in the future (i.e. after currentDate) to find at most maxSlots * active and unsuspended series slots of non-flattened and active brands * whose episodes have never been aired in the past. * * @param platformKey * @param currentDate * @param maxSlots * @return at most maxSlots upcoming series slots */ List<SeriesPromotionalItemDTO> findUpcomingSeriesSlots(Long platformKey, Date currentDate, Integer maxSlots); /** * Retrieves the list of current slots for channel. * * @return A list of slots. An empty list if there're no slots for the * current time, channel or platform. */ List<SlotData> findAllNowSlotsForChannel(Long platformKey, Channel channel, Date givenTime); /** * Returns the slots, satisfying the "Coming Soon" business rules, applied * for all brand categories. * * @param platformKey * Key of the platform for which will be performed the search. * * @return A list of slots satisfying the "Coming Soon" business rule. */ List<SlotDTO> findComingSoonSlots(Long platformKey); /** * Returns the slots, satisfying the "Coming Soon" business rules selected * by brand category. * * <p> * ATTENTION: Note that the category name should be URI-compliant, i.e. no * adjustments like converting to lower case for example will take place * before querying the database. * </p> * * @param platformKey * Key of the platform for which will be performed the search. * @param brandCategoryWst * A brand category websafe title. * * @return A list of slots satisfying the "Coming Soon" business rule for a * given brand category. */ List<SlotDTO> findComingSoonSlotsByBrandCategory(Long platformKey, final String brandCategoryWst); /** * It returns the list of slots give a list of keys. * * @param platformKey * Platform key. * @param slotKeys * List of slots keys. * @return List of slots. */ List<SlotData> findSlotDataBySlotKeys(Long platformKey, List<Long> slotKeys); /** * Retrieves the next airing slot data based in current date. * * @param brandWebSafeTitle * @param fromDateTime * @return Next airing slot date, <strong>null</strong> if there're no next * airing slot data. */ SlotData findNextSlotDataByBrandSortedByTxThenChannel(final String brandWebSafeTitle, final Date fromDateTime); /** * Returns episode list representing the (default) first and second active * and non-suspended episodes (if any) of the first active and non-suspended * series (if any) for given brand (based on brand's key). * * @param brandKey * The brand key used for the selection of the episodes. * @return Returns episode list representing the (default) first and second * active and non-suspended episodes (if any) of the first active * and non-suspended series (if any) for given brand (based on * brand's key). */ List<SlotEpisodeDTO> findDefaultSlotEpisodesForBrand(final Long brandKey); /** * Retrieves the next slot/episode information for the given brand and * channel. This method also takes into account the following restrictions: * <ul> * <li>The slot datetime will be in the future (from now to infinity)</li> * </ul> * * @param brandKey * Key of the brand. * @param channel * Preferred channel of the brand. * @param currentDate * Current date. * @return Next slot/episode information. */ SlotEpisodeDTO findNextOnSlotEpisodeStrict(Long brandKey, Channel channel, Date currentDate); /** * Retrieves the next slot/episode information for the given brand. The only * additional restriction is that the slot datetime will be in the future * (from now to infinity).</br> There will not be restriction relating to * the channel. * * @param brandKey * Key of the brand. * @param currentDate * Current date. * @return Next slot/episode information. */ SlotEpisodeDTO findNextOnSlotEpisodeLenient(Long brandKey, Date currentDate); /** * Retrieves the last slot/episode information for the given brand and * channel. This method also takes into account the following restrictions: * <ul> * <li>The slot datetime will be in the past (no 6 months restriction!)</li> * </ul> * * @param brandKey * Key of the brand. * @param channel * Preferred channel of the brand. * @param currentDate * Current date. * @return Last slot/episode information. */ SlotEpisodeDTO findLastOnSlotEpisodeStrict(Long brandKey, Channel channel, Date currentDate); /** * Retrieves the last slot/episode information for the given brand and * channel. This method also takes into account the following restrictions: * <ul> * <li>The slot datetime will be in last x days (time window).</li> * </ul> * * @param brandKey * Key of the brand. * @param timeWindow * Time window (in days) to be taken into account when searching. * @return Last slot/episode information. */ SlotEpisodeDTO findLastOnSlotEpisodeLenient(Long brandKey, Date currentDate, int timeWindow); }
15,378
0.650865
0.650475
467
31.929337
30.682692
132
false
false
0
0
0
0
0
0
0.316916
false
false
13
bcfe675facd8b11aaee9246605dfb69be0d64d63
19,653,770,358,496
9209fce2d98f211bc81d92f500fe837bfcd2e3fc
/Basic Projects/MethodOverloading/src/com/valkov/Main.java
04f13d5d557d0f2fe26ff63875238f0d563382be
[]
no_license
RosenV95/IdeaProjects
https://github.com/RosenV95/IdeaProjects
54d08f5ba9fcd8f446053a5c2b82ab808ea11dd0
d7e72f1f0635b362ff6d8593dd32617a47a2748c
refs/heads/master
2020-12-12T11:31:56.140000
2020-02-09T11:49:58
2020-02-09T11:49:58
233,907,558
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.valkov; public class Main { public static void main(String[] args) { // write your code here int newScore=calculateScore("Tim", 500); System.out.println("New score is "+newScore); calculateScore(75); calculateScore(); calcFeetAndInchesToCentimeters(6,0); } public static int calculateScore(String playerName, int score){ System.out.println("Player "+ playerName + " scored " + score + " points"); return score*1000; } public static int calculateScore(int score) { System.out.println("Unnamed scored " + score + " points"); return score * 1000; } public static int calculateScore() { System.out.println("No name, no score"); return 0; } public static double calcFeetAndInchesToCentimeters(double feet, double inches){ if((feet<0)|| ((inches<0) || (inches > 12))){ return -1; } double centimetres=(feet*12)*2.54; centimetres+=inches*2.54; System.out.println(feet + " feet, "+inches+" inches = " + centimetres+ " cm"); return centimetres; } public static double calcFeetAndInchesToCentimeters(double inches){ if(inches<0){ return -1; } else{ return (inches); } } }
UTF-8
Java
1,338
java
Main.java
Java
[ { "context": "ur code here\n int newScore=calculateScore(\"Tim\", 500);\n System.out.println(\"New score is ", "end": 152, "score": 0.9625185132026672, "start": 149, "tag": "NAME", "value": "Tim" } ]
null
[]
package com.valkov; public class Main { public static void main(String[] args) { // write your code here int newScore=calculateScore("Tim", 500); System.out.println("New score is "+newScore); calculateScore(75); calculateScore(); calcFeetAndInchesToCentimeters(6,0); } public static int calculateScore(String playerName, int score){ System.out.println("Player "+ playerName + " scored " + score + " points"); return score*1000; } public static int calculateScore(int score) { System.out.println("Unnamed scored " + score + " points"); return score * 1000; } public static int calculateScore() { System.out.println("No name, no score"); return 0; } public static double calcFeetAndInchesToCentimeters(double feet, double inches){ if((feet<0)|| ((inches<0) || (inches > 12))){ return -1; } double centimetres=(feet*12)*2.54; centimetres+=inches*2.54; System.out.println(feet + " feet, "+inches+" inches = " + centimetres+ " cm"); return centimetres; } public static double calcFeetAndInchesToCentimeters(double inches){ if(inches<0){ return -1; } else{ return (inches); } } }
1,338
0.584454
0.561285
43
30.11628
24.445677
86
false
false
0
0
0
0
0
0
0.697674
false
false
13
9bb345f2d785810034318290be2a303c3c71ac7d
13,554,916,789,934
1e13ac6fa7cca6865b18235da4a5bef4db823d98
/src/Handler/BadRequestHandler.java
0bf19716db5c9cab314a3a2100aad32213db2464
[]
no_license
SufianZa/InternetTech
https://github.com/SufianZa/InternetTech
efd335e3fc19e72559d0b01ff7117aafedb39165
90ef07b127d15727b4c06b88a0122e00404a368b
refs/heads/master
2021-06-20T10:07:06.374000
2017-07-16T09:02:49
2017-07-16T09:02:49
91,487,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Handler; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; /** * Created by Sufian Vaio on 15.05.2017. */ public class BadRequestHandler implements IHandler { private final String HEADER_HTTP = "HTTP/1.1 404 OK\n"; public BadRequestHandler() { } @Override public void handle(OutputStream out) throws IOException { FileInputStream fis = new FileInputStream("src/public/bad.html"); int length = fis.available(); byte[] b =new byte[length]; fis.read(b); out.write(HEADER_HTTP.getBytes()); out.write("\n\n".getBytes()); out.write(b); } }
UTF-8
Java
667
java
BadRequestHandler.java
Java
[ { "context": "n;\nimport java.io.OutputStream;\n\n/**\n * Created by Sufian Vaio on 15.05.2017.\n */\npublic class BadRequestHandler", "end": 137, "score": 0.9998688697814941, "start": 126, "tag": "NAME", "value": "Sufian Vaio" } ]
null
[]
package Handler; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; /** * Created by <NAME> on 15.05.2017. */ public class BadRequestHandler implements IHandler { private final String HEADER_HTTP = "HTTP/1.1 404 OK\n"; public BadRequestHandler() { } @Override public void handle(OutputStream out) throws IOException { FileInputStream fis = new FileInputStream("src/public/bad.html"); int length = fis.available(); byte[] b =new byte[length]; fis.read(b); out.write(HEADER_HTTP.getBytes()); out.write("\n\n".getBytes()); out.write(b); } }
662
0.650675
0.631184
26
24.653847
21.114964
73
false
false
0
0
0
0
0
0
0.461538
false
false
13
c2c989f4bdc5b345c25d978b0b36161a02c7c43e
16,810,501,999,698
69fa66175dd9660478b3898b61dca630e4c092fc
/src/ChessRePainting.java
2c74b7d96d047042782a14ce8655bc52f2bbe7b0
[]
no_license
NamjinCho/Algorithm_Study
https://github.com/NamjinCho/Algorithm_Study
711f95c57af7a4e5c7d06265c289577299eebc40
d1a4ca7cc3dc9e7e0c27e1ac39a6871034317e48
refs/heads/master
2020-12-02T17:49:29.362000
2017-10-23T05:21:12
2017-10-23T05:21:12
96,433,369
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; /** * Created by NamjinCho on 2017-10-13. */ public class ChessRePainting { public static void main(String []args) { Scanner sc= new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); sc.nextLine(); char map [][] = new char[N][M]; for(int i=0;i<N;i++) { String line =sc.nextLine(); for(int j=0;j<M;j++) { map[i][j] = line.charAt(j); } } } public static int solve(int row , int col) { return 0; } }
UTF-8
Java
604
java
ChessRePainting.java
Java
[ { "context": "import java.util.Scanner;\n\n/**\n * Created by NamjinCho on 2017-10-13.\n */\npublic class ChessRePainting {", "end": 54, "score": 0.835028350353241, "start": 45, "tag": "USERNAME", "value": "NamjinCho" } ]
null
[]
import java.util.Scanner; /** * Created by NamjinCho on 2017-10-13. */ public class ChessRePainting { public static void main(String []args) { Scanner sc= new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); sc.nextLine(); char map [][] = new char[N][M]; for(int i=0;i<N;i++) { String line =sc.nextLine(); for(int j=0;j<M;j++) { map[i][j] = line.charAt(j); } } } public static int solve(int row , int col) { return 0; } }
604
0.465232
0.44702
31
18.483871
15.943188
46
false
false
0
0
0
0
0
0
0.451613
false
false
13
f6187d6902174a92e247b36090a62ccc7dba3e13
15,384,572,901,874
11fda41104d75372344f34fc73225e222b7ce7ca
/uikit/src/main/java/com/sendbird/uikit/widgets/MyImageFileMessageView.java
c07069eae2a7f7d44d0428fcd1cf97fd19137f08
[ "MIT" ]
permissive
dianapham/sendbird-uikit-android
https://github.com/dianapham/sendbird-uikit-android
e604be032e03729bbe80e524222e960a94f41c4b
63d83868e07544d07c107aadd7799a4e306292de
refs/heads/main
2023-09-03T11:54:31.776000
2021-11-23T10:28:15
2021-11-23T10:28:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sendbird.uikit.widgets; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import androidx.databinding.DataBindingUtil; import com.sendbird.android.BaseMessage; import com.sendbird.android.FileMessage; import com.sendbird.android.GroupChannel; import com.sendbird.uikit.R; import com.sendbird.uikit.SendBirdUIKit; import com.sendbird.uikit.consts.MessageGroupType; import com.sendbird.uikit.databinding.SbViewMyFileImageMessageComponentBinding; import com.sendbird.uikit.utils.DateUtils; import com.sendbird.uikit.utils.DrawableUtils; import com.sendbird.uikit.utils.ViewUtils; public class MyImageFileMessageView extends GroupChannelMessageView { private SbViewMyFileImageMessageComponentBinding binding; @Override public SbViewMyFileImageMessageComponentBinding getBinding() { return binding; } @Override public View getLayout() { return binding.getRoot(); } public MyImageFileMessageView(Context context) { this(context, null); } public MyImageFileMessageView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.sb_message_file_style); } public MyImageFileMessageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, int defStyle) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MessageView_File, defStyle, 0); try { this.binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.sb_view_my_file_image_message_component, this, true); int timeAppearance = a.getResourceId(R.styleable.MessageView_File_sb_message_time_text_appearance, R.style.SendbirdCaption4OnLight03); int messageBackground = a.getResourceId(R.styleable.MessageView_File_sb_message_me_background, R.drawable.sb_shape_chat_bubble); int messageBackgroundTint = a.getResourceId(R.styleable.MessageView_File_sb_message_me_background_tint, R.color.sb_message_me_tint_light); int emojiReactionListBackground = a.getResourceId(R.styleable.MessageView_File_sb_message_emoji_reaction_list_background, R.drawable.sb_shape_chat_bubble_reactions_light); binding.tvSentAt.setTextAppearance(context, timeAppearance); binding.contentPanel.setBackground(DrawableUtils.setTintList(getContext(), messageBackground, messageBackgroundTint)); binding.emojiReactionListBackground.setBackgroundResource(emojiReactionListBackground); int bg = SendBirdUIKit.isDarkMode() ? R.drawable.sb_shape_image_message_background_dark : R.drawable.sb_shape_image_message_background; binding.ivThumbnail.setBackgroundResource(bg); } finally { a.recycle(); } } @Override public void drawMessage(GroupChannel channel, BaseMessage message, MessageGroupType messageGroupType) { boolean sendingState = message.getSendingStatus() == BaseMessage.SendingStatus.SUCCEEDED; boolean hasReaction = message.getReactions() != null && message.getReactions().size() > 0; binding.emojiReactionListBackground.setVisibility(hasReaction ? View.VISIBLE : View.GONE); binding.rvEmojiReactionList.setVisibility(hasReaction ? View.VISIBLE : View.GONE); binding.tvSentAt.setVisibility((sendingState && (messageGroupType == MessageGroupType.GROUPING_TYPE_TAIL || messageGroupType == MessageGroupType.GROUPING_TYPE_SINGLE)) ? View.VISIBLE : View.GONE); binding.tvSentAt.setText(DateUtils.formatTime(getContext(), message.getCreatedAt())); binding.ivStatus.drawStatus(message, channel); ViewUtils.drawReactionEnabled(binding.rvEmojiReactionList, channel); ViewUtils.drawThumbnail(binding.ivThumbnail, (FileMessage) message); ViewUtils.drawThumbnailIcon(binding.ivThumbnailIcon, (FileMessage) message); int paddingTop = getResources().getDimensionPixelSize((messageGroupType == MessageGroupType.GROUPING_TYPE_TAIL || messageGroupType == MessageGroupType.GROUPING_TYPE_BODY) ? R.dimen.sb_size_1 : R.dimen.sb_size_8); int paddingBottom = getResources().getDimensionPixelSize((messageGroupType == MessageGroupType.GROUPING_TYPE_HEAD || messageGroupType == MessageGroupType.GROUPING_TYPE_BODY) ? R.dimen.sb_size_1 : R.dimen.sb_size_8); binding.root.setPadding(binding.root.getPaddingLeft(), paddingTop, binding.root.getPaddingRight(), paddingBottom); ViewUtils.drawQuotedMessage(binding.quoteReplyPanel, message); } }
UTF-8
Java
4,749
java
MyImageFileMessageView.java
Java
[]
null
[]
package com.sendbird.uikit.widgets; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import androidx.databinding.DataBindingUtil; import com.sendbird.android.BaseMessage; import com.sendbird.android.FileMessage; import com.sendbird.android.GroupChannel; import com.sendbird.uikit.R; import com.sendbird.uikit.SendBirdUIKit; import com.sendbird.uikit.consts.MessageGroupType; import com.sendbird.uikit.databinding.SbViewMyFileImageMessageComponentBinding; import com.sendbird.uikit.utils.DateUtils; import com.sendbird.uikit.utils.DrawableUtils; import com.sendbird.uikit.utils.ViewUtils; public class MyImageFileMessageView extends GroupChannelMessageView { private SbViewMyFileImageMessageComponentBinding binding; @Override public SbViewMyFileImageMessageComponentBinding getBinding() { return binding; } @Override public View getLayout() { return binding.getRoot(); } public MyImageFileMessageView(Context context) { this(context, null); } public MyImageFileMessageView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.sb_message_file_style); } public MyImageFileMessageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, int defStyle) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MessageView_File, defStyle, 0); try { this.binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.sb_view_my_file_image_message_component, this, true); int timeAppearance = a.getResourceId(R.styleable.MessageView_File_sb_message_time_text_appearance, R.style.SendbirdCaption4OnLight03); int messageBackground = a.getResourceId(R.styleable.MessageView_File_sb_message_me_background, R.drawable.sb_shape_chat_bubble); int messageBackgroundTint = a.getResourceId(R.styleable.MessageView_File_sb_message_me_background_tint, R.color.sb_message_me_tint_light); int emojiReactionListBackground = a.getResourceId(R.styleable.MessageView_File_sb_message_emoji_reaction_list_background, R.drawable.sb_shape_chat_bubble_reactions_light); binding.tvSentAt.setTextAppearance(context, timeAppearance); binding.contentPanel.setBackground(DrawableUtils.setTintList(getContext(), messageBackground, messageBackgroundTint)); binding.emojiReactionListBackground.setBackgroundResource(emojiReactionListBackground); int bg = SendBirdUIKit.isDarkMode() ? R.drawable.sb_shape_image_message_background_dark : R.drawable.sb_shape_image_message_background; binding.ivThumbnail.setBackgroundResource(bg); } finally { a.recycle(); } } @Override public void drawMessage(GroupChannel channel, BaseMessage message, MessageGroupType messageGroupType) { boolean sendingState = message.getSendingStatus() == BaseMessage.SendingStatus.SUCCEEDED; boolean hasReaction = message.getReactions() != null && message.getReactions().size() > 0; binding.emojiReactionListBackground.setVisibility(hasReaction ? View.VISIBLE : View.GONE); binding.rvEmojiReactionList.setVisibility(hasReaction ? View.VISIBLE : View.GONE); binding.tvSentAt.setVisibility((sendingState && (messageGroupType == MessageGroupType.GROUPING_TYPE_TAIL || messageGroupType == MessageGroupType.GROUPING_TYPE_SINGLE)) ? View.VISIBLE : View.GONE); binding.tvSentAt.setText(DateUtils.formatTime(getContext(), message.getCreatedAt())); binding.ivStatus.drawStatus(message, channel); ViewUtils.drawReactionEnabled(binding.rvEmojiReactionList, channel); ViewUtils.drawThumbnail(binding.ivThumbnail, (FileMessage) message); ViewUtils.drawThumbnailIcon(binding.ivThumbnailIcon, (FileMessage) message); int paddingTop = getResources().getDimensionPixelSize((messageGroupType == MessageGroupType.GROUPING_TYPE_TAIL || messageGroupType == MessageGroupType.GROUPING_TYPE_BODY) ? R.dimen.sb_size_1 : R.dimen.sb_size_8); int paddingBottom = getResources().getDimensionPixelSize((messageGroupType == MessageGroupType.GROUPING_TYPE_HEAD || messageGroupType == MessageGroupType.GROUPING_TYPE_BODY) ? R.dimen.sb_size_1 : R.dimen.sb_size_8); binding.root.setPadding(binding.root.getPaddingLeft(), paddingTop, binding.root.getPaddingRight(), paddingBottom); ViewUtils.drawQuotedMessage(binding.quoteReplyPanel, message); } }
4,749
0.754053
0.752158
89
52.35955
53.865467
223
false
false
0
0
0
0
0
0
1.033708
false
false
13
61b90c90775c8835f92cf751d5bae85964996295
18,193,481,511,981
2c3d1a075181e77ceb3aa035ea246acb7bc7432a
/app/src/main/java/com/autodesk/ekaterinatemnogrudova/autodesktestapplication/utils/Constants.java
9f8af49041336438b73aac24f2f85e4ad5f58a1e
[]
no_license
Temnogrudova/AutodeskTestApplication
https://github.com/Temnogrudova/AutodeskTestApplication
9979f1a6ea1b9df66e3aac67d556aef5d5b42e57
02fbb68cf5602e61661fe85050df7ac8a4233755
refs/heads/master
2020-05-09T09:42:40.235000
2019-04-13T12:15:42
2019-04-13T12:15:52
180,995,285
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.autodesk.ekaterinatemnogrudova.autodesktestapplication.utils; public class Constants { public static final String BASE_URL = "https://newsapi.org/"; public static final String BUNDLE_ARTICLE = "BUNDLE_ARTICLE"; public static final String FRAGMENT_ARTICLE = "FRAGMENT_ARTICLE"; public static final String DATE_PATTERN = "EEE, dd MMM yyyy - HH:mm"; public static final String QUERY_PUBLISHED = "1ea491abc3eb424294a165428ea0c455"; public static final String QUERY_BITCOIN = "bitcoin"; public static final String API_KEY = "1ea491abc3eb424294a165428ea0c455"; }
UTF-8
Java
599
java
Constants.java
Java
[ { "context": "tcoin\";\n public static final String API_KEY = \"1ea491abc3eb424294a165428ea0c455\";\n\n}\n", "end": 593, "score": 0.9996541142463684, "start": 561, "tag": "KEY", "value": "1ea491abc3eb424294a165428ea0c455" } ]
null
[]
package com.autodesk.ekaterinatemnogrudova.autodesktestapplication.utils; public class Constants { public static final String BASE_URL = "https://newsapi.org/"; public static final String BUNDLE_ARTICLE = "BUNDLE_ARTICLE"; public static final String FRAGMENT_ARTICLE = "FRAGMENT_ARTICLE"; public static final String DATE_PATTERN = "EEE, dd MMM yyyy - HH:mm"; public static final String QUERY_PUBLISHED = "1ea491abc3eb424294a165428ea0c455"; public static final String QUERY_BITCOIN = "bitcoin"; public static final String API_KEY = "1ea491abc3eb424294a165428ea0c455"; }
599
0.761269
0.691152
12
48.916668
31.375305
84
false
false
0
0
0
0
0
0
0.75
false
false
13
a44666225032bcfd95a68fed3d40833be79bd621
21,088,289,468,887
4686d486ff0db01b5604b1561862b60a54f91480
/Python_Java/HW5/src/hw5/testApp.java
8f4fdf619bd685ac38845c5305fbebf977a8467e
[]
no_license
chosun41/codeportfolio
https://github.com/chosun41/codeportfolio
1ed188c3b99e687d02f5eaeb6fb0b90ce4be77cc
3fdfc90937a642a091688d5903e435067c8499b3
refs/heads/master
2021-01-13T14:45:56.348000
2017-06-18T06:04:38
2017-06-18T06:04:38
94,666,938
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package hw5; import java.util.ArrayList; import java.util.Collections; import java.text.ParseException; import java.io.FileWriter; import java.io.IOException; import java.io.File; public class testApp { public static void main(String [] args) throws ParseException, IOException{ /* empty array list * */ ArrayList<Appointment> x = new ArrayList<Appointment>(); /* add appointments for onetime, daily, and monthly subclasses * in empty appointment arraylist x */ x.add(new Onetime("surgery","11/01/2017")); x.add(new Daily("insulin shots","5/1/2017","8/1/2017")); x.add(new Monthly("mri",1, 2017, 2, 2017, 7)); /* test cases for description, string method, and occursIn method true/false * for each arraylist item of appointments */ System.out.println("Test cases for onetime appointment on 11/1/2017"); System.out.println(x.get(0).getdescr()); System.out.println("Testing 11/1/2017 " + x.get(0).occursIn(2017,11,1)); System.out.println("Testing 11/2/2017 " + x.get(0).occursIn(2017,11,2)); System.out.println(x.get(0).toString() + "\n"); System.out.println("Test cases for daily appointment 5/1-8/1/2017"); System.out.println(x.get(1).getdescr()); System.out.println("Testing 4/1/2017 " + x.get(1).occursIn(2017,4,1)); System.out.println("Testing 5/1/2017 " + x.get(1).occursIn(2017,5,1)); System.out.println("Testing 6/5/2017 " + x.get(1).occursIn(2017,6,5)); System.out.println("Testing 8/1/2017 " + x.get(1).occursIn(2017,8,1)); System.out.println("Testing 9/1/2017 " + x.get(1).occursIn(2017,9,1)); System.out.println(x.get(1).toString()+ "\n"); System.out.println("Test cases for monthly appointment 2/1-7/1/2017"); System.out.println(x.get(2).getdescr()); System.out.println("Testing 1/1/2017 " + x.get(2).occursIn(2017,1,1)); System.out.println("Testing 2/1/2017 " + x.get(2).occursIn(2017,2,1)); System.out.println("Testing 5/1/2017 " + x.get(2).occursIn(2017,5,1)); System.out.println("Testing 5/2/2017 " + x.get(2).occursIn(2017,5,2)); System.out.println("Testing 7/1/2017 " + x.get(2).occursIn(2017,7,1)); System.out.println("Testing 8/1/2017 " + x.get(2).occursIn(2017,8,1)); System.out.println(x.get(2).toString()+ "\n"); /* write appointments to text file * */ apptotxt(x); /* print out all appointments that occur on this date * testing 7/1/2017 which has both a monthly and daily appointment */ printappt(x, 2017, 7, 1); } /* writes text of tostring method into a text file * * @param arraylist of appointments * @return nothing, just writes text of arraylist tostring method into file */ public static void apptotxt(ArrayList<Appointment>inptx) throws IOException{ FileWriter fw = new FileWriter("appt.txt"); for (Appointment elem : inptx) { fw.write(elem.toString() + System.getProperty("line.separator")); } fw.close(); } /* writes text of tostring method into a text file * * @param arraylist of appointments * @return nothing, just writes text of arraylist tostring method into file */ public static void printappt(ArrayList<Appointment>inptx, int year, int month, int day) throws IOException, ParseException{ for (int i = 0; i < inptx.size(); i++){ if(inptx.get(i).occursIn(year, month, day)){ System.out.println(inptx.get(i).toString()); } } } }
UTF-8
Java
3,363
java
testApp.java
Java
[]
null
[]
package hw5; import java.util.ArrayList; import java.util.Collections; import java.text.ParseException; import java.io.FileWriter; import java.io.IOException; import java.io.File; public class testApp { public static void main(String [] args) throws ParseException, IOException{ /* empty array list * */ ArrayList<Appointment> x = new ArrayList<Appointment>(); /* add appointments for onetime, daily, and monthly subclasses * in empty appointment arraylist x */ x.add(new Onetime("surgery","11/01/2017")); x.add(new Daily("insulin shots","5/1/2017","8/1/2017")); x.add(new Monthly("mri",1, 2017, 2, 2017, 7)); /* test cases for description, string method, and occursIn method true/false * for each arraylist item of appointments */ System.out.println("Test cases for onetime appointment on 11/1/2017"); System.out.println(x.get(0).getdescr()); System.out.println("Testing 11/1/2017 " + x.get(0).occursIn(2017,11,1)); System.out.println("Testing 11/2/2017 " + x.get(0).occursIn(2017,11,2)); System.out.println(x.get(0).toString() + "\n"); System.out.println("Test cases for daily appointment 5/1-8/1/2017"); System.out.println(x.get(1).getdescr()); System.out.println("Testing 4/1/2017 " + x.get(1).occursIn(2017,4,1)); System.out.println("Testing 5/1/2017 " + x.get(1).occursIn(2017,5,1)); System.out.println("Testing 6/5/2017 " + x.get(1).occursIn(2017,6,5)); System.out.println("Testing 8/1/2017 " + x.get(1).occursIn(2017,8,1)); System.out.println("Testing 9/1/2017 " + x.get(1).occursIn(2017,9,1)); System.out.println(x.get(1).toString()+ "\n"); System.out.println("Test cases for monthly appointment 2/1-7/1/2017"); System.out.println(x.get(2).getdescr()); System.out.println("Testing 1/1/2017 " + x.get(2).occursIn(2017,1,1)); System.out.println("Testing 2/1/2017 " + x.get(2).occursIn(2017,2,1)); System.out.println("Testing 5/1/2017 " + x.get(2).occursIn(2017,5,1)); System.out.println("Testing 5/2/2017 " + x.get(2).occursIn(2017,5,2)); System.out.println("Testing 7/1/2017 " + x.get(2).occursIn(2017,7,1)); System.out.println("Testing 8/1/2017 " + x.get(2).occursIn(2017,8,1)); System.out.println(x.get(2).toString()+ "\n"); /* write appointments to text file * */ apptotxt(x); /* print out all appointments that occur on this date * testing 7/1/2017 which has both a monthly and daily appointment */ printappt(x, 2017, 7, 1); } /* writes text of tostring method into a text file * * @param arraylist of appointments * @return nothing, just writes text of arraylist tostring method into file */ public static void apptotxt(ArrayList<Appointment>inptx) throws IOException{ FileWriter fw = new FileWriter("appt.txt"); for (Appointment elem : inptx) { fw.write(elem.toString() + System.getProperty("line.separator")); } fw.close(); } /* writes text of tostring method into a text file * * @param arraylist of appointments * @return nothing, just writes text of arraylist tostring method into file */ public static void printappt(ArrayList<Appointment>inptx, int year, int month, int day) throws IOException, ParseException{ for (int i = 0; i < inptx.size(); i++){ if(inptx.get(i).occursIn(year, month, day)){ System.out.println(inptx.get(i).toString()); } } } }
3,363
0.677371
0.603925
94
34.776596
28.357203
78
false
false
0
0
0
0
0
0
2.595745
false
false
13
291881132cbf6879bcd535c812e44e3d862fc686
26,474,178,443,833
f3ff1ca294c004e55def079f76f52ed66a8c6e31
/src/main/java/fr/cinema/models/Film.java
4df7c61a445714bb5bd5e39f2b4232af9037b506
[]
no_license
frenchincubus/spring-cinema
https://github.com/frenchincubus/spring-cinema
29fbc7842b993e85567cdd557722a87218cb8eb9
585318f3e3563d9748fbda74e1669fe0bd32aef5
refs/heads/main
2023-03-02T02:38:32.495000
2021-01-30T16:39:04
2021-01-30T16:39:04
334,182,858
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.cinema.models; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Data @Document("film") public class Film { @Id private String id; private String nom; private int duree; }
UTF-8
Java
271
java
Film.java
Java
[]
null
[]
package fr.cinema.models; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Data @Document("film") public class Film { @Id private String id; private String nom; private int duree; }
271
0.774908
0.774908
15
17.066668
17.109322
62
false
false
0
0
0
0
0
0
0.733333
false
false
13
760aeb079e7d31ac6f4f29d3c41dd61e4d405904
29,669,634,122,303
f49f3b97e3a4fdd311d267ce58562aac1126e4f0
/src/test/java/Model/DataPool.java
dcece78d397546e83e6153ded5a696cc37f524b6
[]
no_license
TheEluzive/QA
https://github.com/TheEluzive/QA
6481db326bd8c3509c044ab859f343d1c3d3c406
9a0ce3f2662ce483e5ff54d448897d77a9ace0c4
refs/heads/Dev
2022-11-29T15:43:16.099000
2019-11-25T18:49:10
2019-11-25T18:49:10
195,461,290
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Model; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.NoArgsConstructor; import org.testng.ITestContext; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @NoArgsConstructor public class DataPool<T> { { dataCollection = new ArrayList<>(); } public DataPool(String testParameterName, ITestContext testContext, Class<T> dataClass) { fillNewDataPool(testParameterName, testContext, dataClass); } private final Collection<T> dataCollection; private void processDataFile(String filePath, Class<T> dataClass) { ObjectMapper objectMapper = new ObjectMapper(); try { T data = objectMapper.readValue(new File(filePath), dataClass); dataCollection.add(data); System.out.println("dataPool created"); } catch (IOException e) { e.printStackTrace(); } } public Object[][] getData() { Object[][] dataToGet = new Object[1][dataCollection.size()]; Iterator<T> it = dataCollection.iterator(); int i = 0; while (it.hasNext()) { dataToGet[0][i] = it.next(); System.out.println(dataToGet[0][i].toString()); i++; } return dataToGet; } public void fillNewDataPool(String testParameterName, ITestContext testContext, Class<T> dataClass) { HashMap<String, String> parameters = new HashMap<>(testContext.getCurrentXmlTest().getAllParameters()); this.processDataFile(parameters.get(testParameterName), dataClass); } }
UTF-8
Java
1,675
java
DataPool.java
Java
[]
null
[]
package Model; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.NoArgsConstructor; import org.testng.ITestContext; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @NoArgsConstructor public class DataPool<T> { { dataCollection = new ArrayList<>(); } public DataPool(String testParameterName, ITestContext testContext, Class<T> dataClass) { fillNewDataPool(testParameterName, testContext, dataClass); } private final Collection<T> dataCollection; private void processDataFile(String filePath, Class<T> dataClass) { ObjectMapper objectMapper = new ObjectMapper(); try { T data = objectMapper.readValue(new File(filePath), dataClass); dataCollection.add(data); System.out.println("dataPool created"); } catch (IOException e) { e.printStackTrace(); } } public Object[][] getData() { Object[][] dataToGet = new Object[1][dataCollection.size()]; Iterator<T> it = dataCollection.iterator(); int i = 0; while (it.hasNext()) { dataToGet[0][i] = it.next(); System.out.println(dataToGet[0][i].toString()); i++; } return dataToGet; } public void fillNewDataPool(String testParameterName, ITestContext testContext, Class<T> dataClass) { HashMap<String, String> parameters = new HashMap<>(testContext.getCurrentXmlTest().getAllParameters()); this.processDataFile(parameters.get(testParameterName), dataClass); } }
1,675
0.662687
0.660299
53
30.603773
28.153448
111
false
false
0
0
0
0
0
0
0.698113
false
false
13
b1fce65ea40ffd4f1e37e4cac3e42f25cffffe38
18,923,625,938,080
899e3440cda769c6a4b7649065dee47bc0516b6c
/database_systems/sandbox/src/SqlHelper.java
b96566f444465a53d74cb5e07cc8aa98ecf8e563
[]
no_license
karanjude/snippets
https://github.com/karanjude/snippets
6bf1492cb751a206e4b403ea7f03eda2a37c6892
a1c7e85b8999214f03b30469222cb64b5ad80146
refs/heads/master
2021-01-06T20:38:17.017000
2011-06-06T23:37:53
2011-06-06T23:37:53
32,311,843
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class SqlHelper { public String generateAnimalSql(String input) { String animalSql = "insert into animals values(%s, '%s', SDO_GEOMETRY(2001,NULL,SDO_POINT_TYPE(%s,%s,NULL),NULL,NULL))"; return String.format(animalSql, input.split(", ")); } }
UTF-8
Java
262
java
SqlHelper.java
Java
[]
null
[]
public class SqlHelper { public String generateAnimalSql(String input) { String animalSql = "insert into animals values(%s, '%s', SDO_GEOMETRY(2001,NULL,SDO_POINT_TYPE(%s,%s,NULL),NULL,NULL))"; return String.format(animalSql, input.split(", ")); } }
262
0.694656
0.679389
9
28
38.767113
122
false
false
0
0
0
0
0
0
2.222222
false
false
13
3a19cedae7802f8e9b6ff30d2f02ce82a54251fb
3,341,484,605,913
342fd5c4eba417d0b37a854945cf3a804afdc3b2
/aliblibrary/src/main/java/cn/hbjx/alib/observer/IObsArray.java
b50dadabde71aa1d16d118ee6a8ae0096150f14c
[]
no_license
hhhrc/aliblibrary
https://github.com/hhhrc/aliblibrary
25a6ebc2971604e95763497def4b111df30a8fca
d6736a7f228a331a1efc093347f3cbe33fe85f58
refs/heads/master
2021-07-20T09:53:20.964000
2017-10-31T04:27:03
2017-10-31T04:27:03
108,937,749
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.hbjx.alib.observer; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by DengYiQian on 2017/6/6. */ public interface IObsArray<T> { List<T> getList(); void setList(ArrayList<T> var1); void add(T var1); void remove(T var1); void remove(int var1); void add(int var1, T var2); void add(Collection<T> var1); void add(int var1, Collection<T> var2); void addObserverListener(IObsListener var1); void setObserverListener(IObsListener var1); void removeObserverListener(IObsListener var1); }
UTF-8
Java
600
java
IObsArray.java
Java
[ { "context": "lection;\nimport java.util.List;\n\n/**\n * Created by DengYiQian on 2017/6/6.\n */\n\npublic interface IObsArray<T> {", "end": 141, "score": 0.9997966885566711, "start": 131, "tag": "NAME", "value": "DengYiQian" } ]
null
[]
package cn.hbjx.alib.observer; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by DengYiQian on 2017/6/6. */ public interface IObsArray<T> { List<T> getList(); void setList(ArrayList<T> var1); void add(T var1); void remove(T var1); void remove(int var1); void add(int var1, T var2); void add(Collection<T> var1); void add(int var1, Collection<T> var2); void addObserverListener(IObsListener var1); void setObserverListener(IObsListener var1); void removeObserverListener(IObsListener var1); }
600
0.688333
0.658333
35
16.142857
17.489822
51
false
false
0
0
0
0
0
0
0.485714
false
false
13
d02fd028baf8ec838ef9d30694d848cbdd203fd7
36,979,668,433,170
bf07a468137352b6e00df67710774b882e8287d5
/FourStringsSquare.java
baf30efeae7d3351e90cf64f3764c73c6e4d9da2
[]
no_license
akilesh96/Java
https://github.com/akilesh96/Java
cbbb7aed15418ffe08968814ed2dddd5820c2444
1b14bc1a19f8a95203d5c981f8d4782dfa909761
refs/heads/master
2020-03-28T04:04:15.557000
2018-09-06T15:25:45
2018-09-06T15:25:45
147,692,574
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class FourStringsSquare { public static void main(String[] args) { Scanner s=new Scanner(System.in); String[]str=new String[4]; for(int i=0;i<4;i++) str[i]=s.next(); int len=str[0].length(); //System.out.println(len); char[][] mat=new char[len][len]; for(int j=0;j<len;j++) mat[0][j]=str[0].charAt(j); for(int i=1;i<len;i++) for(int j=0;j<len;j++) mat[i][j]='*'; int counter=0; char last=str[0].charAt(len-1); while(counter!=3){ //char last=str[counter].charAt(len-1); String sstr=null; int f=0; for(int i=0;i<4;i++) { if(last==str[i].charAt(0)){ sstr=str[i]; last=str[i].charAt(len-1); f=1; break; } } //System.out.println(sstr); if(counter==0&&f==1){ for(int i=1;i<len;i++) mat[i][len-1]=sstr.charAt(i); } if(counter==1&&f==1){ for(int i=len-2,j=1;i>=1;i--,j++){ mat[len-1][i]=sstr.charAt(j); } } if(counter==2&&f==1){ for(int i=len-1,j=0;i>=0;i--,j++) mat[i][0]=sstr.charAt(j); } counter++; } //display for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ System.out.print(mat[i][j]);} System.out.println(); } //System.out.println("Hi"); } }
UTF-8
Java
1,396
java
FourStringsSquare.java
Java
[]
null
[]
import java.util.*; public class FourStringsSquare { public static void main(String[] args) { Scanner s=new Scanner(System.in); String[]str=new String[4]; for(int i=0;i<4;i++) str[i]=s.next(); int len=str[0].length(); //System.out.println(len); char[][] mat=new char[len][len]; for(int j=0;j<len;j++) mat[0][j]=str[0].charAt(j); for(int i=1;i<len;i++) for(int j=0;j<len;j++) mat[i][j]='*'; int counter=0; char last=str[0].charAt(len-1); while(counter!=3){ //char last=str[counter].charAt(len-1); String sstr=null; int f=0; for(int i=0;i<4;i++) { if(last==str[i].charAt(0)){ sstr=str[i]; last=str[i].charAt(len-1); f=1; break; } } //System.out.println(sstr); if(counter==0&&f==1){ for(int i=1;i<len;i++) mat[i][len-1]=sstr.charAt(i); } if(counter==1&&f==1){ for(int i=len-2,j=1;i>=1;i--,j++){ mat[len-1][i]=sstr.charAt(j); } } if(counter==2&&f==1){ for(int i=len-1,j=0;i>=0;i--,j++) mat[i][0]=sstr.charAt(j); } counter++; } //display for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ System.out.print(mat[i][j]);} System.out.println(); } //System.out.println("Hi"); } }
1,396
0.469914
0.442693
56
22.964285
11.935787
45
false
false
0
0
0
0
0
0
2.696429
false
false
13
628e7f607ee5110b84c2ba7a0efe4338e800f5d3
15,324,443,367,595
62d3ec55742067cf0d769c69e04a86e25ebef20a
/src/main/java/signingToday/client/model/TrustedDevice.java
2a6662d03cdfe90b4a852992da062fca3c7462f3
[ "MIT" ]
permissive
signingtoday/signingtoday-sdk-java
https://github.com/signingtoday/signingtoday-sdk-java
4fa60a3599365f1f75fefbd417ba6dc27c30f183
1a6c6ff16a3483e66b69e78fefdfd5abd4891684
refs/heads/master
2022-05-29T14:14:30.351000
2020-03-24T08:26:37
2020-03-24T08:26:37
232,547,913
0
0
MIT
false
2022-05-20T21:20:59
2020-01-08T11:26:45
2020-03-24T08:26:49
2022-05-20T21:20:59
542
0
0
2
Java
false
false
/* * Signing Today Web * *Signing Today* is the perfect Digital Signature Gateway. Whenever in Your workflow You need to add one or more Digital Signatures to Your document, *Signing Today* is the right choice. You prepare Your documents, *Signing Today* takes care of all the rest: send invitations (`signature tickets`) to signers, collects their signatures, send You back the signed document. Integrating *Signing Today* in Your existing applications is very easy. Just follow these API specifications and get inspired by the many examples presented hereafter. * * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package signingToday.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.UUID; import org.threeten.bp.OffsetDateTime; /** * TrustedDevice */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-24T08:13:36.809Z[GMT]") public class TrustedDevice { public static final String SERIALIZED_NAME_INSTANCE_ID = "_instance_id"; @SerializedName(SERIALIZED_NAME_INSTANCE_ID) private Long instanceId; public static final String SERIALIZED_NAME_USER_ID = "userId"; @SerializedName(SERIALIZED_NAME_USER_ID) private UUID userId; public static final String SERIALIZED_NAME_DEVICE_ID = "deviceId"; @SerializedName(SERIALIZED_NAME_DEVICE_ID) private String deviceId; public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; public static final String SERIALIZED_NAME_REGISTERED_AT = "registeredAt"; @SerializedName(SERIALIZED_NAME_REGISTERED_AT) private OffsetDateTime registeredAt; /** * It is a reference for internal use * @return instanceId **/ @javax.annotation.Nullable @ApiModelProperty(example = "1", value = "It is a reference for internal use") public Long getInstanceId() { return instanceId; } public TrustedDevice userId(UUID userId) { this.userId = userId; return this; } /** * Get userId * @return userId **/ @javax.annotation.Nullable @ApiModelProperty(example = "737dc132-a3f0-11e9-a2a3-2a2ae2dbcce4", value = "") public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } public TrustedDevice deviceId(String deviceId) { this.deviceId = deviceId; return this; } /** * Get deviceId * @return deviceId **/ @javax.annotation.Nullable @ApiModelProperty(example = "e6419924-fd1d-4c42-9fa2-88023461f5df", value = "") public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public TrustedDevice name(String name) { this.name = name; return this; } /** * Application defined label to identify the device * @return name **/ @javax.annotation.Nullable @ApiModelProperty(example = "John Doe\"s Iphone", value = "Application defined label to identify the device") public String getName() { return name; } public void setName(String name) { this.name = name; } public TrustedDevice registeredAt(OffsetDateTime registeredAt) { this.registeredAt = registeredAt; return this; } /** * Get registeredAt * @return registeredAt **/ @javax.annotation.Nullable @ApiModelProperty(example = "2021-10-17T07:26Z", value = "") public OffsetDateTime getRegisteredAt() { return registeredAt; } public void setRegisteredAt(OffsetDateTime registeredAt) { this.registeredAt = registeredAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TrustedDevice trustedDevice = (TrustedDevice) o; return Objects.equals(this.instanceId, trustedDevice.instanceId) && Objects.equals(this.userId, trustedDevice.userId) && Objects.equals(this.deviceId, trustedDevice.deviceId) && Objects.equals(this.name, trustedDevice.name) && Objects.equals(this.registeredAt, trustedDevice.registeredAt); } @Override public int hashCode() { return Objects.hash(instanceId, userId, deviceId, name, registeredAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TrustedDevice {\n"); sb.append(" instanceId: ").append(toIndentedString(instanceId)).append("\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" deviceId: ").append(toIndentedString(deviceId)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" registeredAt: ").append(toIndentedString(registeredAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
UTF-8
Java
5,671
java
TrustedDevice.java
Java
[ { "context": "nnotation.Nullable\n @ApiModelProperty(example = \"John Doe\\\"s Iphone\", value = \"Application defined label to", "end": 3469, "score": 0.9933497905731201, "start": 3461, "tag": "NAME", "value": "John Doe" } ]
null
[]
/* * Signing Today Web * *Signing Today* is the perfect Digital Signature Gateway. Whenever in Your workflow You need to add one or more Digital Signatures to Your document, *Signing Today* is the right choice. You prepare Your documents, *Signing Today* takes care of all the rest: send invitations (`signature tickets`) to signers, collects their signatures, send You back the signed document. Integrating *Signing Today* in Your existing applications is very easy. Just follow these API specifications and get inspired by the many examples presented hereafter. * * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package signingToday.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.UUID; import org.threeten.bp.OffsetDateTime; /** * TrustedDevice */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-24T08:13:36.809Z[GMT]") public class TrustedDevice { public static final String SERIALIZED_NAME_INSTANCE_ID = "_instance_id"; @SerializedName(SERIALIZED_NAME_INSTANCE_ID) private Long instanceId; public static final String SERIALIZED_NAME_USER_ID = "userId"; @SerializedName(SERIALIZED_NAME_USER_ID) private UUID userId; public static final String SERIALIZED_NAME_DEVICE_ID = "deviceId"; @SerializedName(SERIALIZED_NAME_DEVICE_ID) private String deviceId; public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; public static final String SERIALIZED_NAME_REGISTERED_AT = "registeredAt"; @SerializedName(SERIALIZED_NAME_REGISTERED_AT) private OffsetDateTime registeredAt; /** * It is a reference for internal use * @return instanceId **/ @javax.annotation.Nullable @ApiModelProperty(example = "1", value = "It is a reference for internal use") public Long getInstanceId() { return instanceId; } public TrustedDevice userId(UUID userId) { this.userId = userId; return this; } /** * Get userId * @return userId **/ @javax.annotation.Nullable @ApiModelProperty(example = "737dc132-a3f0-11e9-a2a3-2a2ae2dbcce4", value = "") public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } public TrustedDevice deviceId(String deviceId) { this.deviceId = deviceId; return this; } /** * Get deviceId * @return deviceId **/ @javax.annotation.Nullable @ApiModelProperty(example = "e6419924-fd1d-4c42-9fa2-88023461f5df", value = "") public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public TrustedDevice name(String name) { this.name = name; return this; } /** * Application defined label to identify the device * @return name **/ @javax.annotation.Nullable @ApiModelProperty(example = "<NAME>\"s Iphone", value = "Application defined label to identify the device") public String getName() { return name; } public void setName(String name) { this.name = name; } public TrustedDevice registeredAt(OffsetDateTime registeredAt) { this.registeredAt = registeredAt; return this; } /** * Get registeredAt * @return registeredAt **/ @javax.annotation.Nullable @ApiModelProperty(example = "2021-10-17T07:26Z", value = "") public OffsetDateTime getRegisteredAt() { return registeredAt; } public void setRegisteredAt(OffsetDateTime registeredAt) { this.registeredAt = registeredAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TrustedDevice trustedDevice = (TrustedDevice) o; return Objects.equals(this.instanceId, trustedDevice.instanceId) && Objects.equals(this.userId, trustedDevice.userId) && Objects.equals(this.deviceId, trustedDevice.deviceId) && Objects.equals(this.name, trustedDevice.name) && Objects.equals(this.registeredAt, trustedDevice.registeredAt); } @Override public int hashCode() { return Objects.hash(instanceId, userId, deviceId, name, registeredAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TrustedDevice {\n"); sb.append(" instanceId: ").append(toIndentedString(instanceId)).append("\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" deviceId: ").append(toIndentedString(deviceId)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" registeredAt: ").append(toIndentedString(registeredAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
5,669
0.700935
0.688062
207
26.391304
44.119804
542
false
false
0
0
0
0
0
0
0.376812
false
false
13
14510fc4ac385504ff14910416119618aa002c8f
17,540,646,497,235
ffa4f66ff699cbe0c9280631d06258d1439a0cd8
/src/test/java/TestMapperTest.java
ac9cc5e12cf3ba21926656bc1105bf19701923cc
[]
no_license
kenny-Turtle/ssmshop
https://github.com/kenny-Turtle/ssmshop
2efbbcb017d401a9e2f3cd56d3d009a52a5c3f11
fe5de51a540c685147428d20add79f34d0582665
refs/heads/master
2022-12-26T17:18:04.338000
2020-03-09T11:27:54
2020-03-09T11:27:54
246,017,351
0
0
null
false
2022-12-16T15:21:54
2020-03-09T11:26:17
2020-03-09T11:31:23
2022-12-16T15:21:51
41,446
0
0
9
Java
false
false
import com.zfj.mapper.CategoryMapper; import com.zfj.mapper.TestMapper; import com.zfj.mapper.UserMapper; import com.zfj.pojo.Category; import com.zfj.pojo.TestExample; import com.zfj.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * @Author zfj * @create 2020/2/24 13:39 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mybatis.xml"}) public class TestMapperTest { @Autowired private TestMapper testMapper; @Autowired private CategoryMapper categoryMapper; @Autowired private UserMapper userMapper; @Test public void test1(){ com.zfj.pojo.Test tt = new com.zfj.pojo.Test(); tt.setId(4); tt.setUsername("小杰"); testMapper.insert(tt); System.out.println("添加成功"); } @Test public void test02(){ List<com.zfj.pojo.Test> tests = testMapper.selectByExample(); System.out.println( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+tests+ "<<<<<<<<<<<<<<<<<<<<<<<<<<<"); } @Test public void test03(){ com.zfj.pojo.Test test = testMapper.selectByPrimaryKey(2); System.out.println(">>>>>>>>>>>>>>"+test+"<<<<<<<<<<<<<<<<<<"); } @Test public void test04(){ Category category = categoryMapper.selectByPrimaryKey(3); System.out.println(">>>>>>>>>"+category.getName()+"<<<<<<<<<<<<<<<<<<"); } @Test public void test06(){ // boolean isexit = userService.isExist("张逢杰"); User user = userMapper.selectByName("张逢杰"); List<User> users = userMapper.selectByExample(); // System.out.println(">>>>>>>>>>"+user.getName()+";"+user.getPassword()+"<<<<<<<<"); System.out.println(users); } }
UTF-8
Java
2,030
java
TestMapperTest.java
Java
[ { "context": "assRunner;\n\nimport java.util.List;\n\n/**\n * @Author zfj\n * @create 2020/2/24 13:39\n */\n@RunWith(SpringJUn", "end": 491, "score": 0.9997409582138062, "start": 488, "tag": "USERNAME", "value": "zfj" }, { "context": "t();\n tt.setId(4);\n tt.setUsernam...
null
[]
import com.zfj.mapper.CategoryMapper; import com.zfj.mapper.TestMapper; import com.zfj.mapper.UserMapper; import com.zfj.pojo.Category; import com.zfj.pojo.TestExample; import com.zfj.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * @Author zfj * @create 2020/2/24 13:39 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mybatis.xml"}) public class TestMapperTest { @Autowired private TestMapper testMapper; @Autowired private CategoryMapper categoryMapper; @Autowired private UserMapper userMapper; @Test public void test1(){ com.zfj.pojo.Test tt = new com.zfj.pojo.Test(); tt.setId(4); tt.setUsername("小杰"); testMapper.insert(tt); System.out.println("添加成功"); } @Test public void test02(){ List<com.zfj.pojo.Test> tests = testMapper.selectByExample(); System.out.println( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+tests+ "<<<<<<<<<<<<<<<<<<<<<<<<<<<"); } @Test public void test03(){ com.zfj.pojo.Test test = testMapper.selectByPrimaryKey(2); System.out.println(">>>>>>>>>>>>>>"+test+"<<<<<<<<<<<<<<<<<<"); } @Test public void test04(){ Category category = categoryMapper.selectByPrimaryKey(3); System.out.println(">>>>>>>>>"+category.getName()+"<<<<<<<<<<<<<<<<<<"); } @Test public void test06(){ // boolean isexit = userService.isExist("张逢杰"); User user = userMapper.selectByName("张逢杰"); List<User> users = userMapper.selectByExample(); // System.out.println(">>>>>>>>>>"+user.getName()+";"+user.getPassword()+"<<<<<<<<"); System.out.println(users); } }
2,030
0.608175
0.595214
66
29.39394
23.720518
92
false
false
0
0
0
0
0
0
0.484848
false
false
13
2c34688b93b2695544558819d1ec9fea025bbc31
37,022,618,104,476
42aa50a8a946e1350f3e2ef35361b19bbc4d2049
/src/main/java/io/yun/dao/TYunDemandReplyDao.java
fdd5f26c0162f05bcbb6c15d7be104ba9dfbd2c9
[ "Apache-2.0" ]
permissive
xuyuqin/xuyuqin
https://github.com/xuyuqin/xuyuqin
bcd5ef323ca63572f1bc09541525dff81d16e43d
1261e7486464876d903e3df35cecc308d166806d
refs/heads/master
2021-01-01T04:38:38.499000
2017-08-07T02:20:35
2017-08-07T02:20:35
97,217,810
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.yun.dao; import io.unicall.dao.BaseDao; import io.yun.entity.TYunDemandReplyEntity; /** * 求购单报价表 * * @author unicall * @email bq.zhu@unicall.com * @date 2017-06-27 14:05:08 */ public interface TYunDemandReplyDao extends BaseDao<TYunDemandReplyEntity> { }
UTF-8
Java
289
java
TYunDemandReplyDao.java
Java
[ { "context": "unDemandReplyEntity;\n\n/**\n * 求购单报价表\n * \n * @author unicall\n * @email bq.zhu@unicall.com\n * @date 2017-06-27 ", "end": 133, "score": 0.9996044039726257, "start": 126, "tag": "USERNAME", "value": "unicall" }, { "context": "y;\n\n/**\n * 求购单报价表\n * \n * @author unic...
null
[]
package io.yun.dao; import io.unicall.dao.BaseDao; import io.yun.entity.TYunDemandReplyEntity; /** * 求购单报价表 * * @author unicall * @email <EMAIL> * @date 2017-06-27 14:05:08 */ public interface TYunDemandReplyDao extends BaseDao<TYunDemandReplyEntity> { }
278
0.732852
0.68231
15
17.466667
20.512978
76
false
false
0
0
0
0
0
0
0.266667
false
false
13
3820fc01920388233cda4ddb39fe08de389d6c12
3,118,146,311,312
3c2b10c2bfedcaa2556698dc0a155911b43ba045
/code/real-estate-sales-manager/src/main/java/com/zx/base/model/FileBean.java
b884b8fa256b9d0b1c29272d90538028abc2ecf1
[]
no_license
inh3r1t/real-estate-sales
https://github.com/inh3r1t/real-estate-sales
5c15ced3492b95dd42970866530478e9693f2123
55cf27ab58062c9fd1e904117f7cd92323448292
refs/heads/master
2022-07-07T14:28:42.487000
2020-11-19T01:59:36
2020-11-19T01:59:36
158,639,050
0
0
null
false
2022-06-29T17:04:39
2018-11-22T03:44:12
2020-11-19T02:01:09
2022-06-29T17:04:38
15,179
0
0
4
JavaScript
false
false
package com.zx.base.model; import java.io.Serializable; /** * 文件对象 * * @author V.E. * @version 2017/12/11 */ @SuppressWarnings("serial") public class FileBean implements Serializable { private String filePath; private String fileName; private String fileSize; private String fileType; private String fileLastModifiedTime; public FileBean() {} public FileBean(String filePath, String fileName, String fileSize, String fileType,String fileLastModifiedTime) { super(); this.filePath = filePath; this.fileName = fileName; this.fileSize = fileSize; this.fileType = fileType; this.fileLastModifiedTime = fileLastModifiedTime; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileLastModifiedTime() { return fileLastModifiedTime; } public void setFileLastModifiedTime(String fileLastModifiedTime) { this.fileLastModifiedTime = fileLastModifiedTime; } }
UTF-8
Java
1,585
java
FileBean.java
Java
[ { "context": "t java.io.Serializable;\n\n/**\n * 文件对象\n *\n * @author V.E.\n * @version 2017/12/11\n */\n\n@SuppressWarnings(\"se", "end": 87, "score": 0.999157190322876, "start": 84, "tag": "NAME", "value": "V.E" } ]
null
[]
package com.zx.base.model; import java.io.Serializable; /** * 文件对象 * * @author V.E. * @version 2017/12/11 */ @SuppressWarnings("serial") public class FileBean implements Serializable { private String filePath; private String fileName; private String fileSize; private String fileType; private String fileLastModifiedTime; public FileBean() {} public FileBean(String filePath, String fileName, String fileSize, String fileType,String fileLastModifiedTime) { super(); this.filePath = filePath; this.fileName = fileName; this.fileSize = fileSize; this.fileType = fileType; this.fileLastModifiedTime = fileLastModifiedTime; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileLastModifiedTime() { return fileLastModifiedTime; } public void setFileLastModifiedTime(String fileLastModifiedTime) { this.fileLastModifiedTime = fileLastModifiedTime; } }
1,585
0.6487
0.643627
72
20.902779
19.49869
70
false
false
0
0
0
0
0
0
0.375
false
false
13
15191a3ec3209e9a344285068765c48624c1f0b6
23,768,349,069,152
4f77a4ad924a386f6c98d89511390a5da9d11848
/multithreadpattern.java
a1887644782e216eb15bb8d8c1fd27fd9b86978e
[]
no_license
AbhishekGirkar/Java_Lab_Second-year
https://github.com/AbhishekGirkar/Java_Lab_Second-year
64c46f4e9e7fe34c38a9bff6f89cf2082ac92033
47852308f35ad7bd2d9ae801443a5cd19048a0c9
refs/heads/master
2022-12-13T15:55:31.493000
2020-09-12T17:50:00
2020-09-12T17:50:00
294,994,654
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class alpha extends Thread { public void run() { for(char i = 65; i<=74; i++) { System.out.println(i); try{ Thread.sleep(1000); //Change this Value if u don't get desired output } catch(InterruptedException e){} } } } class digit extends Thread { public void run() { for(int i=1; i<=10; i++) { System.out.println(i); try{ Thread.sleep(1000); //Change this Value if u don't get desired output } catch(InterruptedException e){} } } } public class multithreadpattern { public static void main(String[] args) { digit a = new digit(); alpha b = new alpha(); a.start(); b.start(); try { a.join(); b.join(); }catch(InterruptedException e){} } }
UTF-8
Java
679
java
multithreadpattern.java
Java
[]
null
[]
class alpha extends Thread { public void run() { for(char i = 65; i<=74; i++) { System.out.println(i); try{ Thread.sleep(1000); //Change this Value if u don't get desired output } catch(InterruptedException e){} } } } class digit extends Thread { public void run() { for(int i=1; i<=10; i++) { System.out.println(i); try{ Thread.sleep(1000); //Change this Value if u don't get desired output } catch(InterruptedException e){} } } } public class multithreadpattern { public static void main(String[] args) { digit a = new digit(); alpha b = new alpha(); a.start(); b.start(); try { a.join(); b.join(); }catch(InterruptedException e){} } }
679
0.639175
0.617084
43
13.83721
14.095901
49
false
false
0
0
0
0
0
0
0.325581
false
false
13
c7ed8d53160ccd698a9b5b4fb83b5ba0245f40e6
25,726,854,169,310
9dccfdd702254911c27dcbad607fefa942727b08
/app/src/main/java/com/example/robotcrudapp/fragments/UpdateRobotFragment.java
8b0af5adee0043b85feed5bf20243ca2ccae5caa
[]
no_license
Oleg700/RobotCRUDApp
https://github.com/Oleg700/RobotCRUDApp
77be1991ba711fdc3e828aa249791cbc4471ed88
329882f67b4c724fd838bd22d3fe55f826edc97e
refs/heads/master
2020-05-24T13:47:05.941000
2019-05-20T23:09:52
2019-05-20T23:09:52
187,069,976
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.robotcrudapp.fragments; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.robotcrudapp.R; import com.example.robotcrudapp.constants.Constant; import com.example.robotcrudapp.model.Robot; import com.example.robotcrudapp.viewmodel.MainActivityViewModel; public class UpdateRobotFragment extends Fragment { private EditText robotName, robotType, robotYear; private Button buttonUpdate; private MainActivityViewModel mMainActivityViewModel; public UpdateRobotFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_update_robot, container, false); robotName = view.findViewById(R.id.txt_robot_name); robotType = view.findViewById(R.id.txt_robot_type); robotYear = view.findViewById(R.id.txt_robot_year); buttonUpdate = view.findViewById(R.id.bn_update_robot); buttonUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = getArguments(); int robotIdSet = Integer.parseInt(bundle.getString(Constant.ROBOT_ID)); String robotNameSet = robotName.getText().toString(); String robotTypeSet = robotType.getText().toString(); int robotYearSet = Integer.parseInt(robotYear.getText().toString()); Robot robotToInsert = new Robot(); robotToInsert.setId(robotIdSet); robotToInsert.setName(robotNameSet); robotToInsert.setType(robotTypeSet); robotToInsert.setYear(robotYearSet); updateRobot(robotIdSet, robotToInsert); getFragmentManager() .beginTransaction() .replace(R.id.fragment_container, new ListRobotFragment()) .commit(); } }); return view; } private void updateRobot(int id, Robot robot) { mMainActivityViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class); mMainActivityViewModel.init(); mMainActivityViewModel.updateRobot(id, robot); Toast.makeText(getActivity(), "Robot with id " + "is updated", Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
2,679
java
UpdateRobotFragment.java
Java
[]
null
[]
package com.example.robotcrudapp.fragments; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.robotcrudapp.R; import com.example.robotcrudapp.constants.Constant; import com.example.robotcrudapp.model.Robot; import com.example.robotcrudapp.viewmodel.MainActivityViewModel; public class UpdateRobotFragment extends Fragment { private EditText robotName, robotType, robotYear; private Button buttonUpdate; private MainActivityViewModel mMainActivityViewModel; public UpdateRobotFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_update_robot, container, false); robotName = view.findViewById(R.id.txt_robot_name); robotType = view.findViewById(R.id.txt_robot_type); robotYear = view.findViewById(R.id.txt_robot_year); buttonUpdate = view.findViewById(R.id.bn_update_robot); buttonUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = getArguments(); int robotIdSet = Integer.parseInt(bundle.getString(Constant.ROBOT_ID)); String robotNameSet = robotName.getText().toString(); String robotTypeSet = robotType.getText().toString(); int robotYearSet = Integer.parseInt(robotYear.getText().toString()); Robot robotToInsert = new Robot(); robotToInsert.setId(robotIdSet); robotToInsert.setName(robotNameSet); robotToInsert.setType(robotTypeSet); robotToInsert.setYear(robotYearSet); updateRobot(robotIdSet, robotToInsert); getFragmentManager() .beginTransaction() .replace(R.id.fragment_container, new ListRobotFragment()) .commit(); } }); return view; } private void updateRobot(int id, Robot robot) { mMainActivityViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class); mMainActivityViewModel.init(); mMainActivityViewModel.updateRobot(id, robot); Toast.makeText(getActivity(), "Robot with id " + "is updated", Toast.LENGTH_SHORT).show(); } }
2,679
0.66928
0.668906
69
37.826088
27.11861
98
false
false
0
0
0
0
0
0
0.753623
false
false
13
12f74577a3b8008b3d49c4e2e1449e57f11f688a
27,530,740,423,639
63dd45f84c66fd120d37e535197a9cba094e2568
/src/test/java/br/com/crudhightech/test/TestUsuarioPersistenceDAO.java
7fb5320b66cfb3c4f75cf88d8271d112824f99b7
[]
no_license
mrcllw/CRUD-HighTech
https://github.com/mrcllw/CRUD-HighTech
bda62b45c1241567d42da1e9419005f2e686440a
47196adc625d1d48f137a7fb0b28de1b611e7580
refs/heads/master
2021-01-20T17:32:54.298000
2016-06-16T03:47:18
2016-06-16T03:47:18
61,260,246
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.crudhightech.test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import br.com.crudhightech.entity.Usuario; import br.com.crudhightech.exception.DAOException; import br.com.crudhightech.repository.UsuarioDAOJPA; public class TestUsuarioPersistenceDAO { public static void main(String[] args) throws DAOException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("crudHightech"); EntityManager em = emf.createEntityManager(); Usuario usu = new Usuario(); usu.setEmail("m@m.com"); usu.setPassword("123"); UsuarioDAOJPA usuarioDAO = new UsuarioDAOJPA(em); //SALVAR usuarioDAO.save(usu); //BUSCAR Usuario usuMod = usuarioDAO.findById(2); System.out.println(usuMod); //EDITAR //usuMod.setEmail("mm@mm.com"); //usuarioDAO.edit(usuMod); //System.out.println(usuMod); //EXCLUIR //usuarioDAO.delete(usuMod); } }
UTF-8
Java
977
java
TestUsuarioPersistenceDAO.java
Java
[ { "context": "\t\t\n\t\tUsuario usu = new Usuario();\n\t\tusu.setEmail(\"m@m.com\");\n\t\tusu.setPassword(\"123\");\n\t\t\n\t\tUsuarioDAOJPA u", "end": 607, "score": 0.999920666217804, "start": 600, "tag": "EMAIL", "value": "m@m.com" }, { "context": "();\n\t\tusu.setEmail(\"m@m.com\"...
null
[]
package br.com.crudhightech.test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import br.com.crudhightech.entity.Usuario; import br.com.crudhightech.exception.DAOException; import br.com.crudhightech.repository.UsuarioDAOJPA; public class TestUsuarioPersistenceDAO { public static void main(String[] args) throws DAOException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("crudHightech"); EntityManager em = emf.createEntityManager(); Usuario usu = new Usuario(); usu.setEmail("<EMAIL>"); usu.setPassword("123"); UsuarioDAOJPA usuarioDAO = new UsuarioDAOJPA(em); //SALVAR usuarioDAO.save(usu); //BUSCAR Usuario usuMod = usuarioDAO.findById(2); System.out.println(usuMod); //EDITAR //usuMod.setEmail("<EMAIL>"); //usuarioDAO.edit(usuMod); //System.out.println(usuMod); //EXCLUIR //usuarioDAO.delete(usuMod); } }
975
0.749232
0.745138
39
24.051283
21.009092
84
false
false
0
0
0
0
0
0
1.820513
false
false
13
ee0aaf64f48180f7656a147f2e5f465133ef6744
37,580,963,859,047
c9fbb47d51a444524f2f743410fa29ba04bad5f3
/app/src/main/java/com/example/onlineshop/view/ConnectionFragment.java
e2c21391b13a23faaf3b60374a75f19d0c84d912
[]
no_license
z-liaghat/OnlineShop
https://github.com/z-liaghat/OnlineShop
69dcef44a9af3a49c8eccc44c67e46455db15e94
cd2adf989efdbb0bb388bc5a2dcbb28d0dea73be
refs/heads/master
2020-09-11T05:25:29.333000
2020-03-04T12:09:15
2020-03-04T12:09:15
221,953,571
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.onlineshop.view; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import com.example.onlineshop.R; import com.example.onlineshop.network.WooCommerceRepository; import com.example.onlineshop.utils.NetworkHelper; import com.google.android.material.snackbar.Snackbar; /** * A simple {@link Fragment} subclass. */ public class ConnectionFragment extends Fragment implements WooCommerceRepository.NetworkErrorCallBack { public ConnectionFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!NetworkHelper.isConnected(getActivity())) { Intent intent = NoInternetActivity.newIntent(getActivity()); startActivity(intent); getActivity().finish(); } WooCommerceRepository.getsInstance().setNetworkErrorCallBack(this); } @Override public void onFail(String errorMessage) { // new AlertDialog.Builder(getActivity()) // .setMessage(errorMessage) // .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialogInterface, int i) { // dialogInterface.dismiss(); // } // }) // // .setView(this.getView()) // .create().show(); Snackbar snackbar = Snackbar .make(this.getView(), "" + errorMessage, Snackbar.LENGTH_LONG) .setAction(android.R.string.ok, new View.OnClickListener() { @Override public void onClick(View view) { // Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Message is restored!", Snackbar.LENGTH_SHORT); // snackbar1.show(); } }); View view = snackbar.getView(); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams(); params.gravity = Gravity.TOP; // calculate actionbar height TypedValue tv = new TypedValue(); int actionBarHeight = 0; if (getActivity().getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics()); } // set margin params.setMargins(0, actionBarHeight, 0, 0); view.setLayoutParams(params); snackbar.show(); } }
UTF-8
Java
3,000
java
ConnectionFragment.java
Java
[]
null
[]
package com.example.onlineshop.view; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import com.example.onlineshop.R; import com.example.onlineshop.network.WooCommerceRepository; import com.example.onlineshop.utils.NetworkHelper; import com.google.android.material.snackbar.Snackbar; /** * A simple {@link Fragment} subclass. */ public class ConnectionFragment extends Fragment implements WooCommerceRepository.NetworkErrorCallBack { public ConnectionFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!NetworkHelper.isConnected(getActivity())) { Intent intent = NoInternetActivity.newIntent(getActivity()); startActivity(intent); getActivity().finish(); } WooCommerceRepository.getsInstance().setNetworkErrorCallBack(this); } @Override public void onFail(String errorMessage) { // new AlertDialog.Builder(getActivity()) // .setMessage(errorMessage) // .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialogInterface, int i) { // dialogInterface.dismiss(); // } // }) // // .setView(this.getView()) // .create().show(); Snackbar snackbar = Snackbar .make(this.getView(), "" + errorMessage, Snackbar.LENGTH_LONG) .setAction(android.R.string.ok, new View.OnClickListener() { @Override public void onClick(View view) { // Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Message is restored!", Snackbar.LENGTH_SHORT); // snackbar1.show(); } }); View view = snackbar.getView(); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams(); params.gravity = Gravity.TOP; // calculate actionbar height TypedValue tv = new TypedValue(); int actionBarHeight = 0; if (getActivity().getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics()); } // set margin params.setMargins(0, actionBarHeight, 0, 0); view.setLayoutParams(params); snackbar.show(); } }
3,000
0.640333
0.638333
92
31.608696
28.8813
127
false
false
0
0
0
0
0
0
0.532609
false
false
13
0aeefe0595375fe471442e177a81959e20dc9469
4,844,723,143,201
7485a64fdfc29c4e2b397ffd4155ba1d3ff3eedc
/SRC/Supernet/SuperNet2007/src/com/santander/supernet/beans/pagos/PagoImpuestosBean.java
8e41c864f18b1f18d61ac23b01f195be1d569a19
[]
no_license
CEyC/FSW
https://github.com/CEyC/FSW
e640d9eff5db737de909ed5954560342bac42978
a44ef4b188aacf03aa4d9c4fd7050d4a48bf5be6
refs/heads/master
2017-11-28T09:31:25.158000
2016-06-02T18:05:13
2016-06-02T18:05:13
40,670,638
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.santander.supernet.beans.pagos; import java.io.Serializable; import com.santander.supernet.servicios.CreacomprobantePDF; public class PagoImpuestosBean implements Serializable{ /** Serial ID */ private static final long serialVersionUID = 1L; /** Comprobante Pdf. */ private CreacomprobantePDF creacomprobantePDF; /** Nombre comprobante Pdf */ private String nombrePDF; /** Comprobante XML. */ private String comprobanteXML; /** * Constructor */ public PagoImpuestosBean(){ comprobanteXML = ""; } /** * @return the comprobanteXML */ public String getComprobanteXML() { return comprobanteXML; } /** * @param comprobanteXML the comprobanteXML to set */ public void setComprobanteXML(String comprobanteXML) { this.comprobanteXML = comprobanteXML; } /** * @return the creacomprobantePDF */ public CreacomprobantePDF getCreacomprobantePDF() { return creacomprobantePDF; } /** * @param creacomprobantePDF the creacomprobantePDF to set */ public void setCreacomprobantePDF(CreacomprobantePDF creacomprobantePDF) { this.creacomprobantePDF = creacomprobantePDF; } /** * @return the nombrePDF */ public String getNombrePDF() { return nombrePDF; } /** * @param nombrePDF the nombrePDF to set */ public void setNombrePDF(String nombrePDF) { this.nombrePDF = nombrePDF; } }
UTF-8
Java
1,361
java
PagoImpuestosBean.java
Java
[]
null
[]
package com.santander.supernet.beans.pagos; import java.io.Serializable; import com.santander.supernet.servicios.CreacomprobantePDF; public class PagoImpuestosBean implements Serializable{ /** Serial ID */ private static final long serialVersionUID = 1L; /** Comprobante Pdf. */ private CreacomprobantePDF creacomprobantePDF; /** Nombre comprobante Pdf */ private String nombrePDF; /** Comprobante XML. */ private String comprobanteXML; /** * Constructor */ public PagoImpuestosBean(){ comprobanteXML = ""; } /** * @return the comprobanteXML */ public String getComprobanteXML() { return comprobanteXML; } /** * @param comprobanteXML the comprobanteXML to set */ public void setComprobanteXML(String comprobanteXML) { this.comprobanteXML = comprobanteXML; } /** * @return the creacomprobantePDF */ public CreacomprobantePDF getCreacomprobantePDF() { return creacomprobantePDF; } /** * @param creacomprobantePDF the creacomprobantePDF to set */ public void setCreacomprobantePDF(CreacomprobantePDF creacomprobantePDF) { this.creacomprobantePDF = creacomprobantePDF; } /** * @return the nombrePDF */ public String getNombrePDF() { return nombrePDF; } /** * @param nombrePDF the nombrePDF to set */ public void setNombrePDF(String nombrePDF) { this.nombrePDF = nombrePDF; } }
1,361
0.728141
0.727406
69
18.724638
20.020195
75
false
false
0
0
0
0
0
0
1.086957
false
false
13
a28fed5b18d3fd0c01508f6c5a01011200a8a4d6
32,083,405,756,759
6d7fe2b101f2f946d1a2bfd7ba924e4bb15bece8
/src/main/java/fr/unilim/iut/spaceinvaders/model/DessinSpaceInvaders.java
3242deedb60369b135943058415486af01f391c1
[ "MIT" ]
permissive
JulesDufosse/spaceinvaders
https://github.com/JulesDufosse/spaceinvaders
964f928f5a4b6ff398705bc636fedd94faad7437
e3001e1878caccb92d65ccc01eb399bc6decb6d4
refs/heads/master
2021-07-03T15:27:39.264000
2019-06-05T15:20:20
2019-06-05T15:20:20
180,378,768
0
0
MIT
false
2020-10-13T12:46:20
2019-04-09T13:56:26
2019-06-05T15:21:57
2020-10-13T12:46:19
151
0
0
1
Java
false
false
package fr.unilim.iut.spaceinvaders.model; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import fr.unilim.iut.spaceinvaders.moteurjeu.DessinJeu; public class DessinSpaceInvaders implements DessinJeu { private SpaceInvaders jeu; public DessinSpaceInvaders(SpaceInvaders spaceInvaders) { this.jeu = spaceInvaders; } @Override public void dessiner(BufferedImage im) { if (this.jeu.aUnVaisseau()) { Vaisseau vaisseau = this.jeu.recupererVaisseau(); this.dessinerUnVaisseau(vaisseau, im); if (this.jeu.aUnMissile()) { Missile missile = this.jeu.recupererMissile(); this.dessinerUnMissile(missile, im); } if(this.jeu.aUnEnvahisseur()) { Envahisseur envahisseur =this.jeu.recuperEnvahisseur(); this.dessinerUnEnvahisseur(envahisseur, im); } } } private void dessinerUnVaisseau(Vaisseau vaisseau, BufferedImage im) { Graphics2D crayon = (Graphics2D) im.getGraphics(); crayon.setColor(Color.gray); crayon.fillRect(vaisseau.abscisseLaPlusAGauche(), vaisseau.ordonneeLaPlusBasse(), vaisseau.longueur(), vaisseau.hauteur()); } private void dessinerUnMissile(Missile missile, BufferedImage im) { Graphics2D crayon = (Graphics2D) im.getGraphics(); crayon.setColor(Color.blue); crayon.fillRect(missile.abscisseLaPlusAGauche(), missile.ordonneeLaPlusBasse(), missile.longueur(),missile.hauteur()); } private void dessinerUnEnvahisseur(Envahisseur envahisseur,BufferedImage im) { Graphics2D crayon =(Graphics2D) im.getGraphics(); crayon.setColor(Color.green); crayon.fillRect(envahisseur.abscisseLaPlusAGauche(), envahisseur.ordonneeLaPlusBasse(), envahisseur.longueur(), envahisseur.hauteur()); } }
UTF-8
Java
1,772
java
DessinSpaceInvaders.java
Java
[]
null
[]
package fr.unilim.iut.spaceinvaders.model; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import fr.unilim.iut.spaceinvaders.moteurjeu.DessinJeu; public class DessinSpaceInvaders implements DessinJeu { private SpaceInvaders jeu; public DessinSpaceInvaders(SpaceInvaders spaceInvaders) { this.jeu = spaceInvaders; } @Override public void dessiner(BufferedImage im) { if (this.jeu.aUnVaisseau()) { Vaisseau vaisseau = this.jeu.recupererVaisseau(); this.dessinerUnVaisseau(vaisseau, im); if (this.jeu.aUnMissile()) { Missile missile = this.jeu.recupererMissile(); this.dessinerUnMissile(missile, im); } if(this.jeu.aUnEnvahisseur()) { Envahisseur envahisseur =this.jeu.recuperEnvahisseur(); this.dessinerUnEnvahisseur(envahisseur, im); } } } private void dessinerUnVaisseau(Vaisseau vaisseau, BufferedImage im) { Graphics2D crayon = (Graphics2D) im.getGraphics(); crayon.setColor(Color.gray); crayon.fillRect(vaisseau.abscisseLaPlusAGauche(), vaisseau.ordonneeLaPlusBasse(), vaisseau.longueur(), vaisseau.hauteur()); } private void dessinerUnMissile(Missile missile, BufferedImage im) { Graphics2D crayon = (Graphics2D) im.getGraphics(); crayon.setColor(Color.blue); crayon.fillRect(missile.abscisseLaPlusAGauche(), missile.ordonneeLaPlusBasse(), missile.longueur(),missile.hauteur()); } private void dessinerUnEnvahisseur(Envahisseur envahisseur,BufferedImage im) { Graphics2D crayon =(Graphics2D) im.getGraphics(); crayon.setColor(Color.green); crayon.fillRect(envahisseur.abscisseLaPlusAGauche(), envahisseur.ordonneeLaPlusBasse(), envahisseur.longueur(), envahisseur.hauteur()); } }
1,772
0.739278
0.735327
56
29.642857
31.727314
137
false
false
0
0
0
0
0
0
2.035714
false
false
13
851442e351f33d5b236b73bb4f256f1bf6f3d44a
32,083,405,756,252
eeed12cca2ae295031fb442fb468abbe0de4235e
/src/main/java/leetCode/graphs/RedundantConnection.java
6592e55fa906dd11047dc57466255bc174a9ea31
[]
no_license
JesusNunez1031/Coding-Questions
https://github.com/JesusNunez1031/Coding-Questions
a248a9ad1ae78cc92c8b8a211ab47a2f2781cd49
a96163d3009009f4697c12964299345c3f2f96ca
refs/heads/master
2022-12-23T07:54:15.541000
2022-12-23T06:37:08
2022-12-23T06:37:08
164,381,536
0
1
null
false
2022-12-23T06:37:08
2019-01-07T05:15:22
2022-01-11T02:14:32
2022-12-23T06:37:08
1,109
0
0
0
Java
false
false
package leetCode.graphs; public class RedundantConnection { /* In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input. Example 1: [1]--[2] | / | / [3] Input: edges = [[1,2],[1,3],[2,3]] Output: [2,3] Example 2: [2]--[3]--[5] | | [1]--[4] Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]] Output: [1,4] Constraints: 1. n == edges.length 2. 3 <= n <= 1000 3. edges[i].length == 2 4. 1 <= ai < bi <= edges.length 5. ai != bi 6. There are no repeated edges. 7. The given graph is connected. */ // array of all n nodes that can be found in graph int[] nodes; //TC/S: O(n) public int[] findRedundantConnection(int[][] edges) { nodes = new int[edges.length + 1]; // n == edges.length /* to use union-find, self root each node, as new connections are found, the root of the connected nodes will be combined under one node, e.g. if [1,2] [2,3], the root of 2 and 3 will be 1 */ for (int i = 0; i <= edges.length; i++) { nodes[i] = i; } /* loop through all the edges in the graph, get the roots of the two nodes connected, if their roots match that means a cycle was found, i.e. the nodes connect through other nodes, so the cyclic edge is returned since there is only one cycle edge, otherwise merge the two nodes under one root, "from" */ for (int[] edge : edges) { int from = edge[0]; int to = edge[1]; if (find(from) == find(to)) { return edge; } else { union(from, to); } } //no cycles detected return new int[]{-1, -1}; } //returns the root of the given node p private int find(int p) { /* p is the node which we want to find the root for, so while the root of p != p, i.e. not self rooted, get the to the root of p by searching through all connected nodes e.g. if [0, 1] [1,2] and [2,3] edges have been seen so far then the array of nodes = [0, 1, 2, 3] and roots = [0, 0, 1, 1] to get the root the root of 3, we check of 3 == 1, since 3 is not self rooted, we move to its root 1, 1 != 0, so we move to its root 0, 0 == 0 so the root has been found */ while (nodes[p] != p) { p = nodes[p]; } return p; } //unites p and q if they don't already belong in the same union set private void union(int p, int q) { //get the roots of both nodes p and q int rootP = find(p); int rootQ = find(q); //if the nodes are not part of the same tree, set the root of the subtree to the root Q if (rootP != rootQ) { nodes[rootP] = rootQ; } } }
UTF-8
Java
3,548
java
RedundantConnection.java
Java
[]
null
[]
package leetCode.graphs; public class RedundantConnection { /* In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input. Example 1: [1]--[2] | / | / [3] Input: edges = [[1,2],[1,3],[2,3]] Output: [2,3] Example 2: [2]--[3]--[5] | | [1]--[4] Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]] Output: [1,4] Constraints: 1. n == edges.length 2. 3 <= n <= 1000 3. edges[i].length == 2 4. 1 <= ai < bi <= edges.length 5. ai != bi 6. There are no repeated edges. 7. The given graph is connected. */ // array of all n nodes that can be found in graph int[] nodes; //TC/S: O(n) public int[] findRedundantConnection(int[][] edges) { nodes = new int[edges.length + 1]; // n == edges.length /* to use union-find, self root each node, as new connections are found, the root of the connected nodes will be combined under one node, e.g. if [1,2] [2,3], the root of 2 and 3 will be 1 */ for (int i = 0; i <= edges.length; i++) { nodes[i] = i; } /* loop through all the edges in the graph, get the roots of the two nodes connected, if their roots match that means a cycle was found, i.e. the nodes connect through other nodes, so the cyclic edge is returned since there is only one cycle edge, otherwise merge the two nodes under one root, "from" */ for (int[] edge : edges) { int from = edge[0]; int to = edge[1]; if (find(from) == find(to)) { return edge; } else { union(from, to); } } //no cycles detected return new int[]{-1, -1}; } //returns the root of the given node p private int find(int p) { /* p is the node which we want to find the root for, so while the root of p != p, i.e. not self rooted, get the to the root of p by searching through all connected nodes e.g. if [0, 1] [1,2] and [2,3] edges have been seen so far then the array of nodes = [0, 1, 2, 3] and roots = [0, 0, 1, 1] to get the root the root of 3, we check of 3 == 1, since 3 is not self rooted, we move to its root 1, 1 != 0, so we move to its root 0, 0 == 0 so the root has been found */ while (nodes[p] != p) { p = nodes[p]; } return p; } //unites p and q if they don't already belong in the same union set private void union(int p, int q) { //get the roots of both nodes p and q int rootP = find(p); int rootQ = find(q); //if the nodes are not part of the same tree, set the root of the subtree to the root Q if (rootP != rootQ) { nodes[rootP] = rootQ; } } }
3,548
0.549324
0.52593
101
34.128712
35.147121
123
false
false
0
0
0
0
0
0
0.752475
false
false
13
cc4a2fa264897d0f701ad8e0d98053c833db7b58
31,714,038,542,947
2cb29e12c6d714617d76fe541892bd1ccbfb2c33
/CR/src/main/java/net/mysoftworks/crud/JPAMasterDetailEntityEditor.java
7c59ee866525ebbdb0b2b08ef0b6c181758ac741
[]
no_license
viveknerle/vaadin-crud
https://github.com/viveknerle/vaadin-crud
00449230d8bdb152ef9d4d26c71767ad488607d1
fb002290a008bc6e9e3b63eff331bef31582acbb
refs/heads/master
2021-01-22T11:42:31.545000
2012-06-21T15:29:31
2012-06-21T15:29:31
41,761,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.mysoftworks.crud; import java.util.Collection; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanContainer; import com.vaadin.data.util.BeanItem; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.ui.AbstractField; import com.vaadin.ui.Component; import com.vaadin.ui.Select; import com.vaadin.ui.Table; public class JPAMasterDetailEntityEditor<ET> extends JPAEntityEditor<ET> { /** * */ private static final long serialVersionUID = 1L; public enum MASTER_SELECT_TYPE {SELECT,TABLE,TEXT_SEARCH} private AbstractField masterElement; private MASTER_SELECT_TYPE masterType; private AbstractField createSelect() { Container cont = getContainerProvider().loadAll(cl, null); System.out.println("\n\nContainer:" + cont.getClass() ); if (cont instanceof BeanItemContainer) { BeanItemContainer bic = (BeanItemContainer) cont; Collection ids = bic.getItemIds(); for (Object id: ids) { System.out.println("\n\nitem:" + ((BeanItem)bic.getItem(id)).getBean()); } } Select itemSelector = new Select("Select a " + cl.getSimpleName(),cont); itemSelector.setItemCaptionMode(Select.ITEM_CAPTION_MODE_ITEM); itemSelector.setImmediate(true); itemSelector.setNullSelectionAllowed(false); return itemSelector; } private AbstractField createTable() { Table table = new Table("Select a " + cl.getSimpleName(),getContainerProvider().loadAll(cl, null)); table.setSelectable(true); table.setMultiSelect(false); table.setImmediate(true); table.setNullSelectionAllowed(false); return table; } private AbstractField createTextSearch() { return null; // Table table = new Table("Select a " + cl.getSimpleName(),container); // table.setSelectable(true); // table.setMultiSelect(false); // table.setImmediate(true); // table.setNullSelectionAllowed(false); // return table; } private AbstractField createMaster(MASTER_SELECT_TYPE master) { AbstractField masterElement = null; switch (master) { case SELECT:masterElement = createSelect(); break; case TABLE: masterElement = createTable(); break; case TEXT_SEARCH: masterElement = createTextSearch(); break; default: break; } if (masterElement != null) { addComponent(masterElement); } return masterElement; } private ValueChangeListener getMasterValueChangeListener(Component masterElement) { return new ValueChangeListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void valueChange(ValueChangeEvent event) { System.out.println("event.getProperty():" + event.getProperty()); Item item = getContainerProvider().refresh((ET) event.getProperty().getValue()); renderDetail(item); } }; } private void renderDetail(Item instance) { super.render(instance); } public void render() { this.masterElement = createMaster(masterType); if (masterElement != null) { masterElement.addListener(getMasterValueChangeListener(masterElement)); } } public JPAMasterDetailEntityEditor(Class<ET> cl,MASTER_SELECT_TYPE master) throws Exception { super(cl); this.masterType = master; } }
UTF-8
Java
3,294
java
JPAMasterDetailEntityEditor.java
Java
[]
null
[]
package net.mysoftworks.crud; import java.util.Collection; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanContainer; import com.vaadin.data.util.BeanItem; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.ui.AbstractField; import com.vaadin.ui.Component; import com.vaadin.ui.Select; import com.vaadin.ui.Table; public class JPAMasterDetailEntityEditor<ET> extends JPAEntityEditor<ET> { /** * */ private static final long serialVersionUID = 1L; public enum MASTER_SELECT_TYPE {SELECT,TABLE,TEXT_SEARCH} private AbstractField masterElement; private MASTER_SELECT_TYPE masterType; private AbstractField createSelect() { Container cont = getContainerProvider().loadAll(cl, null); System.out.println("\n\nContainer:" + cont.getClass() ); if (cont instanceof BeanItemContainer) { BeanItemContainer bic = (BeanItemContainer) cont; Collection ids = bic.getItemIds(); for (Object id: ids) { System.out.println("\n\nitem:" + ((BeanItem)bic.getItem(id)).getBean()); } } Select itemSelector = new Select("Select a " + cl.getSimpleName(),cont); itemSelector.setItemCaptionMode(Select.ITEM_CAPTION_MODE_ITEM); itemSelector.setImmediate(true); itemSelector.setNullSelectionAllowed(false); return itemSelector; } private AbstractField createTable() { Table table = new Table("Select a " + cl.getSimpleName(),getContainerProvider().loadAll(cl, null)); table.setSelectable(true); table.setMultiSelect(false); table.setImmediate(true); table.setNullSelectionAllowed(false); return table; } private AbstractField createTextSearch() { return null; // Table table = new Table("Select a " + cl.getSimpleName(),container); // table.setSelectable(true); // table.setMultiSelect(false); // table.setImmediate(true); // table.setNullSelectionAllowed(false); // return table; } private AbstractField createMaster(MASTER_SELECT_TYPE master) { AbstractField masterElement = null; switch (master) { case SELECT:masterElement = createSelect(); break; case TABLE: masterElement = createTable(); break; case TEXT_SEARCH: masterElement = createTextSearch(); break; default: break; } if (masterElement != null) { addComponent(masterElement); } return masterElement; } private ValueChangeListener getMasterValueChangeListener(Component masterElement) { return new ValueChangeListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void valueChange(ValueChangeEvent event) { System.out.println("event.getProperty():" + event.getProperty()); Item item = getContainerProvider().refresh((ET) event.getProperty().getValue()); renderDetail(item); } }; } private void renderDetail(Item instance) { super.render(instance); } public void render() { this.masterElement = createMaster(masterType); if (masterElement != null) { masterElement.addListener(getMasterValueChangeListener(masterElement)); } } public JPAMasterDetailEntityEditor(Class<ET> cl,MASTER_SELECT_TYPE master) throws Exception { super(cl); this.masterType = master; } }
3,294
0.735883
0.735276
116
27.396551
25.021328
101
false
false
0
0
0
0
0
0
2.181035
false
false
13
cae5d2a5381ef7a32c061996c1e78f9127511ab5
28,896,540,019,185
3e1a882e2b13fd583375277061fdeb28baa41556
/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageProcessor.java
14b839e3af2f81a260b17b21d6202d539ae26051
[ "Apache-2.0" ]
permissive
devfest-bugbust/onap-sdc
https://github.com/devfest-bugbust/onap-sdc
2b4bb35beaaef16d352ae84c8289e7802df6471a
150c13a2641c87ddffbed7aaad294bd6dacde2fc
refs/heads/master
2023-08-17T02:06:53.821000
2021-09-23T19:19:34
2021-09-23T21:10:09
407,484,169
0
5
NOASSERTION
true
2021-09-23T21:39:36
2021-09-17T09:34:36
2021-09-23T21:10:14
2021-09-23T21:10:10
215,470
0
5
6
Java
false
false
/* * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation * Copyright (C) 2021 Nokia * ================================================================================ * 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. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding; import static org.openecomp.sdc.common.errors.Messages.COULD_NOT_READ_MANIFEST_FILE; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_EMPTY_ERROR; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_INVALID_ERROR; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_INVALID_EXTENSION; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_MISSING_INTERNAL_PACKAGE; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_PROCESS_ERROR; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_PROCESS_INTERNAL_PACKAGE_ERROR; import static org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager.ALLOWED_CERTIFICATE_EXTENSIONS; import static org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager.ALLOWED_SIGNATURE_EXTENSIONS; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.io.FilenameUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.be.csar.storage.ArtifactInfo; import org.openecomp.sdc.common.CommonConfigurationManager; import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.common.zip.exception.ZipException; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.validation.CnfPackageValidator; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackage; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardSignedPackage; public class OnboardingPackageProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(OnboardingPackageProcessor.class); private static final String CSAR_EXTENSION = "csar"; private static final String ZIP_EXTENSION = "zip"; private final String packageFileName; private final byte[] packageFileContent; private final Set<ErrorMessage> errorMessages = new HashSet<>(); private final OnboardPackageInfo onboardPackageInfo; private final CnfPackageValidator cnfPackageValidator; private FileContentHandler packageContent; public OnboardingPackageProcessor(final String packageFileName, final byte[] packageFileContent, final CnfPackageValidator cnfPackageValidator, final ArtifactInfo artifactInfo) { this.packageFileName = packageFileName; this.packageFileContent = packageFileContent; this.cnfPackageValidator = cnfPackageValidator; onboardPackageInfo = processPackage(); if (onboardPackageInfo != null) { onboardPackageInfo.setArtifactInfo(artifactInfo); } } public Optional<OnboardPackageInfo> getOnboardPackageInfo() { return Optional.ofNullable(onboardPackageInfo); } public boolean hasErrors() { return errorMessages.stream() .anyMatch(error -> error.getLevel() == ErrorLevel.ERROR); } public boolean hasNoErrors() { return errorMessages.stream() .noneMatch(error -> error.getLevel() == ErrorLevel.ERROR); } public Set<ErrorMessage> getErrorMessages() { return errorMessages; } private OnboardPackageInfo processPackage() { OnboardPackageInfo packageInfo = null; validateFile(); if (hasNoErrors()) { final String packageName = FilenameUtils.getBaseName(packageFileName); final String packageExtension = FilenameUtils.getExtension(packageFileName); if (hasSignedPackageStructure()) { packageInfo = processSignedPackage(packageName, packageExtension); } else { if (packageExtension.equalsIgnoreCase(CSAR_EXTENSION)) { packageInfo = processCsarPackage(packageName, packageExtension); } else if (packageExtension.equalsIgnoreCase(ZIP_EXTENSION)) { packageInfo = processOnapNativeZipPackage(packageName, packageExtension); } } } return packageInfo; } private void validateFile() { if (!hasValidExtension()) { String message = PACKAGE_INVALID_EXTENSION.formatMessage(packageFileName, String.join(", ", CSAR_EXTENSION, ZIP_EXTENSION)); reportError(ErrorLevel.ERROR, message); } else { try { packageContent = CommonUtil.getZipContent(packageFileContent); if (isPackageEmpty()) { String message = PACKAGE_EMPTY_ERROR.formatMessage(packageFileName); reportError(ErrorLevel.ERROR, message); } } catch (final ZipException e) { String message = PACKAGE_PROCESS_ERROR.formatMessage(packageFileName); reportError(ErrorLevel.ERROR, message); LOGGER.error(message, e); } } } private OnboardPackageInfo processCsarPackage(String packageName, String packageExtension) { OnboardPackage onboardPackage = new OnboardPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), new OnboardingPackageContentHandler(packageContent)); return new OnboardPackageInfo(onboardPackage, OnboardingTypesEnum.CSAR); } private OnboardPackageInfo createOnboardPackageInfoForZip(String packageName, String packageExtension) { return new OnboardPackageInfo( new OnboardPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), packageContent), OnboardingTypesEnum.ZIP); } private OnboardPackageInfo processOnapNativeZipPackage(String packageName, String packageExtension) { if (CommonConfigurationManager.getInstance().getConfigValue("zipValidation", "ignoreManifest", false)) { return createOnboardPackageInfoForZip(packageName, packageExtension); } ManifestContent manifest = getManifest(); if (manifest != null) { List<String> errors = validateZipPackage(manifest); if (errors.isEmpty()) { return createOnboardPackageInfoForZip(packageName, packageExtension); } else { errors.forEach(message -> reportError(ErrorLevel.ERROR, message)); } } else { reportError(ErrorLevel.ERROR, COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName)); } return null; } List<String> validateZipPackage(ManifestContent manifest) { ManifestAnalyzer analyzer = new ManifestAnalyzer(manifest); List<String> errors = Collections.emptyList(); if (analyzer.hasHelmEntries()) { if (shouldValidateHelmPackage(analyzer)) { errors = cnfPackageValidator.validateHelmPackage(analyzer.getHelmEntries()); } } addDummyHeat(manifest); return errors; } boolean shouldValidateHelmPackage(ManifestAnalyzer analyzer) { return analyzer.hasHelmEntries() && !analyzer.hasHeatEntries(); } private ManifestContent getManifest() { ManifestContent manifest = null; try (InputStream zipFileManifest = packageContent.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { manifest = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); } catch (Exception e) { final String message = COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName); LOGGER.error(message, e); } return manifest; } private void addDummyHeat(ManifestContent manifestContent) { // temporary fix for adding dummy base List<FileData> newfiledata = new ArrayList<>(); try { boolean heatBase = false; for (FileData fileData : manifestContent.getData()) { if (Objects.nonNull(fileData.getType()) && fileData.getType().equals(FileData.Type.HELM) && fileData.getBase()) { heatBase = true; fileData.setBase(false); FileData dummyHeat = new FileData(); dummyHeat.setBase(true); dummyHeat.setFile("base_template_dummy_ignore.yaml"); dummyHeat.setType(FileData.Type.HEAT); FileData dummyEnv = new FileData(); dummyEnv.setBase(false); dummyEnv.setFile("base_template_dummy_ignore.env"); dummyEnv.setType(FileData.Type.HEAT_ENV); List<FileData> dataEnvList = new ArrayList<>(); dataEnvList.add(dummyEnv); dummyHeat.setData(dataEnvList); newfiledata.add(dummyHeat); String filePath = new File("").getAbsolutePath() + "/resources"; File envFilePath = new File(filePath + "/base_template.env"); File baseFilePath = new File(filePath + "/base_template.yaml"); try (InputStream envStream = new FileInputStream(envFilePath); InputStream baseStream = new FileInputStream(baseFilePath)) { packageContent.addFile("base_template_dummy_ignore.env", envStream); packageContent.addFile("base_template_dummy_ignore.yaml", baseStream); } catch (Exception e) { LOGGER.error("Failed creating input stream {}", e); } } } if (heatBase) { manifestContent.getData().addAll(newfiledata); InputStream manifestContentStream = new ByteArrayInputStream( (JsonUtil.object2Json(manifestContent)).getBytes(StandardCharsets.UTF_8)); packageContent.remove(SdcCommon.MANIFEST_NAME); packageContent.addFile(SdcCommon.MANIFEST_NAME, manifestContentStream); } } catch (Exception e) { final String message = PACKAGE_INVALID_ERROR.formatMessage(packageFileName); LOGGER.error(message, e); } } private boolean hasValidExtension() { final String packageExtension = FilenameUtils.getExtension(packageFileName); return packageExtension.equalsIgnoreCase(CSAR_EXTENSION) || packageExtension.equalsIgnoreCase(ZIP_EXTENSION); } private OnboardPackageInfo processSignedPackage(final String packageName, final String packageExtension) { final String internalPackagePath = findInternalPackagePath().orElse(null); if (internalPackagePath == null) { reportError(ErrorLevel.ERROR, PACKAGE_MISSING_INTERNAL_PACKAGE.getErrorMessage()); return null; } final String signatureFilePath = findSignatureFilePath().orElse(null); final String certificateFilePath = findCertificateFilePath().orElse(null); final OnboardSignedPackage onboardSignedPackage = new OnboardSignedPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), packageContent, signatureFilePath, internalPackagePath, certificateFilePath); final String internalPackageName = FilenameUtils.getName(internalPackagePath); final String internalPackageBaseName = FilenameUtils.getBaseName(internalPackagePath); final String internalPackageExtension = FilenameUtils.getExtension(internalPackagePath); final byte[] internalPackageContent = packageContent.getFileContent(internalPackagePath); final OnboardPackage onboardPackage; try { final OnboardingPackageContentHandler fileContentHandler = new OnboardingPackageContentHandler( CommonUtil.getZipContent(internalPackageContent)); onboardPackage = new OnboardPackage(internalPackageBaseName, internalPackageExtension, internalPackageContent, fileContentHandler); } catch (final ZipException e) { final String message = PACKAGE_PROCESS_INTERNAL_PACKAGE_ERROR.formatMessage(internalPackageName); LOGGER.error(message, e); reportError(ErrorLevel.ERROR, message); return null; } return new OnboardPackageInfo(onboardSignedPackage, onboardPackage, OnboardingTypesEnum.SIGNED_CSAR); } private void reportError(final ErrorLevel errorLevel, final String message) { errorMessages.add(new ErrorMessage(errorLevel, message)); } private Optional<String> findInternalPackagePath() { return packageContent.getFileList().stream().filter(filePath -> { final String extension = FilenameUtils.getExtension(filePath); return CSAR_EXTENSION.equalsIgnoreCase(extension) || ZIP_EXTENSION.equalsIgnoreCase(extension); }).findFirst(); } private boolean isPackageEmpty() { return MapUtils.isEmpty(packageContent.getFiles()); } private boolean hasSignedPackageStructure() { if (MapUtils.isEmpty(packageContent.getFiles()) || !CollectionUtils.isEmpty(packageContent.getFolderList())) { return false; } final int numberOfFiles = packageContent.getFileList().size(); if (numberOfFiles == 2) { return hasOneInternalPackageFile(packageContent) && hasOneSignatureFile(packageContent); } if (numberOfFiles == 3) { return hasOneInternalPackageFile(packageContent) && hasOneSignatureFile(packageContent) && hasOneCertificateFile(packageContent); } return false; } private boolean hasOneInternalPackageFile(final FileContentHandler fileContentHandler) { return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(file -> file.endsWith(CSAR_EXTENSION)).count() == 1; } private boolean hasOneSignatureFile(final FileContentHandler fileContentHandler) { return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(ALLOWED_SIGNATURE_EXTENSIONS::contains).count() == 1; } private boolean hasOneCertificateFile(final FileContentHandler fileContentHandler) { return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(ALLOWED_CERTIFICATE_EXTENSIONS::contains).count() == 1; } private Optional<String> findSignatureFilePath() { final Map<String, byte[]> files = packageContent.getFiles(); return files.keySet().stream().filter(fileName -> ALLOWED_SIGNATURE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) .findFirst(); } private Optional<String> findCertificateFilePath() { final Map<String, byte[]> files = packageContent.getFiles(); return files.keySet().stream().filter(fileName -> ALLOWED_CERTIFICATE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) .findFirst(); } }
UTF-8
Java
16,989
java
OnboardingPackageProcessor.java
Java
[]
null
[]
/* * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation * Copyright (C) 2021 Nokia * ================================================================================ * 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. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding; import static org.openecomp.sdc.common.errors.Messages.COULD_NOT_READ_MANIFEST_FILE; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_EMPTY_ERROR; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_INVALID_ERROR; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_INVALID_EXTENSION; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_MISSING_INTERNAL_PACKAGE; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_PROCESS_ERROR; import static org.openecomp.sdc.common.errors.Messages.PACKAGE_PROCESS_INTERNAL_PACKAGE_ERROR; import static org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager.ALLOWED_CERTIFICATE_EXTENSIONS; import static org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager.ALLOWED_SIGNATURE_EXTENSIONS; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.io.FilenameUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.be.csar.storage.ArtifactInfo; import org.openecomp.sdc.common.CommonConfigurationManager; import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.common.zip.exception.ZipException; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.validation.CnfPackageValidator; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackage; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardSignedPackage; public class OnboardingPackageProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(OnboardingPackageProcessor.class); private static final String CSAR_EXTENSION = "csar"; private static final String ZIP_EXTENSION = "zip"; private final String packageFileName; private final byte[] packageFileContent; private final Set<ErrorMessage> errorMessages = new HashSet<>(); private final OnboardPackageInfo onboardPackageInfo; private final CnfPackageValidator cnfPackageValidator; private FileContentHandler packageContent; public OnboardingPackageProcessor(final String packageFileName, final byte[] packageFileContent, final CnfPackageValidator cnfPackageValidator, final ArtifactInfo artifactInfo) { this.packageFileName = packageFileName; this.packageFileContent = packageFileContent; this.cnfPackageValidator = cnfPackageValidator; onboardPackageInfo = processPackage(); if (onboardPackageInfo != null) { onboardPackageInfo.setArtifactInfo(artifactInfo); } } public Optional<OnboardPackageInfo> getOnboardPackageInfo() { return Optional.ofNullable(onboardPackageInfo); } public boolean hasErrors() { return errorMessages.stream() .anyMatch(error -> error.getLevel() == ErrorLevel.ERROR); } public boolean hasNoErrors() { return errorMessages.stream() .noneMatch(error -> error.getLevel() == ErrorLevel.ERROR); } public Set<ErrorMessage> getErrorMessages() { return errorMessages; } private OnboardPackageInfo processPackage() { OnboardPackageInfo packageInfo = null; validateFile(); if (hasNoErrors()) { final String packageName = FilenameUtils.getBaseName(packageFileName); final String packageExtension = FilenameUtils.getExtension(packageFileName); if (hasSignedPackageStructure()) { packageInfo = processSignedPackage(packageName, packageExtension); } else { if (packageExtension.equalsIgnoreCase(CSAR_EXTENSION)) { packageInfo = processCsarPackage(packageName, packageExtension); } else if (packageExtension.equalsIgnoreCase(ZIP_EXTENSION)) { packageInfo = processOnapNativeZipPackage(packageName, packageExtension); } } } return packageInfo; } private void validateFile() { if (!hasValidExtension()) { String message = PACKAGE_INVALID_EXTENSION.formatMessage(packageFileName, String.join(", ", CSAR_EXTENSION, ZIP_EXTENSION)); reportError(ErrorLevel.ERROR, message); } else { try { packageContent = CommonUtil.getZipContent(packageFileContent); if (isPackageEmpty()) { String message = PACKAGE_EMPTY_ERROR.formatMessage(packageFileName); reportError(ErrorLevel.ERROR, message); } } catch (final ZipException e) { String message = PACKAGE_PROCESS_ERROR.formatMessage(packageFileName); reportError(ErrorLevel.ERROR, message); LOGGER.error(message, e); } } } private OnboardPackageInfo processCsarPackage(String packageName, String packageExtension) { OnboardPackage onboardPackage = new OnboardPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), new OnboardingPackageContentHandler(packageContent)); return new OnboardPackageInfo(onboardPackage, OnboardingTypesEnum.CSAR); } private OnboardPackageInfo createOnboardPackageInfoForZip(String packageName, String packageExtension) { return new OnboardPackageInfo( new OnboardPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), packageContent), OnboardingTypesEnum.ZIP); } private OnboardPackageInfo processOnapNativeZipPackage(String packageName, String packageExtension) { if (CommonConfigurationManager.getInstance().getConfigValue("zipValidation", "ignoreManifest", false)) { return createOnboardPackageInfoForZip(packageName, packageExtension); } ManifestContent manifest = getManifest(); if (manifest != null) { List<String> errors = validateZipPackage(manifest); if (errors.isEmpty()) { return createOnboardPackageInfoForZip(packageName, packageExtension); } else { errors.forEach(message -> reportError(ErrorLevel.ERROR, message)); } } else { reportError(ErrorLevel.ERROR, COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName)); } return null; } List<String> validateZipPackage(ManifestContent manifest) { ManifestAnalyzer analyzer = new ManifestAnalyzer(manifest); List<String> errors = Collections.emptyList(); if (analyzer.hasHelmEntries()) { if (shouldValidateHelmPackage(analyzer)) { errors = cnfPackageValidator.validateHelmPackage(analyzer.getHelmEntries()); } } addDummyHeat(manifest); return errors; } boolean shouldValidateHelmPackage(ManifestAnalyzer analyzer) { return analyzer.hasHelmEntries() && !analyzer.hasHeatEntries(); } private ManifestContent getManifest() { ManifestContent manifest = null; try (InputStream zipFileManifest = packageContent.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { manifest = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); } catch (Exception e) { final String message = COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName); LOGGER.error(message, e); } return manifest; } private void addDummyHeat(ManifestContent manifestContent) { // temporary fix for adding dummy base List<FileData> newfiledata = new ArrayList<>(); try { boolean heatBase = false; for (FileData fileData : manifestContent.getData()) { if (Objects.nonNull(fileData.getType()) && fileData.getType().equals(FileData.Type.HELM) && fileData.getBase()) { heatBase = true; fileData.setBase(false); FileData dummyHeat = new FileData(); dummyHeat.setBase(true); dummyHeat.setFile("base_template_dummy_ignore.yaml"); dummyHeat.setType(FileData.Type.HEAT); FileData dummyEnv = new FileData(); dummyEnv.setBase(false); dummyEnv.setFile("base_template_dummy_ignore.env"); dummyEnv.setType(FileData.Type.HEAT_ENV); List<FileData> dataEnvList = new ArrayList<>(); dataEnvList.add(dummyEnv); dummyHeat.setData(dataEnvList); newfiledata.add(dummyHeat); String filePath = new File("").getAbsolutePath() + "/resources"; File envFilePath = new File(filePath + "/base_template.env"); File baseFilePath = new File(filePath + "/base_template.yaml"); try (InputStream envStream = new FileInputStream(envFilePath); InputStream baseStream = new FileInputStream(baseFilePath)) { packageContent.addFile("base_template_dummy_ignore.env", envStream); packageContent.addFile("base_template_dummy_ignore.yaml", baseStream); } catch (Exception e) { LOGGER.error("Failed creating input stream {}", e); } } } if (heatBase) { manifestContent.getData().addAll(newfiledata); InputStream manifestContentStream = new ByteArrayInputStream( (JsonUtil.object2Json(manifestContent)).getBytes(StandardCharsets.UTF_8)); packageContent.remove(SdcCommon.MANIFEST_NAME); packageContent.addFile(SdcCommon.MANIFEST_NAME, manifestContentStream); } } catch (Exception e) { final String message = PACKAGE_INVALID_ERROR.formatMessage(packageFileName); LOGGER.error(message, e); } } private boolean hasValidExtension() { final String packageExtension = FilenameUtils.getExtension(packageFileName); return packageExtension.equalsIgnoreCase(CSAR_EXTENSION) || packageExtension.equalsIgnoreCase(ZIP_EXTENSION); } private OnboardPackageInfo processSignedPackage(final String packageName, final String packageExtension) { final String internalPackagePath = findInternalPackagePath().orElse(null); if (internalPackagePath == null) { reportError(ErrorLevel.ERROR, PACKAGE_MISSING_INTERNAL_PACKAGE.getErrorMessage()); return null; } final String signatureFilePath = findSignatureFilePath().orElse(null); final String certificateFilePath = findCertificateFilePath().orElse(null); final OnboardSignedPackage onboardSignedPackage = new OnboardSignedPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), packageContent, signatureFilePath, internalPackagePath, certificateFilePath); final String internalPackageName = FilenameUtils.getName(internalPackagePath); final String internalPackageBaseName = FilenameUtils.getBaseName(internalPackagePath); final String internalPackageExtension = FilenameUtils.getExtension(internalPackagePath); final byte[] internalPackageContent = packageContent.getFileContent(internalPackagePath); final OnboardPackage onboardPackage; try { final OnboardingPackageContentHandler fileContentHandler = new OnboardingPackageContentHandler( CommonUtil.getZipContent(internalPackageContent)); onboardPackage = new OnboardPackage(internalPackageBaseName, internalPackageExtension, internalPackageContent, fileContentHandler); } catch (final ZipException e) { final String message = PACKAGE_PROCESS_INTERNAL_PACKAGE_ERROR.formatMessage(internalPackageName); LOGGER.error(message, e); reportError(ErrorLevel.ERROR, message); return null; } return new OnboardPackageInfo(onboardSignedPackage, onboardPackage, OnboardingTypesEnum.SIGNED_CSAR); } private void reportError(final ErrorLevel errorLevel, final String message) { errorMessages.add(new ErrorMessage(errorLevel, message)); } private Optional<String> findInternalPackagePath() { return packageContent.getFileList().stream().filter(filePath -> { final String extension = FilenameUtils.getExtension(filePath); return CSAR_EXTENSION.equalsIgnoreCase(extension) || ZIP_EXTENSION.equalsIgnoreCase(extension); }).findFirst(); } private boolean isPackageEmpty() { return MapUtils.isEmpty(packageContent.getFiles()); } private boolean hasSignedPackageStructure() { if (MapUtils.isEmpty(packageContent.getFiles()) || !CollectionUtils.isEmpty(packageContent.getFolderList())) { return false; } final int numberOfFiles = packageContent.getFileList().size(); if (numberOfFiles == 2) { return hasOneInternalPackageFile(packageContent) && hasOneSignatureFile(packageContent); } if (numberOfFiles == 3) { return hasOneInternalPackageFile(packageContent) && hasOneSignatureFile(packageContent) && hasOneCertificateFile(packageContent); } return false; } private boolean hasOneInternalPackageFile(final FileContentHandler fileContentHandler) { return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(file -> file.endsWith(CSAR_EXTENSION)).count() == 1; } private boolean hasOneSignatureFile(final FileContentHandler fileContentHandler) { return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(ALLOWED_SIGNATURE_EXTENSIONS::contains).count() == 1; } private boolean hasOneCertificateFile(final FileContentHandler fileContentHandler) { return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(ALLOWED_CERTIFICATE_EXTENSIONS::contains).count() == 1; } private Optional<String> findSignatureFilePath() { final Map<String, byte[]> files = packageContent.getFiles(); return files.keySet().stream().filter(fileName -> ALLOWED_SIGNATURE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) .findFirst(); } private Optional<String> findCertificateFilePath() { final Map<String, byte[]> files = packageContent.getFiles(); return files.keySet().stream().filter(fileName -> ALLOWED_CERTIFICATE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) .findFirst(); } }
16,989
0.687209
0.685797
338
49.263313
36.345791
150
false
false
0
0
0
0
81
0.004768
0.698225
false
false
13
6980f30efb8770d68d88e7093f8be3e85c65c3f7
32,830,730,039,347
60d2689d8c243f2d8e258a4faa40e55535ea8859
/src/com/cqnu/sort/QuickSortB.java
212e78593a04917babbccf77c6483cc60a0741a0
[]
no_license
coolZhangSir/DataStructure
https://github.com/coolZhangSir/DataStructure
cd2b0efb06d8d3bd74f17db30f6fd32f1d2e640c
e5eee2adc85e6d6503fc285df2268eeab396c0b0
refs/heads/master
2018-12-21T14:49:02.839000
2018-10-10T11:29:32
2018-10-10T11:29:32
149,729,878
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cqnu.sort; /** * 快速排序(三数取中法) * @author ZhangHao * */ public class QuickSortB { /** * 重载快速排序,只需要传入一个待排序数组即可. * @param source */ public static void quickSort(int[] source){ quickSort(source, 0, source.length - 1); } /** * @param source */ public static void quickSort(int[] source, int low, int high){ if(low >= high){ return; } getPivot(source, low, high); int middle = partition(source, low, high); quickSort(source, low, middle - 1); quickSort(source, middle + 1, high); } /** * 进行划分,轴点已经被放置在a.length - 2的位置上,但是不要想着high - 2,low + 1,如果数组长度只有2就蒙了. * 整体算法容易错的就是下面的--j. * 由于最左和最右都已放置了合适的元素,所以用--j直接跳过这两个元素的操作, * 即在范围low -> high - 1不变的情况下,我们要跳过j从轴点开始比较的话只能选择--j或者修改条件为>= * @return 返回轴点位置,当前被数组被轴点一分为二,以便下一次递归操作 */ private static int partition(int[] source, int low, int high) { int i = low, j = high - 1; int pivot = high - 1; while (i < j){ while (source[++i] < source[pivot]){ } while (i < j && source[--j] > source[pivot]){ } //可以选择修改条件为>=跳过轴点 // while (i < j && source[j] >= source[pivot]){ // j--; // } if(i < j){ swap(source, i, j); } } swap(source, i, pivot); return i; } /** * 使用三方取中法获取轴点 * 1.取出三个数之间的中值 * 2.将最小值交换到最左,将最大值交换到最右,将中间值交换到right - 1的位置 * 以上分割的好处在于:此时已经将这三个数就位,且中间到right - 1的位置可以少比较一次,j初始化就可以设置为right - 1 * * 这一步的思路不用那么复杂,直接边比较边交换,完事之后最小的肯定已经被放在最左边 */ private static void getPivot(int[] source, int low, int high){ int middle = (high + low) / 2; if(source[middle] > source[high]){ swap(source, middle, high); } if(source[low] > source[high]){ swap(source, low, high); } if(source[low] > source[middle]){ swap(source, low, middle); } //交换轴点至high - 1的位置 swap(source, high - 1, middle); } /** * 交换 */ private static void swap(int[] source, int i, int j){ int temp = source[i]; source[i] = source[j]; source[j] = temp; } }
UTF-8
Java
2,573
java
QuickSortB.java
Java
[ { "context": "kage com.cqnu.sort;\n\n/**\n * 快速排序(三数取中法)\n * @author ZhangHao\n *\n */\npublic class QuickSortB {\n\n\t/**\n\t * 重载快速排序", "end": 62, "score": 0.9997249841690063, "start": 54, "tag": "NAME", "value": "ZhangHao" } ]
null
[]
package com.cqnu.sort; /** * 快速排序(三数取中法) * @author ZhangHao * */ public class QuickSortB { /** * 重载快速排序,只需要传入一个待排序数组即可. * @param source */ public static void quickSort(int[] source){ quickSort(source, 0, source.length - 1); } /** * @param source */ public static void quickSort(int[] source, int low, int high){ if(low >= high){ return; } getPivot(source, low, high); int middle = partition(source, low, high); quickSort(source, low, middle - 1); quickSort(source, middle + 1, high); } /** * 进行划分,轴点已经被放置在a.length - 2的位置上,但是不要想着high - 2,low + 1,如果数组长度只有2就蒙了. * 整体算法容易错的就是下面的--j. * 由于最左和最右都已放置了合适的元素,所以用--j直接跳过这两个元素的操作, * 即在范围low -> high - 1不变的情况下,我们要跳过j从轴点开始比较的话只能选择--j或者修改条件为>= * @return 返回轴点位置,当前被数组被轴点一分为二,以便下一次递归操作 */ private static int partition(int[] source, int low, int high) { int i = low, j = high - 1; int pivot = high - 1; while (i < j){ while (source[++i] < source[pivot]){ } while (i < j && source[--j] > source[pivot]){ } //可以选择修改条件为>=跳过轴点 // while (i < j && source[j] >= source[pivot]){ // j--; // } if(i < j){ swap(source, i, j); } } swap(source, i, pivot); return i; } /** * 使用三方取中法获取轴点 * 1.取出三个数之间的中值 * 2.将最小值交换到最左,将最大值交换到最右,将中间值交换到right - 1的位置 * 以上分割的好处在于:此时已经将这三个数就位,且中间到right - 1的位置可以少比较一次,j初始化就可以设置为right - 1 * * 这一步的思路不用那么复杂,直接边比较边交换,完事之后最小的肯定已经被放在最左边 */ private static void getPivot(int[] source, int low, int high){ int middle = (high + low) / 2; if(source[middle] > source[high]){ swap(source, middle, high); } if(source[low] > source[high]){ swap(source, low, high); } if(source[low] > source[middle]){ swap(source, low, middle); } //交换轴点至high - 1的位置 swap(source, high - 1, middle); } /** * 交换 */ private static void swap(int[] source, int i, int j){ int temp = source[i]; source[i] = source[j]; source[j] = temp; } }
2,573
0.603314
0.593475
95
19.326315
18.930033
70
false
false
0
0
0
0
0
0
2.305263
false
false
13
5c4e8cc85d8e77cc0b809f48c5a38121f9ebd056
16,569,983,849,571
6741979b496514c48ceb67b031d2ba3ebcd081ea
/svc-model/src/main/java/com.ebuytech.svc.easybuy/dto/BaseC/BaseSaleTh.java
eaa94e9d51854273db9b19aa6f9179f7d847b9c9
[]
no_license
MiniMacx/3ade48AZ2k
https://github.com/MiniMacx/3ade48AZ2k
aa25627eece7ef0c4968ab7765591a589846a28e
7e116e553af9a2ab2a670707d72fa9c194d268a8
refs/heads/master
2018-12-16T09:44:32.025000
2018-12-10T07:36:54
2018-12-10T07:36:54
148,734,691
2
1
null
false
2018-10-09T01:01:46
2018-09-14T04:12:36
2018-09-23T11:04:46
2018-10-09T01:01:45
1,485
1
2
0
null
false
null
package com.ebuytech.svc.easybuy.dto.BaseC; import lombok.Data; @Data public class BaseSaleTh { protected String group; protected String StoreId; protected String StoreName; protected String StoreProvince; protected String StoreCity; protected String StoreDistrict; protected String StoreAdress; protected Integer SaleTotalNum; protected Double SaleTotalMoney; protected Integer RefundTotaNum; protected Double RefundTotalMoney; public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getStoreId() { return StoreId; } public void setStoreId(String storeId) { StoreId = storeId; } public String getStoreName() { return StoreName; } public void setStoreName(String storeName) { StoreName = storeName; } public String getStoreProvince() { return StoreProvince; } public void setStoreProvince(String storeProvince) { StoreProvince = storeProvince; } public String getStoreCity() { return StoreCity; } public void setStoreCity(String storeCity) { StoreCity = storeCity; } public String getStoreDistrict() { return StoreDistrict; } public void setStoreDistrict(String storeDistrict) { StoreDistrict = storeDistrict; } public String getStoreAdress() { return StoreAdress; } public void setStoreAdress(String storeAdress) { StoreAdress = storeAdress; } public Integer getSaleTotalNum() { return SaleTotalNum; } public void setSaleTotalNum(Integer saleTotalNum) { SaleTotalNum = saleTotalNum; } public Double getSaleTotalMoney() { return SaleTotalMoney; } public void setSaleTotalMoney(Double saleTotalMoney) { SaleTotalMoney = saleTotalMoney; } public Integer getRefundTotaNum() { return RefundTotaNum; } public void setRefundTotaNum(Integer refundTotaNum) { RefundTotaNum = refundTotaNum; } public Double getRefundTotalMoney() { return RefundTotalMoney; } public void setRefundTotalMoney(Double refundTotalMoney) { RefundTotalMoney = refundTotalMoney; } }
UTF-8
Java
2,338
java
BaseSaleTh.java
Java
[]
null
[]
package com.ebuytech.svc.easybuy.dto.BaseC; import lombok.Data; @Data public class BaseSaleTh { protected String group; protected String StoreId; protected String StoreName; protected String StoreProvince; protected String StoreCity; protected String StoreDistrict; protected String StoreAdress; protected Integer SaleTotalNum; protected Double SaleTotalMoney; protected Integer RefundTotaNum; protected Double RefundTotalMoney; public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getStoreId() { return StoreId; } public void setStoreId(String storeId) { StoreId = storeId; } public String getStoreName() { return StoreName; } public void setStoreName(String storeName) { StoreName = storeName; } public String getStoreProvince() { return StoreProvince; } public void setStoreProvince(String storeProvince) { StoreProvince = storeProvince; } public String getStoreCity() { return StoreCity; } public void setStoreCity(String storeCity) { StoreCity = storeCity; } public String getStoreDistrict() { return StoreDistrict; } public void setStoreDistrict(String storeDistrict) { StoreDistrict = storeDistrict; } public String getStoreAdress() { return StoreAdress; } public void setStoreAdress(String storeAdress) { StoreAdress = storeAdress; } public Integer getSaleTotalNum() { return SaleTotalNum; } public void setSaleTotalNum(Integer saleTotalNum) { SaleTotalNum = saleTotalNum; } public Double getSaleTotalMoney() { return SaleTotalMoney; } public void setSaleTotalMoney(Double saleTotalMoney) { SaleTotalMoney = saleTotalMoney; } public Integer getRefundTotaNum() { return RefundTotaNum; } public void setRefundTotaNum(Integer refundTotaNum) { RefundTotaNum = refundTotaNum; } public Double getRefundTotalMoney() { return RefundTotalMoney; } public void setRefundTotalMoney(Double refundTotalMoney) { RefundTotalMoney = refundTotalMoney; } }
2,338
0.661249
0.661249
106
21.056604
18.479376
62
false
false
0
0
0
0
0
0
0.330189
false
false
13
1ba5cadbd0eb7bbafc0f00be5d8956140999b798
27,805,618,328,728
7664e2080f177133f2df6424322dfa1d1b845cb3
/AndroidFinalApp/app/src/main/java/com/example/doctor_patient_app/Dao/TabletsDAO.java
d195bec06da2d8e1b86c03066deb07dbf55090e0
[]
no_license
TupeaAndrei/AndroidFinalProject
https://github.com/TupeaAndrei/AndroidFinalProject
7f432b933e2e80101899fe084d900179ddd94efa
5ccf01ed722a373c84adc952553d92740177ebb3
refs/heads/main
2023-06-05T01:24:15.170000
2021-06-29T07:26:38
2021-06-29T07:26:38
375,716,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.doctor_patient_app.Dao; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.example.doctor_patient_app.models.dbEntities.Tablets; import java.util.List; @Dao public interface TabletsDAO { @Query("SELECT * FROM tablets") List<Tablets> getAllTablets(); @Query("Select id From tablets where name == :tabletName") Integer getIdOfTabletWithName(String tabletName); @Insert void insertTablet(Tablets tablet); @Update void updateTablet(Tablets tablet); @Delete void deleteTablet(Tablets tablet); }
UTF-8
Java
660
java
TabletsDAO.java
Java
[]
null
[]
package com.example.doctor_patient_app.Dao; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.example.doctor_patient_app.models.dbEntities.Tablets; import java.util.List; @Dao public interface TabletsDAO { @Query("SELECT * FROM tablets") List<Tablets> getAllTablets(); @Query("Select id From tablets where name == :tabletName") Integer getIdOfTabletWithName(String tabletName); @Insert void insertTablet(Tablets tablet); @Update void updateTablet(Tablets tablet); @Delete void deleteTablet(Tablets tablet); }
660
0.743939
0.743939
30
21
19.572088
64
false
false
0
0
0
0
0
0
0.433333
false
false
13
2fac0f92a0d093c461dd516e6d4fe704250a8bed
19,602,230,768,621
77cb4c25fc82c708917aedde4bb2a03ff825ebd4
/robin4002/endore/common/block/BlockEndCoalOre.java
f83d8934fdc0a227afd4001b06adc9ae3fe6d3a1
[]
no_license
robin4002/EnderOre
https://github.com/robin4002/EnderOre
978458f63002a44304f446c43743499bc0fbf76e
742382ce862c326e969614509658fe3b4c1a1d1b
refs/heads/master
2016-03-22T15:25:59.025000
2013-03-01T19:23:58
2013-03-01T19:23:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package robin4002.endore.common.block; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import robin4002.endore.common.EndOre; import robin4002.endore.common.item.EnderItemList; public class BlockEndCoalOre extends Block { public BlockEndCoalOre(int par1, int par2) { super(par1, par2, Material.rock); this.setCreativeTab(EndOre.EndCreativeTab); } public String getTextureFile() { return "/robin4002/endore/client/textures/Blocks.png"; } public int quantityDroppedWithBonus(int par1, Random par2Random) { if (par1 > 0 && this.blockID != this.idDropped(0, par2Random, par1)) { int var3 = par2Random.nextInt(par1 + 2) - 1; if (var3 < 0) { var3 = 0; } return this.quantityDropped(par2Random) * (var3 + 1); } else { return this.quantityDropped(par2Random); } } public int idDropped(int par1, Random par2Random, int par3) { return EnderItemList.EndCoal.itemID; } public void dropBlockAsItemWithChance(World par1, int par2, int par3, int par4, int par5, float par6, int par7) { super.dropBlockAsItemWithChance(par1, par2, par3, par4, par5, par6, par7); int var8 = 0; if (this.blockID == EnderBlockList.BlockEndCoalOre.blockID) { var8 = MathHelper.getRandomIntegerInRange(par1.rand, 4, 8); } this.dropXpOnBlockBreak(par1, par2, par3, par4, var8); } public boolean canDragonDestroy(World world, int x, int y, int z) { return false; } }
UTF-8
Java
1,811
java
BlockEndCoalOre.java
Java
[ { "context": "package robin4002.endore.common.block;\n \nimport java.util.Random;\n\n", "end": 17, "score": 0.7350974678993225, "start": 8, "tag": "USERNAME", "value": "robin4002" }, { "context": "thHelper;\nimport net.minecraft.world.World;\nimport robin4002.endore.common.EndOre;\ni...
null
[]
package robin4002.endore.common.block; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import robin4002.endore.common.EndOre; import robin4002.endore.common.item.EnderItemList; public class BlockEndCoalOre extends Block { public BlockEndCoalOre(int par1, int par2) { super(par1, par2, Material.rock); this.setCreativeTab(EndOre.EndCreativeTab); } public String getTextureFile() { return "/robin4002/endore/client/textures/Blocks.png"; } public int quantityDroppedWithBonus(int par1, Random par2Random) { if (par1 > 0 && this.blockID != this.idDropped(0, par2Random, par1)) { int var3 = par2Random.nextInt(par1 + 2) - 1; if (var3 < 0) { var3 = 0; } return this.quantityDropped(par2Random) * (var3 + 1); } else { return this.quantityDropped(par2Random); } } public int idDropped(int par1, Random par2Random, int par3) { return EnderItemList.EndCoal.itemID; } public void dropBlockAsItemWithChance(World par1, int par2, int par3, int par4, int par5, float par6, int par7) { super.dropBlockAsItemWithChance(par1, par2, par3, par4, par5, par6, par7); int var8 = 0; if (this.blockID == EnderBlockList.BlockEndCoalOre.blockID) { var8 = MathHelper.getRandomIntegerInRange(par1.rand, 4, 8); } this.dropXpOnBlockBreak(par1, par2, par3, par4, var8); } public boolean canDragonDestroy(World world, int x, int y, int z) { return false; } }
1,811
0.618443
0.580895
73
23.821918
25.741253
115
false
false
0
0
0
0
0
0
0.712329
false
false
13
1770656e8425ac5db9fcc5fca2cbb3ad8ebd2cdb
12,300,786,380,217
998720939150e580ee8777631f4fcd83b424d8e8
/moovieToXML/src/movies/Person.java
7e2214af3355f8500c9606e479b4a8600d5c2faa
[]
no_license
ronaimate/learn2java_first_weak
https://github.com/ronaimate/learn2java_first_weak
e82999fa12ee19b9d5240521ef3379a5c4a661d2
48261e877153b7873bee58256b9e2cb7bac48d56
refs/heads/master
2016-08-09T10:13:06.859000
2016-02-08T10:49:04
2016-02-08T10:49:04
50,570,151
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package movies; public class Person { String firstName; String lastName; Gender gender; boolean hasOscar; boolean hasGoldenGlobe; public Person(String firstName, String lastName, Gender gender, boolean hasOscar, boolean hasGoldenGlobe) { this.firstName = firstName; this.lastName = lastName; this.gender = gender; this.hasOscar = hasOscar; this.hasGoldenGlobe = hasGoldenGlobe; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Gender getGender() { return this.gender; } public void setGender(Gender gender) { this.gender = gender; } public boolean isHasOscar() { return this.hasOscar; } public void setHasOscar(boolean hasOscar) { this.hasOscar = hasOscar; } public boolean isHasGoldenGlobe() { return this.hasGoldenGlobe; } public void setHasGoldenGlobe(boolean hasGoldenGlobe) { this.hasGoldenGlobe = hasGoldenGlobe; } public String toXMLString() { String resultfirstname = Tools.toXMLTag("firstname", this.firstName); String resultlastname = Tools.toXMLTag("lastname", this.lastName); String resultgender = Tools.toXMLTag("gender", this.gender.toString()); String resulthasoscar = Tools.toXMLTag("hasoscar", String.valueOf(this.hasOscar)); String resultgoldenglobe = Tools.toXMLTag("hasgoldenglobe", String.valueOf(this.hasGoldenGlobe)); String result = Tools.toXMLTag("person", resultfirstname + resultlastname + resultgender + resulthasoscar + resultgoldenglobe); return result; } }
UTF-8
Java
1,706
java
Person.java
Java
[ { "context": "ar, boolean hasGoldenGlobe)\n\t{\n\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tthis.gender = gend", "end": 277, "score": 0.991265058517456, "start": 268, "tag": "NAME", "value": "firstName" }, { "context": "{\n\n\t\tthis.firstName = firstName;\n...
null
[]
package movies; public class Person { String firstName; String lastName; Gender gender; boolean hasOscar; boolean hasGoldenGlobe; public Person(String firstName, String lastName, Gender gender, boolean hasOscar, boolean hasGoldenGlobe) { this.firstName = firstName; this.lastName = lastName; this.gender = gender; this.hasOscar = hasOscar; this.hasGoldenGlobe = hasGoldenGlobe; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Gender getGender() { return this.gender; } public void setGender(Gender gender) { this.gender = gender; } public boolean isHasOscar() { return this.hasOscar; } public void setHasOscar(boolean hasOscar) { this.hasOscar = hasOscar; } public boolean isHasGoldenGlobe() { return this.hasGoldenGlobe; } public void setHasGoldenGlobe(boolean hasGoldenGlobe) { this.hasGoldenGlobe = hasGoldenGlobe; } public String toXMLString() { String resultfirstname = Tools.toXMLTag("firstname", this.firstName); String resultlastname = Tools.toXMLTag("lastname", this.lastName); String resultgender = Tools.toXMLTag("gender", this.gender.toString()); String resulthasoscar = Tools.toXMLTag("hasoscar", String.valueOf(this.hasOscar)); String resultgoldenglobe = Tools.toXMLTag("hasgoldenglobe", String.valueOf(this.hasGoldenGlobe)); String result = Tools.toXMLTag("person", resultfirstname + resultlastname + resultgender + resulthasoscar + resultgoldenglobe); return result; } }
1,706
0.742673
0.742673
84
19.309525
26.118765
129
false
false
0
0
0
0
0
0
1.464286
false
false
13
274739c9ee9af6531de87b029c6b8fcf993fc83b
13,881,334,334,619
2f420ab9c68eb8be3387986a47714c17db0d886f
/src/com/liuchengjie/monitormachine/MonitorPhoneReceiver.java
694dfe9b355707a91da9b767b2068e3d33ebab14
[ "MIT" ]
permissive
liuchengjie01/MonitorMachine
https://github.com/liuchengjie01/MonitorMachine
177cb515cbc20243ba39c9d4c23569e0937b74cb
a9d494c1b8fafc3447cae2abf52807b5900c880e
refs/heads/master
2022-06-30T19:48:53.793000
2020-05-14T12:24:11
2020-05-14T12:24:11
242,280,525
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liuchengjie.monitormachine; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MonitorPhoneReceiver extends BroadcastReceiver { private static final String TAG = "MonitorPhoneReceiver"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Toast.makeText(context, "Intent SMS Detected.", Toast.LENGTH_LONG).show(); Log.v("Cat", "Have listened Phone Broadcast"); Log.v("Cat", intent.getAction()); // Intent phoneIntent = intent; // phoneIntent.setClass(context, cls) String action = intent.getAction(); String phoneNumber = ""; // String myNumber = "15580087385"; // String startTime; //call out signal Log.v(TAG, "==========> " + action); if(action.equals(Intent.ACTION_NEW_OUTGOING_CALL)){ // call out to others phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); Intent outgoingService = new Intent(context, CallOutService.class); outgoingService.putExtra("outgoingNumber", phoneNumber); context.startService(outgoingService); //sTime = intent.getLongExtra(name, defaultValue) } else { Intent phoneService = new Intent(context, PhoneService.class); context.startService(phoneService); } } }
UTF-8
Java
1,360
java
MonitorPhoneReceiver.java
Java
[ { "context": "package com.liuchengjie.monitormachine;\n\nimport android.content.Broadcast", "end": 23, "score": 0.6033289432525635, "start": 14, "tag": "USERNAME", "value": "uchengjie" } ]
null
[]
package com.liuchengjie.monitormachine; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MonitorPhoneReceiver extends BroadcastReceiver { private static final String TAG = "MonitorPhoneReceiver"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Toast.makeText(context, "Intent SMS Detected.", Toast.LENGTH_LONG).show(); Log.v("Cat", "Have listened Phone Broadcast"); Log.v("Cat", intent.getAction()); // Intent phoneIntent = intent; // phoneIntent.setClass(context, cls) String action = intent.getAction(); String phoneNumber = ""; // String myNumber = "15580087385"; // String startTime; //call out signal Log.v(TAG, "==========> " + action); if(action.equals(Intent.ACTION_NEW_OUTGOING_CALL)){ // call out to others phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); Intent outgoingService = new Intent(context, CallOutService.class); outgoingService.putExtra("outgoingNumber", phoneNumber); context.startService(outgoingService); //sTime = intent.getLongExtra(name, defaultValue) } else { Intent phoneService = new Intent(context, PhoneService.class); context.startService(phoneService); } } }
1,360
0.732353
0.724265
42
31.380953
22.522953
76
false
false
0
0
0
0
0
0
2.5
false
false
13
c17c51e05bdc7ca1a28bb3d7fd1950549d0afc08
21,723,944,610,154
40c6c2c8ffc45fd0f93519bc204cceac1d42ea29
/app/src/main/java/sorry/aldan/ti3a_8_12_tugasbesar/Model/User.java
4df5598fc40381b7ab2208382adcb0ed7aa84522
[]
no_license
aldansorry/TI3A_8_12_TugasBesar
https://github.com/aldansorry/TI3A_8_12_TugasBesar
5e347796a31cf9fb3b217ab4916e3719717511ea
5700d87f9f577e63e1ff47015b31c30df51d194e
refs/heads/master
2020-04-08T04:39:44.085000
2018-12-21T13:45:29
2018-12-21T13:45:29
159,026,469
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sorry.aldan.ti3a_8_12_tugasbesar.Model; public class User { int id; String nama; String email; String username; String level; public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } }
UTF-8
Java
853
java
User.java
Java
[ { "context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna", "end": 619, "score": 0.7963050603866577, "start": 611, "tag": "USERNAME", "value": "username" }, { "context": "sername(String username) {\n this....
null
[]
package sorry.aldan.ti3a_8_12_tugasbesar.Model; public class User { int id; String nama; String email; String username; String level; public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } }
853
0.554513
0.549824
53
15.094339
13.946344
47
false
false
0
0
0
0
0
0
0.301887
false
false
13
0310f63ff28e0d762be0ca6ed947b5af8b927378
14,474,039,844,990
12285fa002d7650515fc5a52661b4a35fbe0c30e
/cloudalibaba-config-nacos-client3377/src/main/java/com/NacosConfigClientMain3377.java
d79130a749f2c7d1bd73fadb1adea59d74e444a2
[]
no_license
cuckoo-cuckoo/spring-cloud
https://github.com/cuckoo-cuckoo/spring-cloud
67ef26cc7d24fc65bff7fc4eb1f2cf00de64a187
7a3eb8e153bfe6abf222486c84fc0a68998076f9
refs/heads/master
2023-02-28T21:20:03.576000
2021-02-08T19:57:37
2021-02-08T19:57:37
334,478,956
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ConfigurableApplicationContext; /** * @author Administrator * @create 2021-02-04 21:55 */ @EnableDiscoveryClient @SpringBootApplication public class NacosConfigClientMain3377 { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigClientMain3377.class, args); String userName = applicationContext.getEnvironment().getProperty("user.name"); String userAge = applicationContext.getEnvironment().getProperty("user.age"); System.err.println("user name :"+userName+"; age: "+userAge); } //启动出错:The bean 'nacosRefreshProperties', defined in class path resource [com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.class], could not be registered. A bean with that name has already been defined in URL [jar:file:/D:/Program%20Files/apache/maven-repository/com/alibaba/cloud/spring-cloud-alibaba-nacos-config/2.1.0.RELEASE/spring-cloud-alibaba-nacos-config-2.1.0.RELEASE.jar!/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.class] and overriding is disabled. }
UTF-8
Java
1,336
java
NacosConfigClientMain3377.java
Java
[ { "context": "xt.ConfigurableApplicationContext;\n\n/**\n * @author Administrator\n * @create 2021-02-04 21:55\n */\n@EnableDiscoveryC", "end": 303, "score": 0.9131991267204285, "start": 290, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ConfigurableApplicationContext; /** * @author Administrator * @create 2021-02-04 21:55 */ @EnableDiscoveryClient @SpringBootApplication public class NacosConfigClientMain3377 { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigClientMain3377.class, args); String userName = applicationContext.getEnvironment().getProperty("user.name"); String userAge = applicationContext.getEnvironment().getProperty("user.age"); System.err.println("user name :"+userName+"; age: "+userAge); } //启动出错:The bean 'nacosRefreshProperties', defined in class path resource [com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.class], could not be registered. A bean with that name has already been defined in URL [jar:file:/D:/Program%20Files/apache/maven-repository/com/alibaba/cloud/spring-cloud-alibaba-nacos-config/2.1.0.RELEASE/spring-cloud-alibaba-nacos-config-2.1.0.RELEASE.jar!/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.class] and overriding is disabled. }
1,336
0.792609
0.771493
24
54.166668
95.018715
480
false
false
0
0
0
0
0
0
0.541667
false
false
13
3e691f7c3150a2c8f53837c05ce0cd92d0079d37
14,474,039,846,099
a1a38df84e5be97f59c5d3abbc23dd78a1606e19
/src/dao/ConectorDados.java
54c185ab12efcfa8c091b114e9a62319b8043a28
[]
no_license
danilotorres9/SirastWeb
https://github.com/danilotorres9/SirastWeb
2994c894f4051fc6fe1687cd0caa7203ec46af47
c03bb2f5b280e33b87993a9ae54175d7820b9f29
refs/heads/master
2020-03-05T16:07:38.120000
2017-06-07T01:49:27
2017-06-07T01:49:27
93,465,534
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import java.sql.DriverManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConectorDados { static Statement statment; static Connection conn; public static void conectar() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://mysql.hostinger.com.br:3306/u678871300_12345", "u678871300_12345", "1234566"); statment = conn.createStatement(); } public static String logar(String telefone, String senha) throws SQLException{ ResultSet rs = statment.executeQuery("SELECT * FROM Usuarios"); while (rs.next()){ System.out.println("Dado1:"+rs.getString(1)); } statment.execute("INSERT INTO Usuarios VALUES('Romario')"); ResultSet rs3= statment.executeQuery("SELECT * FROM Usuarios"); while (rs3.next()){ System.out.println("Dado2:"+rs3.getString(1)); } return ""; } }
UTF-8
Java
971
java
ConectorDados.java
Java
[ { "context": "\n\t\tstatment.execute(\"INSERT INTO Usuarios VALUES('Romario')\");\n\t\t\n\t\tResultSet rs3= statment.executeQuery(\"S", "end": 798, "score": 0.9990187883377075, "start": 791, "tag": "NAME", "value": "Romario" } ]
null
[]
package dao; import java.sql.DriverManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConectorDados { static Statement statment; static Connection conn; public static void conectar() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://mysql.hostinger.com.br:3306/u678871300_12345", "u678871300_12345", "1234566"); statment = conn.createStatement(); } public static String logar(String telefone, String senha) throws SQLException{ ResultSet rs = statment.executeQuery("SELECT * FROM Usuarios"); while (rs.next()){ System.out.println("Dado1:"+rs.getString(1)); } statment.execute("INSERT INTO Usuarios VALUES('Romario')"); ResultSet rs3= statment.executeQuery("SELECT * FROM Usuarios"); while (rs3.next()){ System.out.println("Dado2:"+rs3.getString(1)); } return ""; } }
971
0.717817
0.670443
40
23.275
27.598902
129
false
false
0
0
0
0
0
0
1.775
false
false
13
6a9179f369b0fc9368ecdfe4df0441e3405430f4
30,605,937,004,219
e59e0e9d87ba3a6552a0ad66d431933e47049281
/xh-demo-se/src/main/java/com/xiaohe66/demo/se/oop/instanceofdemo/Son.java
d2b9abfd90ef99f0f724fe711e164499582520c8
[]
no_license
tiy-he/xh-demo
https://github.com/tiy-he/xh-demo
215e5cfc8e38202cd44d616f27bbcd35c854ac9e
c0970fddfc56fc6d4a0067983f32df3127e87dd7
refs/heads/master
2018-12-15T06:44:58.237000
2018-09-14T02:05:36
2018-09-14T02:05:36
100,341,191
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiaohe66.demo.se.oop.instanceofdemo; /** * instanceof关键字 * 该关键字可以判断某个实例是否为某个类的实例 * * @author xh * @date 17-12-20 020 */ public class Son extends Super{ public static void main(String[] args) { Super s = new Son(); Super s2 = new Super(); System.out.println(s instanceof Son); System.out.println(s2 instanceof Son); } }
UTF-8
Java
426
java
Son.java
Java
[ { "context": "stanceof关键字\n * 该关键字可以判断某个实例是否为某个类的实例\n *\n * @author xh\n * @date 17-12-20 020\n */\npublic class Son extend", "end": 112, "score": 0.9996413588523865, "start": 110, "tag": "USERNAME", "value": "xh" } ]
null
[]
package com.xiaohe66.demo.se.oop.instanceofdemo; /** * instanceof关键字 * 该关键字可以判断某个实例是否为某个类的实例 * * @author xh * @date 17-12-20 020 */ public class Son extends Super{ public static void main(String[] args) { Super s = new Son(); Super s2 = new Super(); System.out.println(s instanceof Son); System.out.println(s2 instanceof Son); } }
426
0.634921
0.600529
17
21.235294
16.996641
48
false
false
0
0
0
0
0
0
0.294118
false
false
13
8dfe939d22550d0553d2851b12fcff2fc1604810
8,169,027,852,140
027cd7112ef70fbcdb2670a009654f360bb7e06e
/net/htmlparser/jericho/StartTagTypeComment.java
2e4f8f8b144e9392a3160f7d0083130b639f0be9
[]
no_license
code4ghana/courseScheduler
https://github.com/code4ghana/courseScheduler
1c968ebc249a75661bdc22075408fc60e6d0df19
9885df3638c6b287841f8a7b751cfe1523a68fb2
refs/heads/master
2016-08-03T14:06:38.715000
2014-08-03T03:37:36
2014-08-03T03:37:36
22,566,289
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.htmlparser.jericho; final class StartTagTypeComment extends StartTagTypeGenericImplementation { static final StartTagTypeComment INSTANCE = new StartTagTypeComment(); private StartTagTypeComment() { super("comment", "<!--", "-->", null, false); } } /* Location: /Users/jeff.kusi/Downloads/AutomatedScheduler - Fakhry & Kusi.jar * Qualified Name: net.htmlparser.jericho.StartTagTypeComment * JD-Core Version: 0.6.2 */
UTF-8
Java
463
java
StartTagTypeComment.java
Java
[ { "context": "ull, false);\n }\n}\n\n/* Location: /Users/jeff.kusi/Downloads/AutomatedScheduler - Fakhry & Kusi.jar\n", "end": 315, "score": 0.9994810819625854, "start": 306, "tag": "USERNAME", "value": "jeff.kusi" } ]
null
[]
package net.htmlparser.jericho; final class StartTagTypeComment extends StartTagTypeGenericImplementation { static final StartTagTypeComment INSTANCE = new StartTagTypeComment(); private StartTagTypeComment() { super("comment", "<!--", "-->", null, false); } } /* Location: /Users/jeff.kusi/Downloads/AutomatedScheduler - Fakhry & Kusi.jar * Qualified Name: net.htmlparser.jericho.StartTagTypeComment * JD-Core Version: 0.6.2 */
463
0.717063
0.710583
16
28
30.694056
88
false
false
0
0
0
0
0
0
0.4375
false
false
13
3057f9ff6f852175f4323b7ae807a545f5f849fd
3,135,326,154,316
afcc67d6a80c4bbf984111e1d9123b437dc13494
/vocs-service/src/com/viettel/vocs/controller/AuthenticationController.java
fbbb68e2674f03e72e2792f1c2ff3498ada1798e
[]
no_license
tienpm1128/Mano-
https://github.com/tienpm1128/Mano-
144cda8ef28ddb52d025962f560cf02de2dee715
2f67d6293d1843d21af6ae1821ba6bd359423cdb
refs/heads/master
2022-12-23T04:40:22.831000
2020-03-10T15:44:12
2020-03-10T15:44:12
246,340,747
0
0
null
false
2022-12-10T05:59:55
2020-03-10T15:39:28
2020-03-10T15:48:20
2022-12-10T05:59:54
11,454
0
0
26
TypeScript
false
false
package com.viettel.vocs.controller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; import com.google.gson.Gson; import com.viettel.vocs.bo.ErrHttpCode; import com.viettel.vocs.dto.AuthRequest; import com.viettel.vocs.service.UsersService; import com.viettel.vocs.session.TokenUtil; import com.viettel.vocs.utils.Constants; import com.viettel.vocs.utils.RestUtils; import reactor.core.publisher.Mono; @RestController @RequestMapping("/vocs-service") @CrossOrigin(origins = "http://localhost:8084") public class AuthenticationController { private static Logger logger = LogManager.getLogger(AuthenticationController.class); @Value("${springbootwebfluxjjwt.jjwt.expiration}") private String expirationTime; @Value("${spring.path.json}") private String pathJson; @Autowired private UsersService usersService; @Autowired RestUtils restUtils; static final Gson gson = new Gson(); TokenUtil tokenUtils; @RequestMapping(value = "/users/auth", method = RequestMethod.POST) public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar, WebSession session) { logger.info("Authenticated information of user."); String json = gson.toJson(ar); session.getAttributes().putIfAbsent("SESSION_AUTH", json); ErrHttpCode errHttpCode = new ErrHttpCode(); errHttpCode.setMes400(Constants.MESS_400); Constants.setErrHttpCode(errHttpCode); return usersService.login(json).map((userDetails) -> { if (null != userDetails) { session.getAttributes().putIfAbsent("SESSION_TOKEN", Constants.SESSION_TOKEN); session.getAttributes().putIfAbsent("USER_SESSION", ar); return ResponseEntity.ok(userDetails); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } }).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } @RequestMapping(value = "/users/logout", method = RequestMethod.GET) public void logout(ServerWebExchange exchange) { logger.info("Log out successfully."); WebSession session = exchange.getSession().block(); session.invalidate(); } }
UTF-8
Java
2,707
java
AuthenticationController.java
Java
[]
null
[]
package com.viettel.vocs.controller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; import com.google.gson.Gson; import com.viettel.vocs.bo.ErrHttpCode; import com.viettel.vocs.dto.AuthRequest; import com.viettel.vocs.service.UsersService; import com.viettel.vocs.session.TokenUtil; import com.viettel.vocs.utils.Constants; import com.viettel.vocs.utils.RestUtils; import reactor.core.publisher.Mono; @RestController @RequestMapping("/vocs-service") @CrossOrigin(origins = "http://localhost:8084") public class AuthenticationController { private static Logger logger = LogManager.getLogger(AuthenticationController.class); @Value("${springbootwebfluxjjwt.jjwt.expiration}") private String expirationTime; @Value("${spring.path.json}") private String pathJson; @Autowired private UsersService usersService; @Autowired RestUtils restUtils; static final Gson gson = new Gson(); TokenUtil tokenUtils; @RequestMapping(value = "/users/auth", method = RequestMethod.POST) public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar, WebSession session) { logger.info("Authenticated information of user."); String json = gson.toJson(ar); session.getAttributes().putIfAbsent("SESSION_AUTH", json); ErrHttpCode errHttpCode = new ErrHttpCode(); errHttpCode.setMes400(Constants.MESS_400); Constants.setErrHttpCode(errHttpCode); return usersService.login(json).map((userDetails) -> { if (null != userDetails) { session.getAttributes().putIfAbsent("SESSION_TOKEN", Constants.SESSION_TOKEN); session.getAttributes().putIfAbsent("USER_SESSION", ar); return ResponseEntity.ok(userDetails); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } }).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } @RequestMapping(value = "/users/logout", method = RequestMethod.GET) public void logout(ServerWebExchange exchange) { logger.info("Log out successfully."); WebSession session = exchange.getSession().block(); session.invalidate(); } }
2,707
0.790543
0.78611
76
34.61842
24.471233
88
false
false
0
0
0
0
0
0
1.5
false
false
13
e707347cf1298153c751b1cde5863e96681d9b6c
32,830,730,064,979
63d794c54ffc8bd7b4e2fe0a6a7d757d8ae899fe
/IST440_Autonomous_Raptor/app/src/main/java/edu/psu/ab/ist/sworks/MainActivity.java
9b8d15e4b178150d83656e5505a6e9732e6f98d6
[]
no_license
dchen275/PSU-Projects
https://github.com/dchen275/PSU-Projects
b2bdf5ba6cf4ec132bcdd504e8c57744ed558131
51e1b315bf46597c50ba9b544ae8031b9504a651
refs/heads/master
2022-07-16T09:50:32.190000
2020-05-21T23:32:19
2020-05-21T23:32:19
265,957,697
0
0
null
false
2020-05-21T23:17:49
2020-05-21T21:43:02
2020-05-21T23:17:37
2020-05-21T23:17:48
0
0
0
1
Python
false
false
/* Project: PSA Grover Vehicle Sworks edition Feature: Main Android Activity Course: IST 440w Section 1 Fall 2019 Author: Joe Oakes Date Developed: 4/8/2019 Last Date Changed: Rev: development build 1 */ package edu.psu.ab.ist.sworks; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; /*import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity;*/ import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import edu.psu.ab.ist.sworks.mission.MissionStatus; import edu.psu.ab.ist.sworks.tensor.DetectorActivity; public class MainActivity extends AppCompatActivity { //int view = R.layout.activity_main; // TextView for the reply header private TextView mTextMessage; private Spinner setTimer; private String spinnerText; private Spinner setMissionType; public static final String selectedMissionTimer = "timer"; /*private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: mTextMessage.setText(R.string.title_home); return true; case R.id.navigation_dashboard: mTextMessage.setText(R.string.title_dashboard); return true; case R.id.navigation_notifications: mTextMessage.setText(R.string.title_notifications); return true; } return false; } };*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //new ServiceNow().execute(); // Initialize variable. TextView batteryLvl = findViewById(R.id.batteryLevel); TextView wifiText = findViewById(R.id.wifiConnectivity); TextView bluetoothText = findViewById(R.id.bluetoothConnectivity); setTimer = (Spinner) findViewById(R.id.missionTimerDDB); setMissionType = (Spinner) findViewById(R.id.missionType); final Button startMissionbtn = (Button) findViewById(R.id.startMissionbtn); final Button missionDatabtn = (Button) findViewById(R.id.missionDatabtn); final Button mapBoxbtn = (Button) findViewById(R.id.mapBoxbtn); startMissionbtn.setEnabled(false); //missionDatabtn.setEnabled(false); //mapBoxbtn.setEnabled(false); try { int level = MissionStatus.getBatteryLevel(getApplicationContext(), 10); batteryLvl.append(level + " %"); //Add back when testing to PSU //boolean wifi = MissionStatus.wifiConnected(getApplicationContext(), "PSU"); ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(mWifi.isConnected()) wifiText.append("ON"); else wifiText.append("OFF"); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth bluetoothText.append("NOT SUPPORTED"); } else if (!mBluetoothAdapter.isEnabled()) { // Bluetooth is not enabled :) bluetoothText.append("OFF"); } else { // Bluetooth is enabled bluetoothText.append("ON"); } } catch (Exception e) { batteryLvl.setText("Battery Level Too Low"); Log.d("Battery Level Too Low", e.getMessage()); } ////mission type ArrayAdapter<String> missionTypeChoices = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.missionTypes)){ @Override public boolean isEnabled(int position){ if(position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0){ // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; missionTypeChoices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); setMissionType.setAdapter(missionTypeChoices); ///mission type ends ArrayAdapter<String> timerChoices = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.times)){ @Override public boolean isEnabled(int position){ if(position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0){ // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; timerChoices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); setTimer.setAdapter(timerChoices); setTimer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { spinnerText = (String) parent.getItemAtPosition(position); // If user change the default selection // First item is disable and it is used for hint if(position > 0){ // Notify the selected item text Toast.makeText (getApplicationContext(), "Selected : " + spinnerText, Toast.LENGTH_SHORT) .show(); startMissionbtn.setEnabled(true); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); /*mTextMessage = (TextView) findViewById(R.id.message); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); BatteryManager bm = (BatteryManager) getSystemService(BATTERY_SERVICE); int percentage = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); battery_prct.setText("Battery Percentage is " + percentage + " %");*/ } public void openMapbox(View view) { Intent intent = new Intent(this, MapParameters.class); startActivity(intent); } public void openHelp(View view) { Intent intent = new Intent(this, Help.class); startActivity(intent); } public void startMissionTimer(View view) { /*Intent intent = new Intent(this, MissionTimer.class); String text = setTimer.getSelectedItem().toString(); switch(text) { case "5 Minutes": intent.putExtra(selectedMissionTimer, 300000); startActivityForResult(intent, 1); break; case "10 Minutes": intent.putExtra(selectedMissionTimer, 600000); startActivityForResult(intent, 1); break; case "15 Minutes": intent.putExtra(selectedMissionTimer, 900000); startActivityForResult(intent, 1); break; case "20 Minutes": intent.putExtra(selectedMissionTimer, 1200000); startActivityForResult(intent, 1); break; case "25 Minutes": intent.putExtra(selectedMissionTimer, 1500000); startActivityForResult(intent, 1); break; case "30 Minutes": intent.putExtra(selectedMissionTimer, 1800000); startActivityForResult(intent, 1); break; }*/ Intent intent = new Intent(this, DetectorActivity.class); intent.putExtra("MISSION_TIMER", spinnerText); startActivity(intent); } public void openMissionData(View view) { Intent intent = new Intent(this, MissionData.class); startActivity(intent); } }
UTF-8
Java
10,330
java
MainActivity.java
Java
[ { "context": "ivity\nCourse: IST 440w Section 1 Fall 2019\nAuthor: Joe Oakes\nDate Developed: 4/8/2019\nLast Date Changed:\nRev: ", "end": 131, "score": 0.9998637437820435, "start": 122, "tag": "NAME", "value": "Joe Oakes" } ]
null
[]
/* Project: PSA Grover Vehicle Sworks edition Feature: Main Android Activity Course: IST 440w Section 1 Fall 2019 Author: <NAME> Date Developed: 4/8/2019 Last Date Changed: Rev: development build 1 */ package edu.psu.ab.ist.sworks; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; /*import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity;*/ import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import edu.psu.ab.ist.sworks.mission.MissionStatus; import edu.psu.ab.ist.sworks.tensor.DetectorActivity; public class MainActivity extends AppCompatActivity { //int view = R.layout.activity_main; // TextView for the reply header private TextView mTextMessage; private Spinner setTimer; private String spinnerText; private Spinner setMissionType; public static final String selectedMissionTimer = "timer"; /*private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: mTextMessage.setText(R.string.title_home); return true; case R.id.navigation_dashboard: mTextMessage.setText(R.string.title_dashboard); return true; case R.id.navigation_notifications: mTextMessage.setText(R.string.title_notifications); return true; } return false; } };*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //new ServiceNow().execute(); // Initialize variable. TextView batteryLvl = findViewById(R.id.batteryLevel); TextView wifiText = findViewById(R.id.wifiConnectivity); TextView bluetoothText = findViewById(R.id.bluetoothConnectivity); setTimer = (Spinner) findViewById(R.id.missionTimerDDB); setMissionType = (Spinner) findViewById(R.id.missionType); final Button startMissionbtn = (Button) findViewById(R.id.startMissionbtn); final Button missionDatabtn = (Button) findViewById(R.id.missionDatabtn); final Button mapBoxbtn = (Button) findViewById(R.id.mapBoxbtn); startMissionbtn.setEnabled(false); //missionDatabtn.setEnabled(false); //mapBoxbtn.setEnabled(false); try { int level = MissionStatus.getBatteryLevel(getApplicationContext(), 10); batteryLvl.append(level + " %"); //Add back when testing to PSU //boolean wifi = MissionStatus.wifiConnected(getApplicationContext(), "PSU"); ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(mWifi.isConnected()) wifiText.append("ON"); else wifiText.append("OFF"); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth bluetoothText.append("NOT SUPPORTED"); } else if (!mBluetoothAdapter.isEnabled()) { // Bluetooth is not enabled :) bluetoothText.append("OFF"); } else { // Bluetooth is enabled bluetoothText.append("ON"); } } catch (Exception e) { batteryLvl.setText("Battery Level Too Low"); Log.d("Battery Level Too Low", e.getMessage()); } ////mission type ArrayAdapter<String> missionTypeChoices = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.missionTypes)){ @Override public boolean isEnabled(int position){ if(position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0){ // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; missionTypeChoices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); setMissionType.setAdapter(missionTypeChoices); ///mission type ends ArrayAdapter<String> timerChoices = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.times)){ @Override public boolean isEnabled(int position){ if(position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0){ // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; timerChoices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); setTimer.setAdapter(timerChoices); setTimer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { spinnerText = (String) parent.getItemAtPosition(position); // If user change the default selection // First item is disable and it is used for hint if(position > 0){ // Notify the selected item text Toast.makeText (getApplicationContext(), "Selected : " + spinnerText, Toast.LENGTH_SHORT) .show(); startMissionbtn.setEnabled(true); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); /*mTextMessage = (TextView) findViewById(R.id.message); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); BatteryManager bm = (BatteryManager) getSystemService(BATTERY_SERVICE); int percentage = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); battery_prct.setText("Battery Percentage is " + percentage + " %");*/ } public void openMapbox(View view) { Intent intent = new Intent(this, MapParameters.class); startActivity(intent); } public void openHelp(View view) { Intent intent = new Intent(this, Help.class); startActivity(intent); } public void startMissionTimer(View view) { /*Intent intent = new Intent(this, MissionTimer.class); String text = setTimer.getSelectedItem().toString(); switch(text) { case "5 Minutes": intent.putExtra(selectedMissionTimer, 300000); startActivityForResult(intent, 1); break; case "10 Minutes": intent.putExtra(selectedMissionTimer, 600000); startActivityForResult(intent, 1); break; case "15 Minutes": intent.putExtra(selectedMissionTimer, 900000); startActivityForResult(intent, 1); break; case "20 Minutes": intent.putExtra(selectedMissionTimer, 1200000); startActivityForResult(intent, 1); break; case "25 Minutes": intent.putExtra(selectedMissionTimer, 1500000); startActivityForResult(intent, 1); break; case "30 Minutes": intent.putExtra(selectedMissionTimer, 1800000); startActivityForResult(intent, 1); break; }*/ Intent intent = new Intent(this, DetectorActivity.class); intent.putExtra("MISSION_TIMER", spinnerText); startActivity(intent); } public void openMissionData(View view) { Intent intent = new Intent(this, MissionData.class); startActivity(intent); } }
10,327
0.589158
0.581317
284
35.376762
26.110861
115
false
false
0
0
0
0
0
0
0.566901
false
false
13
1de05c2acba62d6777de71e80aee0433185ab5b0
28,063,316,321,738
76641ff4fa10954d66599ffae01785f186865c1a
/src/coplan/pacman/Corner.java
bbc3dc2b84d309731d5cfd5bb4f97428967d631a
[]
no_license
AaronCoplan/Pacman-2.0
https://github.com/AaronCoplan/Pacman-2.0
2ec74c45244589fe33ae35b8bacc4fbdbda2cabd
037c54f76be9e419585c00b5eb406627a4ce167e
refs/heads/master
2016-09-07T14:40:12.355000
2016-06-06T04:53:38
2016-06-06T04:53:38
44,834,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coplan.pacman; import java.awt.Color; public class Corner { private int x, y; private char[] dirs; private char type; private Color color; public Corner(int x, int y, char[] dirs, char type){ this.x = x; this.y = y; this.dirs = dirs; this.type = type; } public Corner(int x, int y, char[] dirs, char type, Color color){ this.x = x; this.y = y; this.dirs = dirs; this.type = type; this.color = color; } public Color getColor(){ return color; } public char getType(){ return type; } public int getX(){ return x; } public int getY(){ return y; } public char[] getDirs(){ return dirs; } }
UTF-8
Java
656
java
Corner.java
Java
[]
null
[]
package coplan.pacman; import java.awt.Color; public class Corner { private int x, y; private char[] dirs; private char type; private Color color; public Corner(int x, int y, char[] dirs, char type){ this.x = x; this.y = y; this.dirs = dirs; this.type = type; } public Corner(int x, int y, char[] dirs, char type, Color color){ this.x = x; this.y = y; this.dirs = dirs; this.type = type; this.color = color; } public Color getColor(){ return color; } public char getType(){ return type; } public int getX(){ return x; } public int getY(){ return y; } public char[] getDirs(){ return dirs; } }
656
0.617378
0.617378
46
13.26087
13.194918
66
false
false
0
0
0
0
0
0
1.76087
false
false
13
c499b6075e6f9fbfe1276af80c3aa3247f21796f
28,905,129,915,509
d5cbeda307dac2beff62d170fdb1e70015d40b58
/app/src/main/java/com/example/binusezyfood/Items/ItemHolder.java
945587cbace84be4d3e5ce40231f15f1fbb8c2b9
[]
no_license
NeoSuko/ProjectFinalAssignments
https://github.com/NeoSuko/ProjectFinalAssignments
ea2666f24f0cd7570df706f30e3d07a4ae4e75f2
33a20470f0f0cf76a120cd25e64c4768b2462f93
refs/heads/main
2023-02-21T04:11:29.488000
2021-01-10T07:09:37
2021-01-10T07:09:37
328,299,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.binusezyfood.Items; import java.util.ArrayList; public class ItemHolder { public ArrayList<Item> item; private static ItemHolder instance; private ItemHolder(){ item = new ArrayList<Item>(); } public static ItemHolder getInstance(){ if(instance == null){ instance = new ItemHolder(); } return instance; } }
UTF-8
Java
399
java
ItemHolder.java
Java
[]
null
[]
package com.example.binusezyfood.Items; import java.util.ArrayList; public class ItemHolder { public ArrayList<Item> item; private static ItemHolder instance; private ItemHolder(){ item = new ArrayList<Item>(); } public static ItemHolder getInstance(){ if(instance == null){ instance = new ItemHolder(); } return instance; } }
399
0.629073
0.629073
19
20
15.914244
43
false
false
0
0
0
0
0
0
0.368421
false
false
13
58cba36095dda4c85241610728346ddebf10f6b3
28,965,259,481,714
3059624d7d9b305e45ee5d23e87ff3cfe66a5680
/Lab_05_five/Object_ArrayList/ObjectArrayList.java
867e3cca4e765ec1a4000642f542d36354c84baf
[]
no_license
sadegh-babapour/Java-Course-Excercises
https://github.com/sadegh-babapour/Java-Course-Excercises
8e8b3268675c1331408922233ae425979b15c56c
24396cd3025d0f387dc866bb12017bc386fc49ac
refs/heads/master
2020-06-11T12:11:37.762000
2019-07-08T08:46:49
2019-07-08T08:46:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ObjectArrayList { private Point[] pointz; public ObjectArrayList (int size){ if (size > 0) pointz = new Point [size]; } public ObjectArrayList () { pointz = new Point[0]; } public void addElement (Point p) { if (pointz.length <1) { Point[] tempArr = new Point[pointz.length + 1]; tempArr[0] = p; pointz = tempArr; } else { Point[] tempArr = new Point[pointz.length + 1]; for (int index = 0; index < pointz.length; index++) { tempArr[index] = pointz[index]; } tempArr[tempArr.length - 1] = p; pointz = tempArr; } } // @Override // public String toString () { // String strng = "["; // // for (int i = 0; i < pointz.length; i++) { // // if (i != pointz.length - 1) { // strng += pointz[i] + ","; // } // else { // strng += pointz[i]; // } // } // strng += "]"; // return strng; // } public void insertAt(int index, Point p) { if (index < pointz.length && index > -1) { Point[] tempArr = new Point[pointz.length + 1]; for (int i = 0; i < index; i++) { tempArr[i] = pointz[i]; } for (int i = index; i < pointz.length; i++) { tempArr[i + 1] = pointz[i]; } tempArr[index] = p; pointz = tempArr; } else { System.out.println("invalid index"); } } public void removeAt(int index) { if (index < pointz.length && index > -1) { Point[] tempArr = new Point[pointz.length - 1]; for (int i = 0; i < index; i++) { tempArr[i] = pointz[i]; } for (int i = index; i < pointz.length - 1; i++) { tempArr[i] = pointz[i + 1]; } pointz = tempArr; } else { System.out.println("invalid index"); } } public void resize(int length) { if (length >= pointz.length || length < 0) { System.out.println("invalid length!"); } else { Point[] tempArr = new Point[length]; for (int i = 0; i < length; i++) { tempArr[i] = pointz[i]; } pointz = tempArr; } } // this part is already taken care of in the .toString override, but will implement it to satisfy the req. public void printElements(){ String strng = "["; for (int i = 0; i < pointz.length; i++) { if (i != pointz.length - 1) { strng += pointz[i] + ", "; } else { strng += pointz[i]; } } strng += "]"; System.out.println(strng); } }
UTF-8
Java
2,939
java
ObjectArrayList.java
Java
[]
null
[]
public class ObjectArrayList { private Point[] pointz; public ObjectArrayList (int size){ if (size > 0) pointz = new Point [size]; } public ObjectArrayList () { pointz = new Point[0]; } public void addElement (Point p) { if (pointz.length <1) { Point[] tempArr = new Point[pointz.length + 1]; tempArr[0] = p; pointz = tempArr; } else { Point[] tempArr = new Point[pointz.length + 1]; for (int index = 0; index < pointz.length; index++) { tempArr[index] = pointz[index]; } tempArr[tempArr.length - 1] = p; pointz = tempArr; } } // @Override // public String toString () { // String strng = "["; // // for (int i = 0; i < pointz.length; i++) { // // if (i != pointz.length - 1) { // strng += pointz[i] + ","; // } // else { // strng += pointz[i]; // } // } // strng += "]"; // return strng; // } public void insertAt(int index, Point p) { if (index < pointz.length && index > -1) { Point[] tempArr = new Point[pointz.length + 1]; for (int i = 0; i < index; i++) { tempArr[i] = pointz[i]; } for (int i = index; i < pointz.length; i++) { tempArr[i + 1] = pointz[i]; } tempArr[index] = p; pointz = tempArr; } else { System.out.println("invalid index"); } } public void removeAt(int index) { if (index < pointz.length && index > -1) { Point[] tempArr = new Point[pointz.length - 1]; for (int i = 0; i < index; i++) { tempArr[i] = pointz[i]; } for (int i = index; i < pointz.length - 1; i++) { tempArr[i] = pointz[i + 1]; } pointz = tempArr; } else { System.out.println("invalid index"); } } public void resize(int length) { if (length >= pointz.length || length < 0) { System.out.println("invalid length!"); } else { Point[] tempArr = new Point[length]; for (int i = 0; i < length; i++) { tempArr[i] = pointz[i]; } pointz = tempArr; } } // this part is already taken care of in the .toString override, but will implement it to satisfy the req. public void printElements(){ String strng = "["; for (int i = 0; i < pointz.length; i++) { if (i != pointz.length - 1) { strng += pointz[i] + ", "; } else { strng += pointz[i]; } } strng += "]"; System.out.println(strng); } }
2,939
0.430078
0.422252
105
27
19.955666
110
false
false
0
0
0
0
0
0
0.542857
false
false
13
d3100d30951e1a9540d9a52773fcd0f505f24896
13,142,599,971,010
d4620d6d1c0f0cdc7ddc3c8f20cb563fce46af32
/src/gui/util/calculos/Relatorio.java
34382262a2f4097376b1eee60b17581c07269fd9
[]
no_license
zidan-haq/Conta-notas
https://github.com/zidan-haq/Conta-notas
3195d7ecaad06c76d3b85bcc8b31acec0c182fb6
94da2fe9fa65f1690780042c1861cb97884c1b03
refs/heads/master
2021-07-16T13:39:42.586000
2021-01-04T20:24:02
2021-01-04T20:24:02
227,891,513
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gui.util.calculos; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Optional; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.print.SimpleDoc; import gui.conf.Configuracoes; import gui.util.Alerts; import gui.util.ConferirPrograma; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Relatorio { Configuracoes conf = new Configuracoes(); Calendar cal = Calendar.getInstance(); DateTimeFormatter dtm = DateTimeFormatter.ofPattern("dd-MM-yyyy"); public static String quantidadeEmCaixa; public static double totalCartao; public static double totalCredito; public static double totalDebito; public static double totalDinheiro; public static double totalDoDiaSemOnline; public static double totalDoDiaIfood; public static double onlineIfood; public static double dinheiroIfood; public static double cartaoIfood; public static void toStringQuantidadeEmCaixa(List<TextField> listQuantidadeDeNotas, Label totalEmCaixa, TextField descontarCreditoAmanha, TextField descontarDebitoAmanha) { String string = ""; string += String.format("Descontar no próximo caixa:\nCrédito = %.2f\n", Double.parseDouble(descontarCreditoAmanha.getText())); string += String.format("Débito = %.2f\n", Double.parseDouble(descontarDebitoAmanha.getText())); string += "------------------------------\n"; string += "Total em caixa:\n"; String[] tiposDeNotas = { " 100 = ", "\n 50 = ", "\n 20 = ", "\n 10 = ", "\n 5 = ", "\n 2 = ", "\n 1 = ", "\n 0.50 = ", "\n 0.25 = ", "\n 0.10 = ", "\n 0.05 = " }; for (int x = 0; x < listQuantidadeDeNotas.size(); x++) { Integer quantidadeDeNota = Integer.parseInt(listQuantidadeDeNotas.get(x).getText()); if (quantidadeDeNota != 0) { string += String.format("%s%d", tiposDeNotas[x], quantidadeDeNota); } } string += ("\nTotal = " + totalEmCaixa.getText()); quantidadeEmCaixa = string; ConferirPrograma.mudarJaSalvo(false); } // Métodos para gerar a Pré-visualização na tela public static void valoresLoja(Label totalEmDinheiro, Label totalEmCartao, Label credito, Label debito, Label totalDoDia) { totalDinheiro = Double.parseDouble(totalEmDinheiro.getText()); totalCartao = Double.parseDouble(totalEmCartao.getText()); totalCredito = Double.parseDouble(credito.getText()); totalDebito = Double.parseDouble(debito.getText()); totalDoDiaSemOnline = Double.parseDouble(totalDoDia.getText()); ConferirPrograma.mudarJaSalvo(false); } public static void valoresIfood(TextField online, TextField dinheiro, TextField cartao, Label totalDoDia) { onlineIfood = Double.parseDouble(online.getText()); dinheiroIfood = Double.parseDouble(dinheiro.getText()); cartaoIfood = Double.parseDouble(cartao.getText()); totalDoDiaIfood = Double.parseDouble(totalDoDia.getText()); ConferirPrograma.mudarJaSalvo(false); } public String stringTotalDoDia(double totalCartao, double totalCredito, double totalDebito, double totalDinheiro, double totalDoDiaSemOnline, double totalDoDiaIfood, double onlineIfood, double dinheiroIfood, double cartaoIfood) { String str = String.format("LOJA: R$ %.2f\n", totalDoDiaSemOnline - cartaoIfood - dinheiroIfood); str += String.format(" * Dinheiro: R$ %.2f\n", totalDinheiro - dinheiroIfood); str += String.format(" * Cartão: R$ %.2f\n", totalCartao - cartaoIfood); str += String.format("\nIFOOD: R$ %.2f\n", totalDoDiaIfood); str += String.format(" * Dinheiro: R$ %.2f\n", dinheiroIfood); str += String.format(" * Cartão: R$ %.2f\n", cartaoIfood); str += String.format(" * Online: R$ %.2f\n", onlineIfood); str += String.format("\n------------------------"); str += String.format("\nTOTAL: R$ %.2f\n", totalDoDiaSemOnline + onlineIfood); str += String.format(" * Dinheiro: R$ %.2f\n", totalDinheiro); str += String.format(" * Cartão: R$ %.2f\n", totalCartao); str += String.format(" -> Crédito: R$ %.2f\n", totalCredito); str += String.format(" -> Débito: R$ %.2f\n", totalDebito); str += String.format(" * Online Ifood: R$ %.2f\n", onlineIfood); return str; } public void imprimir(TextArea quantidadeEmCaixa, TextArea totalDoDia, RadioButton imprimirTotalDoDia) { if (conf.atualizarEVerificarConfiguracao()) { String impressao = imprimirTotalDoDia.isSelected() ? quantidadeEmCaixa.getText() + "\n\n\n\n\n" + ("" + (char) 27 + (char) 109) + totalDoDia.getText() + "\n\n\n\n\n" + ("" + (char) 27 + (char) 109) : quantidadeEmCaixa.getText() + "\n\n\n\n\n" + ("" + (char) 27 + (char) 109); PrintService impressora = null; try { DocFlavor df = DocFlavor.SERVICE_FORMATTED.PRINTABLE; PrintService[] ps = PrintServiceLookup.lookupPrintServices(df, null); for (PrintService p : ps) { if (p.getName() != null && p.getName().contains(conf.getSelecionarImpressora())) { impressora = p; } } } catch (Exception e) { Alerts.showAlert("Erro ao imprimir", "PrintException", e.getMessage(), Alert.AlertType.ERROR); } //------------------------------ if (impressora == null || impressora.getName().isEmpty()) { Alerts.showAlert("Erro ao imprimir", "Impressora não encontrada", "Selecione uma impressora em 'Configurações'\nantes de tentar imprimir", Alert.AlertType.WARNING); } else if(!quantidadeEmCaixa.getText().isEmpty()) { try { DocPrintJob dpj = impressora.createPrintJob(); InputStream stream = new ByteArrayInputStream( (impressao).getBytes()); DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc doc = new SimpleDoc(stream, flavor, null); dpj.print(doc, null); System.out.println(impressora.getName()); } catch (PrintException e) { Alerts.showAlert("Erro ao imprimir", "PrintException", e.getMessage(), Alert.AlertType.ERROR); } } } } public void salvar(TextArea quantidadeEmCaixa, TextArea totalDoDia, DatePicker datePicker) { boolean continuar = true; if (conf.atualizarEVerificarConfiguracao()) { if (quantidadeEmCaixa.getText().isEmpty() || totalDoDia.getText().isEmpty()) { Alerts.showAlert("Erro ao tentar salvar", "Há um ou mais campos vazios", "Você deve preencher o campo 'Quantidade em\n caixa' e 'Total do dia' antes de salvar", Alert.AlertType.ERROR); } else { if(estaSobrescrevendo(datePicker)) { Optional<ButtonType> resultado = Alerts.showAlert("Confirme", "Já existe um arquivo com está data.", "Deseja sobrescrevê-lo?", AlertType.CONFIRMATION); if(resultado.get() != ButtonType.OK) { continuar = false; } } if(continuar) { //este try() irá criar os txt's dos caixas na pasta try (BufferedWriter bw = new BufferedWriter( new FileWriter(conf.getLocalArmazenamentoDeCaixas() + datePicker.getValue().format(dtm) + ".txt"))) { bw.write(quantidadeEmCaixa.getText()); Alerts.showAlert("Concluído", null, "A operação foi realizada com sucesso", Alert.AlertType.INFORMATION); ConferirPrograma.mudarJaSalvo(true); } catch (IOException e) { Alerts.showAlert("Falha ao tentar salvar arquivo", "O programa não está configurado corretamente", e.getMessage(), Alert.AlertType.ERROR); } // este segundo try{} salva o total do dia na pasta principal do programa, // separado da quantidade do dia try (BufferedWriter bw = new BufferedWriter(new FileWriter(conf.getLocalArmazenamentoTotalDoDia() + datePicker.getValue().format(dtm)))) { bw.write(totalDoDia.getText()); } catch (IOException e) { e.getMessage(); } // esse comando manterá salvo apenas a quantidade de caixas configuradas para // serem salvas. if (conf.getQuantidadeDeCaixasSalvos() == null) { Alerts.showAlert("Programa não configurado", "O programa não está configurado corretamente", null, Alert.AlertType.ERROR); } else { apagarArqAntigos(conf.getLocalArmazenamentoDeCaixas()); apagarArqAntigos(conf.getLocalArmazenamentoTotalDoDia()); } } } } } private boolean estaSobrescrevendo(DatePicker datePicker) { boolean resposta = false; File[] arquivos = new File(conf.getLocalArmazenamentoDeCaixas()).listFiles(); for(File x : arquivos) { if(x.getName().equals(datePicker.getValue().format(dtm)+".txt")) { resposta = true; } } return resposta; } private void apagarArqAntigos(String local) { List<File> arquivos = Arrays.asList(new File(local).listFiles()); ordenarArquivosPorNome(arquivos); //essa parte do código exclui os dias 30 e 31 quando não satisfazem mais a quantidade de caixas que devem ser mantidos salvos arquivos.forEach(x -> { if (conf.getQuantidadeDeCaixasSalvos() == 2 && arquivos.indexOf(x) > 1) { x.delete(); } else if (conf.getQuantidadeDeCaixasSalvos() == 3 && arquivos.indexOf(x) > 2) { x.delete(); } else if (conf.getQuantidadeDeCaixasSalvos() == 7 && arquivos.indexOf(x) > 6) { x.delete(); } }); } private void ordenarArquivosPorNome(List<File> arquivos) { arquivos.sort((a1, a2) -> { String[] tupla = a1.getName().replaceAll(".txt", "").split("-"); Integer a1Inteiro = Integer.parseInt(tupla[2] + tupla[1] + tupla[0]); tupla = a2.getName().replaceAll(".txt", "").split("-"); Integer a2Inteiro = Integer.parseInt(tupla[2] + tupla[1] + tupla[0]); return a1Inteiro.compareTo(a2Inteiro); }); } public static void limparTudo() { quantidadeEmCaixa = null; totalCartao = 0; totalCredito = 0; totalDebito = 0; totalDinheiro = 0; totalDoDiaSemOnline = 0; totalDoDiaIfood = 0; onlineIfood = 0; dinheiroIfood = 0; cartaoIfood = 0; ConferirPrograma.mudarJaSalvo(true); } }
UTF-8
Java
10,425
java
Relatorio.java
Java
[]
null
[]
package gui.util.calculos; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Optional; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.print.SimpleDoc; import gui.conf.Configuracoes; import gui.util.Alerts; import gui.util.ConferirPrograma; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Relatorio { Configuracoes conf = new Configuracoes(); Calendar cal = Calendar.getInstance(); DateTimeFormatter dtm = DateTimeFormatter.ofPattern("dd-MM-yyyy"); public static String quantidadeEmCaixa; public static double totalCartao; public static double totalCredito; public static double totalDebito; public static double totalDinheiro; public static double totalDoDiaSemOnline; public static double totalDoDiaIfood; public static double onlineIfood; public static double dinheiroIfood; public static double cartaoIfood; public static void toStringQuantidadeEmCaixa(List<TextField> listQuantidadeDeNotas, Label totalEmCaixa, TextField descontarCreditoAmanha, TextField descontarDebitoAmanha) { String string = ""; string += String.format("Descontar no próximo caixa:\nCrédito = %.2f\n", Double.parseDouble(descontarCreditoAmanha.getText())); string += String.format("Débito = %.2f\n", Double.parseDouble(descontarDebitoAmanha.getText())); string += "------------------------------\n"; string += "Total em caixa:\n"; String[] tiposDeNotas = { " 100 = ", "\n 50 = ", "\n 20 = ", "\n 10 = ", "\n 5 = ", "\n 2 = ", "\n 1 = ", "\n 0.50 = ", "\n 0.25 = ", "\n 0.10 = ", "\n 0.05 = " }; for (int x = 0; x < listQuantidadeDeNotas.size(); x++) { Integer quantidadeDeNota = Integer.parseInt(listQuantidadeDeNotas.get(x).getText()); if (quantidadeDeNota != 0) { string += String.format("%s%d", tiposDeNotas[x], quantidadeDeNota); } } string += ("\nTotal = " + totalEmCaixa.getText()); quantidadeEmCaixa = string; ConferirPrograma.mudarJaSalvo(false); } // Métodos para gerar a Pré-visualização na tela public static void valoresLoja(Label totalEmDinheiro, Label totalEmCartao, Label credito, Label debito, Label totalDoDia) { totalDinheiro = Double.parseDouble(totalEmDinheiro.getText()); totalCartao = Double.parseDouble(totalEmCartao.getText()); totalCredito = Double.parseDouble(credito.getText()); totalDebito = Double.parseDouble(debito.getText()); totalDoDiaSemOnline = Double.parseDouble(totalDoDia.getText()); ConferirPrograma.mudarJaSalvo(false); } public static void valoresIfood(TextField online, TextField dinheiro, TextField cartao, Label totalDoDia) { onlineIfood = Double.parseDouble(online.getText()); dinheiroIfood = Double.parseDouble(dinheiro.getText()); cartaoIfood = Double.parseDouble(cartao.getText()); totalDoDiaIfood = Double.parseDouble(totalDoDia.getText()); ConferirPrograma.mudarJaSalvo(false); } public String stringTotalDoDia(double totalCartao, double totalCredito, double totalDebito, double totalDinheiro, double totalDoDiaSemOnline, double totalDoDiaIfood, double onlineIfood, double dinheiroIfood, double cartaoIfood) { String str = String.format("LOJA: R$ %.2f\n", totalDoDiaSemOnline - cartaoIfood - dinheiroIfood); str += String.format(" * Dinheiro: R$ %.2f\n", totalDinheiro - dinheiroIfood); str += String.format(" * Cartão: R$ %.2f\n", totalCartao - cartaoIfood); str += String.format("\nIFOOD: R$ %.2f\n", totalDoDiaIfood); str += String.format(" * Dinheiro: R$ %.2f\n", dinheiroIfood); str += String.format(" * Cartão: R$ %.2f\n", cartaoIfood); str += String.format(" * Online: R$ %.2f\n", onlineIfood); str += String.format("\n------------------------"); str += String.format("\nTOTAL: R$ %.2f\n", totalDoDiaSemOnline + onlineIfood); str += String.format(" * Dinheiro: R$ %.2f\n", totalDinheiro); str += String.format(" * Cartão: R$ %.2f\n", totalCartao); str += String.format(" -> Crédito: R$ %.2f\n", totalCredito); str += String.format(" -> Débito: R$ %.2f\n", totalDebito); str += String.format(" * Online Ifood: R$ %.2f\n", onlineIfood); return str; } public void imprimir(TextArea quantidadeEmCaixa, TextArea totalDoDia, RadioButton imprimirTotalDoDia) { if (conf.atualizarEVerificarConfiguracao()) { String impressao = imprimirTotalDoDia.isSelected() ? quantidadeEmCaixa.getText() + "\n\n\n\n\n" + ("" + (char) 27 + (char) 109) + totalDoDia.getText() + "\n\n\n\n\n" + ("" + (char) 27 + (char) 109) : quantidadeEmCaixa.getText() + "\n\n\n\n\n" + ("" + (char) 27 + (char) 109); PrintService impressora = null; try { DocFlavor df = DocFlavor.SERVICE_FORMATTED.PRINTABLE; PrintService[] ps = PrintServiceLookup.lookupPrintServices(df, null); for (PrintService p : ps) { if (p.getName() != null && p.getName().contains(conf.getSelecionarImpressora())) { impressora = p; } } } catch (Exception e) { Alerts.showAlert("Erro ao imprimir", "PrintException", e.getMessage(), Alert.AlertType.ERROR); } //------------------------------ if (impressora == null || impressora.getName().isEmpty()) { Alerts.showAlert("Erro ao imprimir", "Impressora não encontrada", "Selecione uma impressora em 'Configurações'\nantes de tentar imprimir", Alert.AlertType.WARNING); } else if(!quantidadeEmCaixa.getText().isEmpty()) { try { DocPrintJob dpj = impressora.createPrintJob(); InputStream stream = new ByteArrayInputStream( (impressao).getBytes()); DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc doc = new SimpleDoc(stream, flavor, null); dpj.print(doc, null); System.out.println(impressora.getName()); } catch (PrintException e) { Alerts.showAlert("Erro ao imprimir", "PrintException", e.getMessage(), Alert.AlertType.ERROR); } } } } public void salvar(TextArea quantidadeEmCaixa, TextArea totalDoDia, DatePicker datePicker) { boolean continuar = true; if (conf.atualizarEVerificarConfiguracao()) { if (quantidadeEmCaixa.getText().isEmpty() || totalDoDia.getText().isEmpty()) { Alerts.showAlert("Erro ao tentar salvar", "Há um ou mais campos vazios", "Você deve preencher o campo 'Quantidade em\n caixa' e 'Total do dia' antes de salvar", Alert.AlertType.ERROR); } else { if(estaSobrescrevendo(datePicker)) { Optional<ButtonType> resultado = Alerts.showAlert("Confirme", "Já existe um arquivo com está data.", "Deseja sobrescrevê-lo?", AlertType.CONFIRMATION); if(resultado.get() != ButtonType.OK) { continuar = false; } } if(continuar) { //este try() irá criar os txt's dos caixas na pasta try (BufferedWriter bw = new BufferedWriter( new FileWriter(conf.getLocalArmazenamentoDeCaixas() + datePicker.getValue().format(dtm) + ".txt"))) { bw.write(quantidadeEmCaixa.getText()); Alerts.showAlert("Concluído", null, "A operação foi realizada com sucesso", Alert.AlertType.INFORMATION); ConferirPrograma.mudarJaSalvo(true); } catch (IOException e) { Alerts.showAlert("Falha ao tentar salvar arquivo", "O programa não está configurado corretamente", e.getMessage(), Alert.AlertType.ERROR); } // este segundo try{} salva o total do dia na pasta principal do programa, // separado da quantidade do dia try (BufferedWriter bw = new BufferedWriter(new FileWriter(conf.getLocalArmazenamentoTotalDoDia() + datePicker.getValue().format(dtm)))) { bw.write(totalDoDia.getText()); } catch (IOException e) { e.getMessage(); } // esse comando manterá salvo apenas a quantidade de caixas configuradas para // serem salvas. if (conf.getQuantidadeDeCaixasSalvos() == null) { Alerts.showAlert("Programa não configurado", "O programa não está configurado corretamente", null, Alert.AlertType.ERROR); } else { apagarArqAntigos(conf.getLocalArmazenamentoDeCaixas()); apagarArqAntigos(conf.getLocalArmazenamentoTotalDoDia()); } } } } } private boolean estaSobrescrevendo(DatePicker datePicker) { boolean resposta = false; File[] arquivos = new File(conf.getLocalArmazenamentoDeCaixas()).listFiles(); for(File x : arquivos) { if(x.getName().equals(datePicker.getValue().format(dtm)+".txt")) { resposta = true; } } return resposta; } private void apagarArqAntigos(String local) { List<File> arquivos = Arrays.asList(new File(local).listFiles()); ordenarArquivosPorNome(arquivos); //essa parte do código exclui os dias 30 e 31 quando não satisfazem mais a quantidade de caixas que devem ser mantidos salvos arquivos.forEach(x -> { if (conf.getQuantidadeDeCaixasSalvos() == 2 && arquivos.indexOf(x) > 1) { x.delete(); } else if (conf.getQuantidadeDeCaixasSalvos() == 3 && arquivos.indexOf(x) > 2) { x.delete(); } else if (conf.getQuantidadeDeCaixasSalvos() == 7 && arquivos.indexOf(x) > 6) { x.delete(); } }); } private void ordenarArquivosPorNome(List<File> arquivos) { arquivos.sort((a1, a2) -> { String[] tupla = a1.getName().replaceAll(".txt", "").split("-"); Integer a1Inteiro = Integer.parseInt(tupla[2] + tupla[1] + tupla[0]); tupla = a2.getName().replaceAll(".txt", "").split("-"); Integer a2Inteiro = Integer.parseInt(tupla[2] + tupla[1] + tupla[0]); return a1Inteiro.compareTo(a2Inteiro); }); } public static void limparTudo() { quantidadeEmCaixa = null; totalCartao = 0; totalCredito = 0; totalDebito = 0; totalDinheiro = 0; totalDoDiaSemOnline = 0; totalDoDiaIfood = 0; onlineIfood = 0; dinheiroIfood = 0; cartaoIfood = 0; ConferirPrograma.mudarJaSalvo(true); } }
10,425
0.690753
0.68219
269
37.635689
33.670185
156
false
false
0
0
0
0
0
0
3.189591
false
false
13
31a7a863304894cb00a244e862eca4192565e379
17,317,308,168,043
4a7cb14aa934df8f362cf96770e3e724657938d8
/MFES/ATS/Project/structuring/projectsPOO_1920/45/TrazAqui!/Dados.java
8e6be7991432ac9f8a7baa81074c22b93125ea93
[]
no_license
pCosta99/Masters
https://github.com/pCosta99/Masters
7091a5186f581a7d73fd91a3eb31880fa82bff19
f835220de45a3330ac7a8b627e5e4bf0d01d9f1f
refs/heads/master
2023-08-11T01:01:53.554000
2021-09-22T07:51:51
2021-09-22T07:51:51
334,012,667
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.*; import java.lang.*; import java.io.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; import static java.lang.Character.isDigit; /** * Dados - Registo com todos os utilizadores, voluntarios, transportadoras, lojas e encomendas existentes no sistema. * * @author (Eduardo Araujo, Ricardo Machado, Guilherme Araujo) * @version 11/06/2020 */ public class Dados implements Serializable { private Map<String, Utilizador> utilizadores; //email,User private Map<String, Voluntario> voluntarios; private Map<String, Transportadora> transportadoras; private Map<String, Loja> lojas; private Map<String, Double> classificacoes; //codEnc,Score private List<Encomenda> encomendas; /** * Construtor para objetos da classe Dados (por omissao) */ public Dados() { this.utilizadores = new HashMap<>(); this.voluntarios = new HashMap<>(); this.transportadoras = new HashMap<>(); this.lojas = new HashMap<>(); this.classificacoes = new HashMap<>(); this.encomendas = new ArrayList<>(); } /** * Construtor para objetos da classe Dados (parameterizado) * * @param user os utilizadores * @param volu os voluntarios * @param tran as transportadoras * @param loja as lojas * @param encomendas as encomendas */ public Dados(Map<String, Utilizador> user, Map<String, Voluntario> volu, Map<String, Transportadora> tran, Map<String, Loja> loja, Map<String, Double> classificacoes, List<Encomenda> encomendas) { this.setUtilizadores(user); this.setVoluntarios(volu); this.setTransportadoras(tran); this.setLojas(loja); this.setEncomendas(encomendas); this.setClassificacoes(classificacoes); } /** * Construtor para objetos da classe Dados (de copia) * * @param d os dados */ public Dados(Dados d) { this.utilizadores = d.getUtilizadores(); this.voluntarios = d.getVoluntarios(); this.transportadoras = d.getTransportadoras(); this.lojas = d.getLojas(); this.classificacoes = d.getClassificacoes(); List<Encomenda> encomendasClone = new ArrayList<>(); for (Encomenda e : d.encomendas) { encomendasClone.add(e.clone()); } this.encomendas = encomendasClone; } /** * Metodo que devolve os utilizadores de um conjunto de dados * * @return os utilizadores dos dados */ public Map<String, Utilizador> getUtilizadores() { Map<String, Utilizador> aux = new HashMap<>(); for (String em : this.utilizadores.keySet()) { Utilizador c = this.utilizadores.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve os voluntarios de um conjunto de dados * * @return os voluntarios dos dados */ public Map<String, Voluntario> getVoluntarios() { Map<String, Voluntario> aux = new HashMap<>(); for (String em : this.voluntarios.keySet()) { Voluntario c = this.voluntarios.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve as transportadoras de um conjunto de dados * * @return as transportadoras dos dados */ public Map<String, Transportadora> getTransportadoras() { Map<String, Transportadora> aux = new HashMap<>(); for (String em : this.transportadoras.keySet()) { Transportadora c = this.transportadoras.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve as lojas de um conjunto de dados * * @return as lojas dos dados */ public Map<String, Loja> getLojas() { Map<String, Loja> aux = new HashMap<>(); for (String em : this.lojas.keySet()) { Loja c = this.lojas.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve as classificacoes de um conjunto de dados * * @return as classificacoes dos dados */ public Map<String, Double> getClassificacoes() { Map<String, Double> aux = new HashMap<>(); for (String em : this.classificacoes.keySet()) { Double c = this.classificacoes.get(em); aux.put(em, c); } return aux; } /** * Metodo que devolve as encomendas de um conjunto de dados * * @return as encomendas dos dados */ public List<Encomenda> getEncomendas() { List<Encomenda> aux = new ArrayList<>(); for (Encomenda a : this.encomendas) aux.add(a.clone()); return aux; } /** * Metodo que altera os utilizadores de um conjunto de dados * * @param usr os novos utilizadores */ public void setUtilizadores(Map<String, Utilizador> usr) { this.utilizadores = usr.values().stream() .collect(Collectors .toMap((Utilizador::getEmail), Utilizador::clone)); } public void setClassificacoes(Map<String, Double> cla) { for(String s : cla.keySet()){ classificacoes.put(s,cla.get(s)); } } /** * Metodo que altera os voluntarios de um conjunto de dados * * @param vol os novos voluntarios */ public void setVoluntarios(Map<String, Voluntario> vol) { this.voluntarios = vol.values().stream() .collect(Collectors .toMap((Voluntario::getEmail), Voluntario::clone)); } /** * Metodo que altera as trasnportadoras de um conjunto de dados * * @param tra as novas transportadoras */ public void setTransportadoras(Map<String, Transportadora> tra) { this.transportadoras = tra.values().stream() .collect(Collectors .toMap((Transportadora::getEmail), Transportadora::clone)); } /** * Metodo que altera as lojas de um conjunto de dados * * @param loj as novas lojas */ public void setLojas(Map<String, Loja> loj) { this.lojas = loj.values().stream() .collect(Collectors .toMap((Loja::getEmail), Loja::clone)); } /** * Metodo que altera as encomendas de um conjunto de dados * * @param al as novas encomendas */ public void setEncomendas(List<Encomenda> al) { this.encomendas = new ArrayList<>(); for (Encomenda a : al) this.encomendas.add(a.clone()); } /** * Metodo que le dados de um ficheiro * * @return Dados do ficheiro lido */ public static Dados abrirFicheiro(String nomeFicheiro) throws IOException, ClassNotFoundException, ClassCastException { Dados d; FileInputStream in = new FileInputStream(new File(nomeFicheiro)); ObjectInputStream o = new ObjectInputStream(in); d = (Dados) o.readObject(); o.close(); in.close(); d.updateEncs(); return d; } /** * Metodo que guarda os dados num ficheiro * * @param nomeFicheiro nome do ficheiro */ public void guardaFicheiro(String nomeFicheiro) throws FileNotFoundException, IOException { FileOutputStream out = new FileOutputStream(new File(nomeFicheiro)); ObjectOutputStream o = new ObjectOutputStream(out); o.writeObject(this); o.flush(); o.close(); out.close(); } /** * Metodo que retorna o utilizador correspondente ao email * * @param email nome do ficheiro * @return utilizador lido */ public Utilizador emailToUser(String email) { Map<String, Utilizador> aux = this.getUtilizadores(); return aux.get(email); } /** * Metodo que retorna o voluntarios correspondente ao email * * @param email nome do ficheiro * @return voluntario lido */ public Voluntario emailToVolu(String email) { Map<String, Voluntario> aux = this.getVoluntarios(); return aux.get(email); } /** * Metodo que retorna a transportadora correspondente ao email * * @param email nome do ficheiro * @return transportadora lida */ public Transportadora emailToTran(String email) { Map<String, Transportadora> aux = this.getTransportadoras(); return aux.get(email); } /** * Metodo que retorna a loja correspondente ao email * * @param email nome do ficheiro * @return loja lida */ public Loja emailToLoja(String email) { Map<String, Loja> aux = this.getLojas(); return aux.get(email); } /** * Metodo que verifica se existe o email * * @param email email a verificar */ public void existeEmail(String email) throws NoEmailException { Utilizador u = this.utilizadores.get(email); if (u != null) return; Voluntario v = this.voluntarios.get(email); if (v != null) return; Transportadora t = this.transportadoras.get(email); if (t != null) return; Loja l = this.lojas.get(email); if (l != null) return; throw new NoEmailException(email); } /** * Metodo que verifica se o email e valido para registar * * @param email email a verificar */ public void isEmail(String email) throws EmailInvalidoException { try { existeEmail(email); } catch (NoEmailException e) { if (!((email.contains(".com") || email.contains(".pt")) && email.contains("@"))) throw new EmailInvalidoException(email); } } /** * Metodo que devolve o codigo do utilizador/voluntario/transportadora/loja dado o seu email * * @param email email do utilizador/voluntario/transportadora/loja * @return codigo obtido */ public String emailToCod(String email) throws NoEmailException { Utilizador u = this.utilizadores.get(email); if (u != null) return u.getCodUser(); Voluntario v = this.voluntarios.get(email); if (v != null) return v.getCodVol(); Transportadora t = this.transportadoras.get(email); if (t != null) return t.getCodTran(); Loja l = this.lojas.get(email); if (l != null) return l.getCodLoja(); throw new NoEmailException(email); } /** * Metodo que retorna o utilizador correspondente ao codigo do utilizador * * @param codUser codigo do utilizador * @return utilizador correspondente */ public Utilizador codUserToU(String codUser) { Utilizador ret = new Utilizador(); for (Utilizador u : utilizadores.values()) if (codUser.equals(u.getCodUser())) { ret = u.clone(); break; } return ret; } /** * Metodo que retorna o voluntario correspondente ao codigo do voluntario * * @param codVolu codigo do voluntario * @return voluntario correspondente */ public Voluntario codVolToV(String codVolu) { Voluntario ret = new Voluntario(); for (Voluntario v : voluntarios.values()) if (codVolu.equals(v.getCodVol())) { ret = v.clone(); break; } return ret; } /** * Metodo que retorna a transportadora correspondente ao codigo da transportadora * * @param codTran codigo da transportadora * @return transportadora correspondente */ public Transportadora codTranToT(String codTran) { Transportadora ret = new Transportadora(); for (Transportadora t : transportadoras.values()) if (codTran.equals(t.getCodTran())) { ret = t.clone(); break; } return ret; } /** * Metodo que retorna a loja correspondente ao codigo da loja * * @param codLoja codigo da loja * @return loja correspondente */ public Loja codLojaToL(String codLoja) { Loja ret = new Loja(); for (Loja l : lojas.values()) if (codLoja.equals(l.getCodLoja())) { ret = l.clone(); break; } return ret; } /** * Metodo que aceita uma encomenda dos logs * * @param codEnc codigo da encomenda */ public void encAceiteLogs(String codEnc) { int max = encomendas.size(); int ind = -1; Encomenda e = new Encomenda(); for (int i = 0; i < max; i++) { e = encomendas.get(i); if (codEnc.equals(e.getCodEnc())) { ind = i; break; } } Loja l = codLojaToL(e.getCodLoja()); int vol = 0; for (Voluntario v : voluntarios.values()) { if (isInRaio(v.getRaio(), v.getGPSX(), v.getGPSY(), l.getGPSX(), l.getGPSY()) && v.getDisp() != 0) { e.setEstado(0); String data = LocalDateTime.now().toString(); e.setData(data); encomendas.set(ind, e); vol = 1; List<Encomenda> encs = v.getEncomendas(); encs.add(e); v.setEncomendas(encs); voluntarios.put(v.getEmail(), v); break; } } int tran = 0; if (vol == 0) { for (Transportadora t : transportadoras.values()) { if (isInRaio(t.getRaio(), t.getGPSX(), t.getGPSY(), l.getGPSX(), l.getGPSY()) && t.getDisp() != 0) { e.setEstado(3); encomendas.set(ind, e); tran = 1; List<Encomenda> encs = t.getEncomendas(); encs.add(e); t.setEncomendas(encs); transportadoras.put(t.getEmail(), t); break; } } } if (tran == 0 && vol == 0) { System.out.println("Impossivel aceitar encomenda " + codEnc + "!\n"); } } /** * Metodo que retorna a distancia entre uma encomenda e um voluntario * * @param e encomenda * @param v voluntario * @return distancia */ public double getDisEncVol(Encomenda e, Voluntario v) { Loja l = codLojaToL(e.getCodLoja()); return distanciaGPS(l.getGPSX(), l.getGPSY(), v.getGPSY(), v.getGPSY()); } /** * Metodo que retorna a distancia entre uma encomenda e uma transportadora * * @param e encomenda * @param t transportadora * @return distancia */ public double getDisEncTran(Encomenda e, Transportadora t) { Loja l = codLojaToL(e.getCodLoja()); return distanciaGPS(l.getGPSX(), l.getGPSY(), t.getGPSY(), t.getGPSY()); } /** * Metodo que verifica se duas passwords coincidirem * * @param password primeira password * @param pass segunda password * @return 0 se coincidirem */ public int passValida(String password, String pass) throws PassInvalidaException { if (password.equals(pass)) return 0; else throw new PassInvalidaException(pass); } /** * Metodo que verifica se um nome e valido * * @param nome nome * @return 0 se for valido */ public int nomeValido(String nome) throws NomeInvalidoException { int i; char c; for (i = 0; i < nome.length(); i++) { c = nome.charAt(i); if (!Character.isLetter(c) && c != ' ') throw new NomeInvalidoException(nome); } return 0; } /** * Metodo que verifica se um nif e valido * * @param nif nif * @return 0 se for valido */ public int nifValido(long nif) throws NifInvalidoException { if (nif <= 999999999 && nif > 99999999) return 0; else throw new NifInvalidoException(); } /** * Metodo que adiciona um utilizador aos dados * * @param u utilizador */ public void addUser(Utilizador u){ utilizadores.put(u.getEmail(), u); } /** * Metodo que adiciona um voluntario aos dados * * @param v voluntario */ public void addVolu(Voluntario v) { voluntarios.put(v.getEmail(), v); } /** * Metodo que adiciona uma transportdora aos dados * * @param t transportadora */ public void addTran(Transportadora t) { transportadoras.put(t.getEmail(), t); } /** * Metodo que adiciona uma loja aos dados * * @param l loja */ public void addLoja(Loja l) { lojas.put(l.getEmail(), l); } /** * Metodo que gera um novo codigo de utilizador * * @return novo codigo */ public String newCodUser() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "u" + aux; done = 0; for (Utilizador u : utilizadores.values()) { if (u.getCodUser().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que gera um novo codigo de voluntario * * @return novo codigo */ public String newCodVolu() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "v" + aux; done = 0; for (Voluntario v : voluntarios.values()) { if (v.getCodVol().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que gera um novo codigo de transportadora * * @return novo codigo */ public String newCodTran() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "t" + aux; done = 0; for (Transportadora t : transportadoras.values()) { if (t.getCodTran().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que gera um novo codigo de loja * * @return novo codigo */ public String newCodLoja() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "l" + aux; done = 0; for (Loja l : lojas.values()) { if (l.getCodLoja().equals(ret)) { aux++; done = 1; break; } } } return ret; } public String newCodEnc() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "e" + aux; done = 0; for(Encomenda e : encomendas) { if(e.getCodEnc().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que calcula as encomendas acessiveis a um Voluntario * * @param v Voluntario em causa * @return lista de encomendas acessiveis */ public List<Encomenda> getEncomendasAcsVol(Voluntario v) { List<Loja> ljs = lojas .values() .stream() .filter(l -> isInRaio(v.getRaio(), v.getGPSX(), v.getGPSY(), l.getGPSX(), l.getGPSY())) .collect(Collectors.toList()); List<Encomenda> ret = new ArrayList<>(); for (Loja l : ljs) { //System.out.println(l); for (Encomenda e : l.getEncomendas()) { // System.out.println(e); if(e.getEstado() == 2) { if(e.isMed()){ if(v.getDisp() == 2) ret.add(e.clone()); }else ret.add(e.clone()); } } } return ret; } /** * Metodo que calcula as encomendas acessiveis a uma transportadora * * @param t Transportadora em causa * @return lista de encomendas acessiveis */ public List<Encomenda> getEncomendasAcsTran(Transportadora t) { List<Loja> ljs = lojas .values() .stream() .filter(l -> isInRaio(t.getRaio(), t.getGPSX(), t.getGPSY(), l.getGPSX(), l.getGPSY())) .collect(Collectors.toList()); List<Encomenda> ret = new ArrayList<>(); for (Loja l : ljs) { //System.out.println(l); for (Encomenda e : l.getEncomendas()) { // System.out.println(e); if(e.getEstado() == 2){ if(e.isMed()){ if(t.getDisp() == 2) ret.add(e.clone()); }else ret.add(e.clone()); } } } return ret; } /** * Metodo no qual uma transportadora escolhe uma encomenda * * @param t transportadora em causa */ public void escolheEncTran(Transportadora t) { ArrayList<String> aux = new ArrayList<>(); List<Encomenda> enc = getEncomendasAcsTran(t); if(enc.size() != 0) { for (Encomenda e : enc) { //System.out.println(e); aux.add(e.getCodEnc() + "(" + ((int) (getDisEncTran(e, t) + 0.5)) + "Km)"); } String[] s = new String[aux.size()]; for (int i = 0; i < aux.size(); i++) { s[i] = aux.get(i); } UInterface ui = new UInterface(s); System.out.println("\n\n\n\n\n\nEscolha encomenda a transportar:"); int op = ui.exec(); if (op != 0) { Encomenda e = enc.get(op - 1).clone(); e.setEstado(3); int ind = 0; for (Encomenda ed : encomendas) { if (e.getCodEnc().equals(ed.getCodEnc())) { break; } ind++; } encomendas.set(ind, e); t.addEncomenda(e); transportadoras.put(t.getEmail(), t.clone()); updateEncs(); System.out.println("Encomenda selecionada!\n"); } }else System.out.println("\nNao existem encomendas disponiveis!"); } public String geraDataVol(Voluntario v, Loja l, Utilizador u){ List<String> listMet = new ArrayList<>(); listMet.add("Sol"); listMet.add("Nublado"); listMet.add("Chuva"); listMet.add("Nevoeiro"); listMet.add("Tempestade"); Random rand = new Random(); String meteo = listMet.get(rand.nextInt(listMet.size())); double dist = getDistTotalVol(v,l,u); double vel = 0; if(meteo.equals("Sol")) vel = 110; if(meteo.equals("Nublado")) vel = 90; if(meteo.equals("Chuva")) vel = 70; if(meteo.equals("Nevoeiro")) vel = 60; if(meteo.equals("Tempestade")) vel = 30; double tempo = dist/vel; int minutos = (int) tempo*60; LocalDateTime now = LocalDateTime.now().plusMinutes(minutos); return now.toString(); } public String geraDataTran(Transportadora t, Loja l, Utilizador u){ List<String> listMet = new ArrayList<>(); listMet.add("Sol"); listMet.add("Nublado"); listMet.add("Chuva"); listMet.add("Nevoeiro"); listMet.add("Tempestade"); Random rand = new Random(); String meteo = listMet.get(rand.nextInt(listMet.size())); double dist = getDistTotalTran(t,l,u); double vel = 0; if(meteo.equals("Sol")) vel = 110; if(meteo.equals("Nublado")) vel = 90; if(meteo.equals("Chuva")) vel = 70; if(meteo.equals("Nevoeiro")) vel = 60; if(meteo.equals("Tempestade")) vel = 30; double tempo = dist/vel; int minutos = (int) tempo*60; LocalDateTime now = LocalDateTime.now().plusMinutes(minutos); return now.toString(); } /** * Metodo no qual um voluntario escolhe uma encomenda * * @param v voluntario em causa */ public void escolheEncVol(Voluntario v) { ArrayList<String> aux = new ArrayList<>(); List<Encomenda> enc = getEncomendasAcsVol(v); if(enc.size() != 0) { for (Encomenda e : enc){ aux.add(e.getCodEnc() + "(" + ((int) (getDisEncVol(e, v) + 0.5)) + "Km)"); } String[] s = new String[aux.size()]; for (int i = 0; i < aux.size(); i++) { s[i] = aux.get(i); } UInterface ui = new UInterface(s); System.out.println("\n\n\n\n\n\nEscolha encomenda a transportar:"); int op = ui.exec(); if(op != 0) { Encomenda e = enc.get(op - 1).clone(); e.setEstado(0); Loja l = codLojaToL(e.getCodLoja()); Utilizador u = codUserToU(e.getCodUser()); String data = geraDataVol(v,l,u); e.setData(data); LocalDateTime ldt = LocalDateTime.parse(data); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT); System.out.println("Chegada ao utilizador as: " + ldt.format(formatter)); int ind = 0; for (Encomenda ed : encomendas) { if (e.getCodEnc().equals(ed.getCodEnc())) { break; } ind++; } encomendas.set(ind, e); v.addEncomenda(e); voluntarios.put(v.getEmail(), v.clone()); updateEncs(); System.out.println("Encomenda entregue!\n"); } }else System.out.println("\nNao existem encomendas disponiveis!"); } /** * Metodo que da update a todos os objetos necessarios consoante a lista de encomendas */ public void updateEncs() { for (Voluntario v : voluntarios.values()) updateEncsVol(v); for (Transportadora t : transportadoras.values()) updateEncsTran(t); for (Utilizador u : utilizadores.values()) updateEncsUser(u); for (Loja l : lojas.values()) updateEncsLoja(l); } /** * Metodo que da update a todos os voluntarios consoante a lista de encomendas */ public void updateEncsVol(Voluntario v) { List<Encomenda> encV = v.getEncomendas(); for (Encomenda e : encomendas) { int ind2 = 0; for (Encomenda en : encV) { if (e.getCodEnc().equals(en.getCodEnc())) { encV.set(ind2, e.clone()); v.setEncomendas(encV); voluntarios.put(v.getEmail(), v.clone()); //System.out.println("++++++++++++++++++++++\n" + v); } ind2++; } } } /** * Metodo que da update a todos os utilizadores consoante a lista de encomendas */ public void updateEncsUser(Utilizador u) { List<Encomenda> encU = u.getEncomendas(); for (Encomenda e : encomendas) { int ind = 0; for (Encomenda en : encU) { if(e.getCodEnc().equals(en.getCodEnc())) { encU.set(ind, e.clone()); u.setEncomendas(encU); utilizadores.put(u.getEmail(), u.clone()); //System.out.println("++++++++++++++++++++++\n" + u); } ind++; } } } /** * Metodo que da update a todas as transportadoras consoante a lista de encomendas */ public void updateEncsTran(Transportadora t) { List<Encomenda> encT = t.getEncomendas(); for (Encomenda e : encomendas) { int ind = 0; for (Encomenda en : encT) { if (e.getCodEnc().equals(en.getCodEnc())) { encT.set(ind, e.clone()); t.setEncomendas(encT); transportadoras.put(t.getEmail(), t.clone()); //System.out.println("++++++++++++++++++++++\n" + t); } ind++; } } } /** * Metodo que da update a todas as lojas consoante a lista de encomendas */ public void updateEncsLoja(Loja l) { List<Encomenda> encL = l.getEncomendas(); for (Encomenda e : encomendas) { int ind = 0; for (Encomenda en : encL) { if (e.getCodEnc().equals(en.getCodEnc())) { encL.set(ind, e.clone()); l.setEncomendas(encL); lojas.put(l.getEmail(), l.clone()); //System.out.println("++++++++++++++++++++++\n" + l); } ind++; } } } public void isCodProd(String codProd) throws CodProdInvalidoException{ if(codProd.charAt(0) != 'p') throw new CodProdInvalidoException(codProd); for(int i = 1; i < codProd.length(); i++) if(!isDigit(codProd.charAt(i)) || 3 < i ) throw new CodProdInvalidoException(codProd); } public ArrayList<LinhaEncomenda> criarProdutos(){ int op = 1; ArrayList<LinhaEncomenda> ret= new ArrayList<>(); String codProd = null; String desc = null; double qntd = 0.0; double valuni = 0.0; while(op != 0){ LinhaEncomenda le = new LinhaEncomenda(); int val = 1; Scanner in = new Scanner(System.in); while(val != 0){ System.out.println("Insira codigo do produto (pXX)"); codProd = in.nextLine(); try{ isCodProd(codProd); val = 0; }catch(CodProdInvalidoException e){ System.out.println("Valor invalido"); val = 1; } } val = 1; while(val != 0){ System.out.println("Insira descricao do produto"); desc = in.nextLine(); try{ nomeValido(desc); val = 0; }catch(NomeInvalidoException e){ System.out.println("Valor invalido"); val = 1; } } val = 1; while(val != 0){ System.out.println("Insira a quantidade"); try{ qntd = in.nextDouble(); val = 0; }catch(InputMismatchException e){ System.out.println("Valor invalido"); val = 1; } } val = 1; while(val != 0){ System.out.println("Insira o valor unitario"); valuni = -1; try{ valuni = in.nextInt(); val = 0; }catch(InputMismatchException e){ System.out.println("Valor invalido"); val = 1; } } le.setCodProduto(codProd); le.setDescricao(desc); le.setQuantidade(qntd); le.setValorUni(valuni); ret.add(le.clone()); val = 1; int insmais = -1; while(val != 0){ System.out.println("Inserir mais produtos?\n(0 - NAO) (1 - SIM)"); try{ insmais = in.nextInt(); val = 0; }catch (InputMismatchException e){ System.out.println("Valor invalido"); val = 1; } } op = insmais; } return ret; } public void criarEncomenda(String codUser){ Encomenda e = new Encomenda(); e.setCodUser(codUser); int op = 1; Scanner inp = new Scanner(System.in); while(op != 0){ System.out.println("(0 - Sair)\nInsira codigo da loja: "); String in = inp.nextLine(); try { if (Integer.parseInt(in) == 0) return; }catch (NumberFormatException ignored){} Loja l = codLojaToL(in); if(l.getEmail() == null) System.out.println("Loja inexistente"); else{ e.setCodLoja(in); op = 0; } } op = 1; while(op != 0) { System.out.println("(0 - Sair)\nInsira o peso da encomenda: "); double in; try { in = inp.nextInt(); if (in == 0) return; op = 0; e.setPeso((double)in); } catch (Exception ex) { System.out.println("Valor invalido!"); op = 1; } } op = 1; System.out.println("\nEncomenda medica? (0 - SIM)"); double in = -1; try{in = inp.nextInt();}catch (InputMismatchException ignored) {} if(in == 0)e.setMed(true); else e.setMed(false); e.setEstado(1); e.setCodEnc(newCodEnc()); e.setProdutos(criarProdutos()); encomendas.add(e); updateEncs(); } /** * Metodo que informa o sistema que uma encomenda de uma loja esta pronta * * @param l loja em causa */ public void reqEntrega(Loja l) { List<Encomenda> enc = l.getEncomendasEstado(1); if (enc.size() != 0){ String[] encs = new String[enc.size()]; int i = 0; for (Encomenda e : enc) { //System.out.println(e); encs[i] = e.getCodEnc(); i++; } UInterface ui = new UInterface(encs); int op = ui.exec(); if (op == 0) return; Encomenda es = enc.get(op - 1); es.setEstado(2); int indd = 0; for (Encomenda e : encomendas) { if (es.getCodEnc().equals(e.getCodEnc())) break; indd++; } encomendas.set(indd, es.clone()); System.out.println("\nEncomenda disponibilizada com pronta para entrega!\n"); //System.out.println("abcd"); } else System.out.println("\nNao ha encomendas pendentes!\n"); updateEncs(); } public void veAvaliacoes(String codVolTran){ int vol = 0; Voluntario v = codVolToV(codVolTran); Transportadora t = codTranToT(codVolTran); if(v.getEmail()==null){ vol = 1;} List<Encomenda> encs = new ArrayList<>(); if(vol == 0){ encs = v.getEncomendasEstado(0);} else{encs = t.getEncomendasEstado(0);} Map<String, Double> classif = new TreeMap<>(); for(String codE : classificacoes.keySet()){ for(Encomenda e : encs){ if(codE.equals(e.getCodEnc())){ classif.put(codE, classificacoes.get(codE)); } } } double size = classif.size(); if(size == 0) System.out.println("Nao existem classificacoes!"); else{ double media = 0; for(String e : classif.keySet()){ Double d = classif.get(e); System.out.println("Encomenda " + e + " obteve classificacao de " + d); media += d; } media = media/size; System.out.println("Media: " + media); } } public void avaliaEncomenda(String codUser){ Utilizador u = codUserToU(codUser); List<Encomenda> encs = u.getEncomendasEstado(0); for(Encomenda e : encs){ for(String s : classificacoes.keySet()){ if(s.equals(e.getCodEnc())){ encs.remove(e); } } } int i = 0; String[] str = new String[encs.size()]; System.out.println("Escolha encomenda a avaliar:"); for(Encomenda e : encs){ str[i] = ("Encomenda " + e.getCodEnc() + " da loja " + e.getCodLoja()); i++; } UInterface ui = new UInterface(str); int op = ui.exec(); if(op != 0){ Encomenda e = encs.get(op-1); System.out.println("Avalie a encomenda "+ e.getCodEnc() + " (0-5):"); Scanner ss = new Scanner(System.in); double avaliacao = 0.0; int val = 1; while(val!=0) { try { avaliacao = ss.nextInt(); if(avaliacao > 5.0) avaliacao = 5.0; val = 0; } catch (InputMismatchException g) { System.out.print("Valor inválido!"); val = 1; } } classificacoes.put(e.getCodEnc(),avaliacao); System.out.println("Encomenda avaliada com sucesso!\n\n" + avaliacao); } } /** * Metodo imprime o historico de encomendas de um objeto do tipo utilizador, voluntario, transportadora, loja * * @param o objeto em questao */ public void histEncomendas(Object o){ List <Encomenda> encomendas = new ArrayList<>(); if(o instanceof Utilizador){ Utilizador u = (Utilizador) o; encomendas = u.getEncomendasEstado(0); } if(o instanceof Voluntario){ Voluntario v = (Voluntario) o; encomendas = v.getEncomendasEstado(0); } if(o instanceof Transportadora){ Transportadora t = (Transportadora) o; encomendas = t.getEncomendasEstado(0); } if(o instanceof Loja){ Loja l = (Loja) o; encomendas = l.getEncomendasEstado(0); } Scanner input = new Scanner(System.in); int inp = 1; int op = 0; if(encomendas.size() != 0) { while (inp != 0) { System.out.println("(0) - Por data\n(1) - Todas"); try { op = input.nextInt(); inp = 0; } catch (InputMismatchException e) { System.out.println("Valor invalido!"); inp = 1; } } if (op == 0) { input.nextLine(); int val = 1; LocalDateTime date1 = null; LocalDateTime date2 = null; while (val != 0) { System.out.print("\n(aaaa-mm-dd)\nEntre a data: \n"); String dateString = input.nextLine(); dateString += "T00:00:00"; try { date1 = LocalDateTime.parse(dateString); val = 0; } catch (DateTimeParseException e) { System.out.println("Data invalida!"); val = 1; } } val = 1; while (val != 0) { System.out.print("e a data :"); String dateString = input.nextLine(); dateString += "T00:00:00"; try { date2 = LocalDateTime.parse(dateString); val = 0; } catch (DateTimeParseException e) { System.out.println("Data invalida!"); val = 1; } } List<Encomenda> encomendasInData = new ArrayList<>(); LocalDateTime dataEnc; for (Encomenda e : encomendas) { if (e.getData() != null) { dataEnc = LocalDateTime.parse(e.getData()); if (dataEnc.isAfter(date1) && dataEnc.isBefore(date2)) encomendasInData.add(e); } } int arrSize = encomendasInData.size(); if (arrSize != 0) { System.out.println("Encomendas:"); for (Encomenda e : encomendasInData) System.out.println("-" + e.getCodEnc() + " (" + e.getDataPrint() + ")"); } else System.out.println("\nNao existem encomendas terminadas nestas datas!\n"); } else { System.out.println("Encomendas:"); for (Encomenda e : encomendas) { System.out.println("-" + e.getCodEnc() + " (" + e.getDataPrint() + ")"); } } }else{ System.out.println("\nNao existem encomendas terminadas!\n"); } System.out.println(""); } /** * Metodo que povoa alguns dados apos o import de logs */ public void povoaDados() { for (Encomenda e : encomendas) { Utilizador u = codUserToU(e.getCodUser()); int ind1 = 0; int indU = -1; for (Encomenda en : u.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encU = u.getEncomendas(); encU.set(ind1, e.clone()); u.setEncomendas(encU); utilizadores.put(u.getEmail(), u.clone()); //System.out.println("++++++++++++++++++++++\n" + u); indU = ind1; } ind1++; } if (indU == -1) { List<Encomenda> encU = u.getEncomendas(); encU.add(e.clone()); u.setEncomendas(encU); utilizadores.put(u.getEmail(), u); } Voluntario v = codVolToV(e.getCodUser()); int ind2 = 0; for (Encomenda en : v.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encV = v.getEncomendas(); encV.set(ind2, e.clone()); v.setEncomendas(encV); voluntarios.put(v.getEmail(), v.clone()); //System.out.println("++++++++++++++++++++++\n" + v); } ind2++; } Transportadora t = codTranToT(e.getCodUser()); int ind3 = 0; for (Encomenda en : t.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encT = t.getEncomendas(); encT.set(ind3, e.clone()); t.setEncomendas(encT); transportadoras.put(t.getEmail(), t.clone()); //System.out.println("++++++++++++++++++++++\n" + t); } ind3++; } Loja l = codLojaToL(e.getCodLoja()); int ind4 = 0; int indL = -1; for (Encomenda en : l.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encL = l.getEncomendas(); encL.set(ind4, e.clone()); l.setEncomendas(encL); lojas.put(l.getEmail(), l); indL = ind4; } ind4++; } if (indL == -1) { List<Encomenda> encL = l.getEncomendas(); ; encL.add(e.clone()); l.setEncomendas(encL); lojas.put(l.getEmail(), l); } } } /** * Metodo que faz parse dos logs para a estrutura dados * * @param file ficheiro de logs */ public void parse(String file) { int pov = 0; List<String> linhas = lerFicheiro(file); //alterar nome do ficheiro String[] linhaPartida; for (String linha : linhas) { linhaPartida = linha.split(":", 2); switch (linhaPartida[0]) { case "Utilizador": Utilizador u = parseUtilizador(linhaPartida[1]); // criar um Utilizador //System.out.println(u.toString()); //enviar para o ecra apenas para teste utilizadores.put(u.getEmail(), u); break; case "Loja": Loja l = parseLoja(linhaPartida[1]); //System.out.println(l.toString()); lojas.put(l.getEmail(), l); break; case "Voluntario": Voluntario v = parseVoluntario(linhaPartida[1]); voluntarios.put(v.getEmail(), v); //System.out.println(v.toString()); povoaDados(); break; case "Transportadora": Transportadora t = parseTransportadora(linhaPartida[1]); transportadoras.put(t.getEmail(), t); //System.out.println(t.toString()); break; case "Encomenda": Encomenda e = parseEncomenda(linhaPartida[1]); //System.out.println(e.toString()); encomendas.add(e); break; case "Aceite": if (pov == 0) povoaDados(); encAceiteLogs(linhaPartida[1]); pov = 1; break; default: System.out.println("Linha invalida."); break; } } updateEncs(); System.out.println("\n\n\n\nLogs importados com sucesso!\n"); } /** * Metodo que faz parse de uma linha de logs correspondente a um utilizador * * @param input linha de logs * @return utilizador obtido */ public Utilizador parseUtilizador(String input) { Utilizador u = new Utilizador(); String[] campos = input.split(","); String codUtilizador = campos[0]; String nome = campos[1]; double gpsX = Double.parseDouble(campos[2]); double gpsY = Double.parseDouble(campos[3]); String password = nome.replace(" ", "").toLowerCase(); String email = password + "@gmail.com"; u.setCodUser(codUtilizador); u.setNome(nome); u.setGPS(gpsX, gpsY); u.setEmail(email); u.setPassword(password); return u; } /** * Metodo que faz parse de uma linha de logs correspondente a um voluntario * * @param input linha de logs * @return voluntario obtido */ public Voluntario parseVoluntario(String input) { Voluntario v = new Voluntario(); String[] campos = input.split(","); String codVol = campos[0]; String nome = campos[1]; double gpsX = Double.parseDouble(campos[2]); double gpsY = Double.parseDouble(campos[3]); double raio = Double.parseDouble(campos[4]); String password = nome.replace(" ", "").toLowerCase(); String email = password + "@gmail.com"; v.setCodVol(codVol); v.setNome(nome); v.setGPS(gpsX, gpsY); v.setEmail(email); v.setPassword(password); v.setRaio(raio); return v; } /** * Metodo que faz parse de uma linha de logs correspondente a uma transportadora * * @param input linha de logs * @return transportadora obtida */ public Transportadora parseTransportadora(String input) { Transportadora t = new Transportadora(); String[] campos = input.split(","); String codTran = campos[0]; String nome = campos[1]; double gpsX = Double.parseDouble(campos[2]); double gpsY = Double.parseDouble(campos[3]); long nif = Long.parseLong(campos[4]); double raio = Double.parseDouble(campos[5]); double precokm = Double.parseDouble(campos[6]); String password = nome.replace(" ", "").toLowerCase(); String email = password + "@gmail.com"; t.setCodTran(codTran); t.setNome(nome); t.setGPS(gpsX, gpsY); t.setNIF(nif); t.setRaio(raio); t.setPrecoKM(precokm); t.setEmail(email); t.setPassword(password); return t; } /** * Metodo que faz parse de uma linha de logs correspondente a uma loja * * @param input linha de logs * @return loja obtida */ public Loja parseLoja(String input) { double x = ThreadLocalRandom.current().nextDouble(-100, 100); double y = ThreadLocalRandom.current().nextDouble(-100, 100); Loja l = new Loja(); String[] campos = input.split(","); String codLoja = campos[0]; String nome = campos[1]; String password = nome.replace(" ", "").toLowerCase(); String email = password + "@gmail.com"; l.setCodLoja(codLoja); l.setnome(nome); l.setGPS(x, y); l.setEmail(email); l.setPassword(password); return l; } /** * Metodo que faz parse de uma linha de logs correspondente a uma lista de produtos * * @param input linha de logs * @return lista de produtos obtida */ public ArrayList<LinhaEncomenda> parseProdutos(String input) { String[] campos = input.split(","); ArrayList<LinhaEncomenda> produtos = new ArrayList<>(); int camposLength = campos.length; int done = 0; for (int i = 0; done != 1; i += 4) { LinhaEncomenda le = new LinhaEncomenda(); String codProduto = campos[i]; String descricao = campos[i + 1]; double quantidade = Double.parseDouble(campos[i + 2]); double valorUni = Double.parseDouble(campos[i + 3]); le.setCodProduto(codProduto); le.setDescricao(descricao); le.setQuantidade(quantidade); le.setValorUni(valorUni); produtos.add(le); if (i + 4 >= camposLength) done = 1; } return produtos; } /** * Metodo que faz parse de uma linha de logs correspondente a uma encomenda * * @param input linha de logs * @return encomenda obtida */ public Encomenda parseEncomenda(String input) { Encomenda e = new Encomenda(); String[] campos = input.split(",", 5); String codEnc = campos[0]; String codUser = campos[1]; String codLoja = campos[2]; double peso = Double.parseDouble(campos[3]); ArrayList<LinhaEncomenda> produtos = parseProdutos(campos[4]); e.setCodEnc(codEnc); e.setCodUser(codUser); e.setCodLoja(codLoja); e.setPeso(peso); e.setProdutos(produtos); return e; } /** * Metodo le todas as linhas de um ficheiro * * @param nomeFich nome do ficheiro * @return linhas obtidas */ public List<String> lerFicheiro(String nomeFich) { List<String> lines = new ArrayList<>(); try { lines = Files.readAllLines(Paths.get(nomeFich), StandardCharsets.UTF_8); } catch (IOException exc) { System.out.println(exc.getMessage()); } return lines; } /** * Metodo que calcula a distancia entre duas entidades * * @param gpsX1 coordenada x da primeira entidade * @param gpsY1 coordenada y da primeira entidade * @param gpsX2 coordenada x da segunda entidade * @param gpsY2 coordenada y da segunda entidade * @return distancia */ public static double distanciaGPS(double gpsX1, double gpsY1, double gpsX2, double gpsY2) { return Math.sqrt(Math.pow((gpsX2 - gpsX1 + gpsY2 - gpsY1), 2.0)); } /** * Metodo que calcula se uma entidade se encontra no raio de outra * * @param raio raio * @param gpsX1 coordenada x da primeira entidade * @param gpsY1 coordenada y da primeira entidade * @param gpsX2 coordenada x da segunda entidade * @param gpsY2 coordenada y da segunda entidade * @return true se estiver, false se nao estiver */ public static boolean isInRaio(double raio, double gpsX1, double gpsY1, double gpsX2, double gpsY2) { return distanciaGPS(gpsX1, gpsY1, gpsX2, gpsY2) <= raio; } /** * Metodo que verifica se existe uma resposta pendente de um utilizador * * @param u utilizador em causa * @return true se existir, false se nao existir */ public boolean existeRespPend(Utilizador u){ List<Encomenda> aux = u.getEncomendasEstado(3); return aux.size() != 0; } public Transportadora getTranEnc(String codEnc){ for(Transportadora t : transportadoras.values()){ List<Encomenda> aux = t.getEncomendas(); for(Encomenda e : aux){ if(e.getCodEnc().equals(codEnc)) return t.clone(); } } return null; } public double getDistTotalTran(Transportadora t, Loja l, Utilizador u){ return distanciaGPS(t.getGPSX(),t.getGPSY(),l.getGPSX(),l.getGPSY()) + distanciaGPS(l.getGPSX(),l.getGPSY(),u.getGPSX(),u.getGPSY()); } public double getDistTotalVol(Voluntario v, Loja l, Utilizador u){ return distanciaGPS(v.getGPSX(),v.getGPSY(),l.getGPSX(),l.getGPSY()) + distanciaGPS(l.getGPSX(),l.getGPSY(),u.getGPSX(),u.getGPSY()); } public double getPreco(double peso, Transportadora t, Loja l, Utilizador u){ double custoKM = t.getPrecoKM(); return (peso/1.5)*(getDistTotalTran(t,l,u)*custoKM); } /** * Metodo que gere uma resposta pendesnte de um utilizador * * @param u utilizador em causa */ public void gereRespPend(Utilizador u){ List<Encomenda> aux = u.getEncomendasEstado(3); for(Encomenda e : aux){ Transportadora t = getTranEnc(e.getCodEnc()); Loja l = codLojaToL(e.getCodLoja()); double precoD = getPreco(e.getPeso(),t,l,u); String preco = String.format("%.02d", precoD); System.out.println("Encomenda: " + e.getCodEnc() + "\nTransportadora: " + t.getCodTran() + "\nPreco esperado: " + preco); System.out.println("(0) - Recusar\n(1) - Aceitar"); int op = 0; int inp = 1; Scanner s = new Scanner(System.in); while(inp != 0) { try{ op = s.nextInt(); inp = 0; }catch(InputMismatchException i) { System.out.println("Valor invalido!"); inp = 1; } } if(op == 0){ List<Encomenda> auxt = t.getEncomendas(); auxt.remove(e); t.setEncomendas(auxt); transportadoras.put(t.getEmail(),t.clone()); e.setEstado(2); }else{ e.setEstado(0); e.setData(geraDataTran(t,l,u)); e.setPrecoEntrega(precoD); } int ind = 0; for(Encomenda ed : encomendas){ if(e.getCodEnc().equals(ed.getCodEnc())){ break; } ind++; } encomendas.set(ind,e.clone()); updateEncs(); } } public void totFatTrans(){ List<Transportadora> trans = new ArrayList<>(transportadoras.values()); String[] str = new String[trans.size()]; int ind = 0; for(Transportadora t : trans){ str[ind] = t.getCodTran(); ind++; } while(true){ UInterface ui = new UInterface(str); int op = ui.exec(); if(op != 0){ Transportadora tp = trans.get(op-1); System.out.println("Total faturado pela transportadora " + tp.getCodTran() + " e: " + totFatTran(tp) + "€"); }else break; } } public double totFatTran(Transportadora t){ double total = 0; List<Encomenda> encs = t.getEncomendas(); for(Encomenda e : encs){ if(e.getEstado() == 0) total += e.getPrecoEntrega(); } return total; } public void dezUsrMaisUsaram(){ List<Utilizador> usrs = new ArrayList<>(utilizadores.values()); usrs.sort(UserComparator); int i = 1; for(Utilizador u : usrs){ if(i > 10) break; System.out.println(i + " - " + u.getNome() + "(" + u.getEncomendasEstado(0).size() + " Encomendas)"); i++; } System.out.println("\n"); } public void dezTranMaisUsaram(){ Map<Double, Transportadora> mapTran = new TreeMap<>(); for(Transportadora t : transportadoras.values()){ System.out.println(getKmDone(t)); double kmd = getKmDone(t); while(mapTran.containsKey(kmd)){ kmd += 0.00001; } mapTran.put(kmd,t.clone()); } List<Double> sortedKeys = new ArrayList<>(mapTran.keySet()); sortedKeys.sort(Collections.reverseOrder()); List<Transportadora> trans = new ArrayList<>(); for(Double d : sortedKeys){ trans.add(mapTran.get(d)); } int i = 1; for(Transportadora t : trans){ if(i > 10) break; System.out.println(i + " - " + t.getNome() + "(" + getKmDone(t) + " KM)"); i++; } System.out.println("\n"); } public void verPerfilTran(Transportadora o){ int opcao = -1; while(opcao != 0){ System.out.print(o.toString()); System.out.print("\n(1) - Ficar indisponivel" + "\n(2) - Ficar disponivel" + "\n(3) - Ficar disponivel para encomendas medicas" + "\n(0) - Sair\n"); Scanner input = new Scanner(System.in); try{ opcao = input.nextInt(); } catch(InputMismatchException e){ // Não foi escolhido um inteiro opcao = -1; } if(opcao < 0 || opcao > 3){ System.out.println("Valor Inválido!"); opcao = -1; } if(opcao == 1){ o.setDisp(0); } if(opcao == 2){ o.setDisp(1); } if(opcao == 3){ o.setDisp(2); } } transportadoras.put(o.getEmail(),o.clone()); } public void verPerfilVol(Voluntario o){ int opcao = -1; while(opcao != 0){ System.out.print(o.toString()); System.out.print("\n(1) - Ficar indisponivel" + "\n(2) - Ficar disponivel" + "\n(3) - Ficar disponivel para encomendas medicas" + "\n(0) - Sair\n"); Scanner input = new Scanner(System.in); try{ opcao = input.nextInt(); } catch(InputMismatchException e){ // Não foi escolhido um inteiro opcao = -1; } if(opcao < 0 || opcao > 3){ System.out.println("Valor Inválido!"); opcao = -1; } if(opcao == 1){ o.setDisp(0); } if(opcao == 2){ o.setDisp(1); } if(opcao == 3){ o.setDisp(2); } } voluntarios.put(o.getEmail(),o.clone()); } public double getKmDone(Transportadora t){ List<Encomenda> encsT = t.getEncomendasEstado(0); double kms = 0; for(Encomenda e : encsT){ if(e.getEstado() == 0) { Utilizador u = codUserToU(e.getCodUser()); Loja l = codLojaToL(e.getCodLoja()); kms += getPreco(e.getPeso(),t, l, u); } } return kms; } public List<Encomenda> encAccessiveisVol(Voluntario v) { List<Encomenda> ret = new ArrayList<>(); for (Loja lj : lojas.values()) { if (isInRaio(v.getRaio(), v.getGPSX(), v.getGPSY(), lj.getGPSX(), lj.getGPSY())) ret = lj.getEncomendas(); } return ret; } public List<Encomenda> encAccessiveisTra(Transportadora t) { List<Encomenda> ret = new ArrayList<>(); for (Loja lj : lojas.values()) { if (isInRaio(t.getRaio(), t.getGPSX(), t.getGPSY(), lj.getGPSX(), lj.getGPSY())) ret = lj.getEncomendas(); } return ret; } public static Comparator<Utilizador> UserComparator = new Comparator<Utilizador>(){ public int compare(Utilizador u1, Utilizador u2) { int nEncsu1 = u1.getEncomendasEstado(0).size(); int nEncsu2 = u2.getEncomendasEstado(0).size(); return nEncsu2 - nEncsu1; } }; }
UTF-8
Java
62,159
java
Dados.java
Java
[ { "context": " encomendas existentes no sistema.\n *\n * @author (Eduardo Araujo, Ricardo Machado, Guilherme Araujo)\n * @version 1", "end": 653, "score": 0.9998712539672852, "start": 639, "tag": "NAME", "value": "Eduardo Araujo" }, { "context": "stentes no sistema.\n *\n * @author (...
null
[]
import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.*; import java.lang.*; import java.io.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; import static java.lang.Character.isDigit; /** * Dados - Registo com todos os utilizadores, voluntarios, transportadoras, lojas e encomendas existentes no sistema. * * @author (<NAME>, <NAME>, <NAME>) * @version 11/06/2020 */ public class Dados implements Serializable { private Map<String, Utilizador> utilizadores; //email,User private Map<String, Voluntario> voluntarios; private Map<String, Transportadora> transportadoras; private Map<String, Loja> lojas; private Map<String, Double> classificacoes; //codEnc,Score private List<Encomenda> encomendas; /** * Construtor para objetos da classe Dados (por omissao) */ public Dados() { this.utilizadores = new HashMap<>(); this.voluntarios = new HashMap<>(); this.transportadoras = new HashMap<>(); this.lojas = new HashMap<>(); this.classificacoes = new HashMap<>(); this.encomendas = new ArrayList<>(); } /** * Construtor para objetos da classe Dados (parameterizado) * * @param user os utilizadores * @param volu os voluntarios * @param tran as transportadoras * @param loja as lojas * @param encomendas as encomendas */ public Dados(Map<String, Utilizador> user, Map<String, Voluntario> volu, Map<String, Transportadora> tran, Map<String, Loja> loja, Map<String, Double> classificacoes, List<Encomenda> encomendas) { this.setUtilizadores(user); this.setVoluntarios(volu); this.setTransportadoras(tran); this.setLojas(loja); this.setEncomendas(encomendas); this.setClassificacoes(classificacoes); } /** * Construtor para objetos da classe Dados (de copia) * * @param d os dados */ public Dados(Dados d) { this.utilizadores = d.getUtilizadores(); this.voluntarios = d.getVoluntarios(); this.transportadoras = d.getTransportadoras(); this.lojas = d.getLojas(); this.classificacoes = d.getClassificacoes(); List<Encomenda> encomendasClone = new ArrayList<>(); for (Encomenda e : d.encomendas) { encomendasClone.add(e.clone()); } this.encomendas = encomendasClone; } /** * Metodo que devolve os utilizadores de um conjunto de dados * * @return os utilizadores dos dados */ public Map<String, Utilizador> getUtilizadores() { Map<String, Utilizador> aux = new HashMap<>(); for (String em : this.utilizadores.keySet()) { Utilizador c = this.utilizadores.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve os voluntarios de um conjunto de dados * * @return os voluntarios dos dados */ public Map<String, Voluntario> getVoluntarios() { Map<String, Voluntario> aux = new HashMap<>(); for (String em : this.voluntarios.keySet()) { Voluntario c = this.voluntarios.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve as transportadoras de um conjunto de dados * * @return as transportadoras dos dados */ public Map<String, Transportadora> getTransportadoras() { Map<String, Transportadora> aux = new HashMap<>(); for (String em : this.transportadoras.keySet()) { Transportadora c = this.transportadoras.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve as lojas de um conjunto de dados * * @return as lojas dos dados */ public Map<String, Loja> getLojas() { Map<String, Loja> aux = new HashMap<>(); for (String em : this.lojas.keySet()) { Loja c = this.lojas.get(em); aux.put(em, c.clone()); } return aux; } /** * Metodo que devolve as classificacoes de um conjunto de dados * * @return as classificacoes dos dados */ public Map<String, Double> getClassificacoes() { Map<String, Double> aux = new HashMap<>(); for (String em : this.classificacoes.keySet()) { Double c = this.classificacoes.get(em); aux.put(em, c); } return aux; } /** * Metodo que devolve as encomendas de um conjunto de dados * * @return as encomendas dos dados */ public List<Encomenda> getEncomendas() { List<Encomenda> aux = new ArrayList<>(); for (Encomenda a : this.encomendas) aux.add(a.clone()); return aux; } /** * Metodo que altera os utilizadores de um conjunto de dados * * @param usr os novos utilizadores */ public void setUtilizadores(Map<String, Utilizador> usr) { this.utilizadores = usr.values().stream() .collect(Collectors .toMap((Utilizador::getEmail), Utilizador::clone)); } public void setClassificacoes(Map<String, Double> cla) { for(String s : cla.keySet()){ classificacoes.put(s,cla.get(s)); } } /** * Metodo que altera os voluntarios de um conjunto de dados * * @param vol os novos voluntarios */ public void setVoluntarios(Map<String, Voluntario> vol) { this.voluntarios = vol.values().stream() .collect(Collectors .toMap((Voluntario::getEmail), Voluntario::clone)); } /** * Metodo que altera as trasnportadoras de um conjunto de dados * * @param tra as novas transportadoras */ public void setTransportadoras(Map<String, Transportadora> tra) { this.transportadoras = tra.values().stream() .collect(Collectors .toMap((Transportadora::getEmail), Transportadora::clone)); } /** * Metodo que altera as lojas de um conjunto de dados * * @param loj as novas lojas */ public void setLojas(Map<String, Loja> loj) { this.lojas = loj.values().stream() .collect(Collectors .toMap((Loja::getEmail), Loja::clone)); } /** * Metodo que altera as encomendas de um conjunto de dados * * @param al as novas encomendas */ public void setEncomendas(List<Encomenda> al) { this.encomendas = new ArrayList<>(); for (Encomenda a : al) this.encomendas.add(a.clone()); } /** * Metodo que le dados de um ficheiro * * @return Dados do ficheiro lido */ public static Dados abrirFicheiro(String nomeFicheiro) throws IOException, ClassNotFoundException, ClassCastException { Dados d; FileInputStream in = new FileInputStream(new File(nomeFicheiro)); ObjectInputStream o = new ObjectInputStream(in); d = (Dados) o.readObject(); o.close(); in.close(); d.updateEncs(); return d; } /** * Metodo que guarda os dados num ficheiro * * @param nomeFicheiro nome do ficheiro */ public void guardaFicheiro(String nomeFicheiro) throws FileNotFoundException, IOException { FileOutputStream out = new FileOutputStream(new File(nomeFicheiro)); ObjectOutputStream o = new ObjectOutputStream(out); o.writeObject(this); o.flush(); o.close(); out.close(); } /** * Metodo que retorna o utilizador correspondente ao email * * @param email nome do ficheiro * @return utilizador lido */ public Utilizador emailToUser(String email) { Map<String, Utilizador> aux = this.getUtilizadores(); return aux.get(email); } /** * Metodo que retorna o voluntarios correspondente ao email * * @param email nome do ficheiro * @return voluntario lido */ public Voluntario emailToVolu(String email) { Map<String, Voluntario> aux = this.getVoluntarios(); return aux.get(email); } /** * Metodo que retorna a transportadora correspondente ao email * * @param email nome do ficheiro * @return transportadora lida */ public Transportadora emailToTran(String email) { Map<String, Transportadora> aux = this.getTransportadoras(); return aux.get(email); } /** * Metodo que retorna a loja correspondente ao email * * @param email nome do ficheiro * @return loja lida */ public Loja emailToLoja(String email) { Map<String, Loja> aux = this.getLojas(); return aux.get(email); } /** * Metodo que verifica se existe o email * * @param email email a verificar */ public void existeEmail(String email) throws NoEmailException { Utilizador u = this.utilizadores.get(email); if (u != null) return; Voluntario v = this.voluntarios.get(email); if (v != null) return; Transportadora t = this.transportadoras.get(email); if (t != null) return; Loja l = this.lojas.get(email); if (l != null) return; throw new NoEmailException(email); } /** * Metodo que verifica se o email e valido para registar * * @param email email a verificar */ public void isEmail(String email) throws EmailInvalidoException { try { existeEmail(email); } catch (NoEmailException e) { if (!((email.contains(".com") || email.contains(".pt")) && email.contains("@"))) throw new EmailInvalidoException(email); } } /** * Metodo que devolve o codigo do utilizador/voluntario/transportadora/loja dado o seu email * * @param email email do utilizador/voluntario/transportadora/loja * @return codigo obtido */ public String emailToCod(String email) throws NoEmailException { Utilizador u = this.utilizadores.get(email); if (u != null) return u.getCodUser(); Voluntario v = this.voluntarios.get(email); if (v != null) return v.getCodVol(); Transportadora t = this.transportadoras.get(email); if (t != null) return t.getCodTran(); Loja l = this.lojas.get(email); if (l != null) return l.getCodLoja(); throw new NoEmailException(email); } /** * Metodo que retorna o utilizador correspondente ao codigo do utilizador * * @param codUser codigo do utilizador * @return utilizador correspondente */ public Utilizador codUserToU(String codUser) { Utilizador ret = new Utilizador(); for (Utilizador u : utilizadores.values()) if (codUser.equals(u.getCodUser())) { ret = u.clone(); break; } return ret; } /** * Metodo que retorna o voluntario correspondente ao codigo do voluntario * * @param codVolu codigo do voluntario * @return voluntario correspondente */ public Voluntario codVolToV(String codVolu) { Voluntario ret = new Voluntario(); for (Voluntario v : voluntarios.values()) if (codVolu.equals(v.getCodVol())) { ret = v.clone(); break; } return ret; } /** * Metodo que retorna a transportadora correspondente ao codigo da transportadora * * @param codTran codigo da transportadora * @return transportadora correspondente */ public Transportadora codTranToT(String codTran) { Transportadora ret = new Transportadora(); for (Transportadora t : transportadoras.values()) if (codTran.equals(t.getCodTran())) { ret = t.clone(); break; } return ret; } /** * Metodo que retorna a loja correspondente ao codigo da loja * * @param codLoja codigo da loja * @return loja correspondente */ public Loja codLojaToL(String codLoja) { Loja ret = new Loja(); for (Loja l : lojas.values()) if (codLoja.equals(l.getCodLoja())) { ret = l.clone(); break; } return ret; } /** * Metodo que aceita uma encomenda dos logs * * @param codEnc codigo da encomenda */ public void encAceiteLogs(String codEnc) { int max = encomendas.size(); int ind = -1; Encomenda e = new Encomenda(); for (int i = 0; i < max; i++) { e = encomendas.get(i); if (codEnc.equals(e.getCodEnc())) { ind = i; break; } } Loja l = codLojaToL(e.getCodLoja()); int vol = 0; for (Voluntario v : voluntarios.values()) { if (isInRaio(v.getRaio(), v.getGPSX(), v.getGPSY(), l.getGPSX(), l.getGPSY()) && v.getDisp() != 0) { e.setEstado(0); String data = LocalDateTime.now().toString(); e.setData(data); encomendas.set(ind, e); vol = 1; List<Encomenda> encs = v.getEncomendas(); encs.add(e); v.setEncomendas(encs); voluntarios.put(v.getEmail(), v); break; } } int tran = 0; if (vol == 0) { for (Transportadora t : transportadoras.values()) { if (isInRaio(t.getRaio(), t.getGPSX(), t.getGPSY(), l.getGPSX(), l.getGPSY()) && t.getDisp() != 0) { e.setEstado(3); encomendas.set(ind, e); tran = 1; List<Encomenda> encs = t.getEncomendas(); encs.add(e); t.setEncomendas(encs); transportadoras.put(t.getEmail(), t); break; } } } if (tran == 0 && vol == 0) { System.out.println("Impossivel aceitar encomenda " + codEnc + "!\n"); } } /** * Metodo que retorna a distancia entre uma encomenda e um voluntario * * @param e encomenda * @param v voluntario * @return distancia */ public double getDisEncVol(Encomenda e, Voluntario v) { Loja l = codLojaToL(e.getCodLoja()); return distanciaGPS(l.getGPSX(), l.getGPSY(), v.getGPSY(), v.getGPSY()); } /** * Metodo que retorna a distancia entre uma encomenda e uma transportadora * * @param e encomenda * @param t transportadora * @return distancia */ public double getDisEncTran(Encomenda e, Transportadora t) { Loja l = codLojaToL(e.getCodLoja()); return distanciaGPS(l.getGPSX(), l.getGPSY(), t.getGPSY(), t.getGPSY()); } /** * Metodo que verifica se duas passwords coincidirem * * @param password <PASSWORD> * @param pass <PASSWORD> * @return 0 se coincidirem */ public int passValida(String password, String pass) throws PassInvalidaException { if (password.equals(pass)) return 0; else throw new PassInvalidaException(pass); } /** * Metodo que verifica se um nome e valido * * @param nome nome * @return 0 se for valido */ public int nomeValido(String nome) throws NomeInvalidoException { int i; char c; for (i = 0; i < nome.length(); i++) { c = nome.charAt(i); if (!Character.isLetter(c) && c != ' ') throw new NomeInvalidoException(nome); } return 0; } /** * Metodo que verifica se um nif e valido * * @param nif nif * @return 0 se for valido */ public int nifValido(long nif) throws NifInvalidoException { if (nif <= 999999999 && nif > 99999999) return 0; else throw new NifInvalidoException(); } /** * Metodo que adiciona um utilizador aos dados * * @param u utilizador */ public void addUser(Utilizador u){ utilizadores.put(u.getEmail(), u); } /** * Metodo que adiciona um voluntario aos dados * * @param v voluntario */ public void addVolu(Voluntario v) { voluntarios.put(v.getEmail(), v); } /** * Metodo que adiciona uma transportdora aos dados * * @param t transportadora */ public void addTran(Transportadora t) { transportadoras.put(t.getEmail(), t); } /** * Metodo que adiciona uma loja aos dados * * @param l loja */ public void addLoja(Loja l) { lojas.put(l.getEmail(), l); } /** * Metodo que gera um novo codigo de utilizador * * @return novo codigo */ public String newCodUser() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "u" + aux; done = 0; for (Utilizador u : utilizadores.values()) { if (u.getCodUser().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que gera um novo codigo de voluntario * * @return novo codigo */ public String newCodVolu() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "v" + aux; done = 0; for (Voluntario v : voluntarios.values()) { if (v.getCodVol().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que gera um novo codigo de transportadora * * @return novo codigo */ public String newCodTran() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "t" + aux; done = 0; for (Transportadora t : transportadoras.values()) { if (t.getCodTran().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que gera um novo codigo de loja * * @return novo codigo */ public String newCodLoja() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "l" + aux; done = 0; for (Loja l : lojas.values()) { if (l.getCodLoja().equals(ret)) { aux++; done = 1; break; } } } return ret; } public String newCodEnc() { int done = 1; String ret = null; int aux = 0; while (done != 0) { ret = "e" + aux; done = 0; for(Encomenda e : encomendas) { if(e.getCodEnc().equals(ret)) { aux++; done = 1; break; } } } return ret; } /** * Metodo que calcula as encomendas acessiveis a um Voluntario * * @param v Voluntario em causa * @return lista de encomendas acessiveis */ public List<Encomenda> getEncomendasAcsVol(Voluntario v) { List<Loja> ljs = lojas .values() .stream() .filter(l -> isInRaio(v.getRaio(), v.getGPSX(), v.getGPSY(), l.getGPSX(), l.getGPSY())) .collect(Collectors.toList()); List<Encomenda> ret = new ArrayList<>(); for (Loja l : ljs) { //System.out.println(l); for (Encomenda e : l.getEncomendas()) { // System.out.println(e); if(e.getEstado() == 2) { if(e.isMed()){ if(v.getDisp() == 2) ret.add(e.clone()); }else ret.add(e.clone()); } } } return ret; } /** * Metodo que calcula as encomendas acessiveis a uma transportadora * * @param t Transportadora em causa * @return lista de encomendas acessiveis */ public List<Encomenda> getEncomendasAcsTran(Transportadora t) { List<Loja> ljs = lojas .values() .stream() .filter(l -> isInRaio(t.getRaio(), t.getGPSX(), t.getGPSY(), l.getGPSX(), l.getGPSY())) .collect(Collectors.toList()); List<Encomenda> ret = new ArrayList<>(); for (Loja l : ljs) { //System.out.println(l); for (Encomenda e : l.getEncomendas()) { // System.out.println(e); if(e.getEstado() == 2){ if(e.isMed()){ if(t.getDisp() == 2) ret.add(e.clone()); }else ret.add(e.clone()); } } } return ret; } /** * Metodo no qual uma transportadora escolhe uma encomenda * * @param t transportadora em causa */ public void escolheEncTran(Transportadora t) { ArrayList<String> aux = new ArrayList<>(); List<Encomenda> enc = getEncomendasAcsTran(t); if(enc.size() != 0) { for (Encomenda e : enc) { //System.out.println(e); aux.add(e.getCodEnc() + "(" + ((int) (getDisEncTran(e, t) + 0.5)) + "Km)"); } String[] s = new String[aux.size()]; for (int i = 0; i < aux.size(); i++) { s[i] = aux.get(i); } UInterface ui = new UInterface(s); System.out.println("\n\n\n\n\n\nEscolha encomenda a transportar:"); int op = ui.exec(); if (op != 0) { Encomenda e = enc.get(op - 1).clone(); e.setEstado(3); int ind = 0; for (Encomenda ed : encomendas) { if (e.getCodEnc().equals(ed.getCodEnc())) { break; } ind++; } encomendas.set(ind, e); t.addEncomenda(e); transportadoras.put(t.getEmail(), t.clone()); updateEncs(); System.out.println("Encomenda selecionada!\n"); } }else System.out.println("\nNao existem encomendas disponiveis!"); } public String geraDataVol(Voluntario v, Loja l, Utilizador u){ List<String> listMet = new ArrayList<>(); listMet.add("Sol"); listMet.add("Nublado"); listMet.add("Chuva"); listMet.add("Nevoeiro"); listMet.add("Tempestade"); Random rand = new Random(); String meteo = listMet.get(rand.nextInt(listMet.size())); double dist = getDistTotalVol(v,l,u); double vel = 0; if(meteo.equals("Sol")) vel = 110; if(meteo.equals("Nublado")) vel = 90; if(meteo.equals("Chuva")) vel = 70; if(meteo.equals("Nevoeiro")) vel = 60; if(meteo.equals("Tempestade")) vel = 30; double tempo = dist/vel; int minutos = (int) tempo*60; LocalDateTime now = LocalDateTime.now().plusMinutes(minutos); return now.toString(); } public String geraDataTran(Transportadora t, Loja l, Utilizador u){ List<String> listMet = new ArrayList<>(); listMet.add("Sol"); listMet.add("Nublado"); listMet.add("Chuva"); listMet.add("Nevoeiro"); listMet.add("Tempestade"); Random rand = new Random(); String meteo = listMet.get(rand.nextInt(listMet.size())); double dist = getDistTotalTran(t,l,u); double vel = 0; if(meteo.equals("Sol")) vel = 110; if(meteo.equals("Nublado")) vel = 90; if(meteo.equals("Chuva")) vel = 70; if(meteo.equals("Nevoeiro")) vel = 60; if(meteo.equals("Tempestade")) vel = 30; double tempo = dist/vel; int minutos = (int) tempo*60; LocalDateTime now = LocalDateTime.now().plusMinutes(minutos); return now.toString(); } /** * Metodo no qual um voluntario escolhe uma encomenda * * @param v voluntario em causa */ public void escolheEncVol(Voluntario v) { ArrayList<String> aux = new ArrayList<>(); List<Encomenda> enc = getEncomendasAcsVol(v); if(enc.size() != 0) { for (Encomenda e : enc){ aux.add(e.getCodEnc() + "(" + ((int) (getDisEncVol(e, v) + 0.5)) + "Km)"); } String[] s = new String[aux.size()]; for (int i = 0; i < aux.size(); i++) { s[i] = aux.get(i); } UInterface ui = new UInterface(s); System.out.println("\n\n\n\n\n\nEscolha encomenda a transportar:"); int op = ui.exec(); if(op != 0) { Encomenda e = enc.get(op - 1).clone(); e.setEstado(0); Loja l = codLojaToL(e.getCodLoja()); Utilizador u = codUserToU(e.getCodUser()); String data = geraDataVol(v,l,u); e.setData(data); LocalDateTime ldt = LocalDateTime.parse(data); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT); System.out.println("Chegada ao utilizador as: " + ldt.format(formatter)); int ind = 0; for (Encomenda ed : encomendas) { if (e.getCodEnc().equals(ed.getCodEnc())) { break; } ind++; } encomendas.set(ind, e); v.addEncomenda(e); voluntarios.put(v.getEmail(), v.clone()); updateEncs(); System.out.println("Encomenda entregue!\n"); } }else System.out.println("\nNao existem encomendas disponiveis!"); } /** * Metodo que da update a todos os objetos necessarios consoante a lista de encomendas */ public void updateEncs() { for (Voluntario v : voluntarios.values()) updateEncsVol(v); for (Transportadora t : transportadoras.values()) updateEncsTran(t); for (Utilizador u : utilizadores.values()) updateEncsUser(u); for (Loja l : lojas.values()) updateEncsLoja(l); } /** * Metodo que da update a todos os voluntarios consoante a lista de encomendas */ public void updateEncsVol(Voluntario v) { List<Encomenda> encV = v.getEncomendas(); for (Encomenda e : encomendas) { int ind2 = 0; for (Encomenda en : encV) { if (e.getCodEnc().equals(en.getCodEnc())) { encV.set(ind2, e.clone()); v.setEncomendas(encV); voluntarios.put(v.getEmail(), v.clone()); //System.out.println("++++++++++++++++++++++\n" + v); } ind2++; } } } /** * Metodo que da update a todos os utilizadores consoante a lista de encomendas */ public void updateEncsUser(Utilizador u) { List<Encomenda> encU = u.getEncomendas(); for (Encomenda e : encomendas) { int ind = 0; for (Encomenda en : encU) { if(e.getCodEnc().equals(en.getCodEnc())) { encU.set(ind, e.clone()); u.setEncomendas(encU); utilizadores.put(u.getEmail(), u.clone()); //System.out.println("++++++++++++++++++++++\n" + u); } ind++; } } } /** * Metodo que da update a todas as transportadoras consoante a lista de encomendas */ public void updateEncsTran(Transportadora t) { List<Encomenda> encT = t.getEncomendas(); for (Encomenda e : encomendas) { int ind = 0; for (Encomenda en : encT) { if (e.getCodEnc().equals(en.getCodEnc())) { encT.set(ind, e.clone()); t.setEncomendas(encT); transportadoras.put(t.getEmail(), t.clone()); //System.out.println("++++++++++++++++++++++\n" + t); } ind++; } } } /** * Metodo que da update a todas as lojas consoante a lista de encomendas */ public void updateEncsLoja(Loja l) { List<Encomenda> encL = l.getEncomendas(); for (Encomenda e : encomendas) { int ind = 0; for (Encomenda en : encL) { if (e.getCodEnc().equals(en.getCodEnc())) { encL.set(ind, e.clone()); l.setEncomendas(encL); lojas.put(l.getEmail(), l.clone()); //System.out.println("++++++++++++++++++++++\n" + l); } ind++; } } } public void isCodProd(String codProd) throws CodProdInvalidoException{ if(codProd.charAt(0) != 'p') throw new CodProdInvalidoException(codProd); for(int i = 1; i < codProd.length(); i++) if(!isDigit(codProd.charAt(i)) || 3 < i ) throw new CodProdInvalidoException(codProd); } public ArrayList<LinhaEncomenda> criarProdutos(){ int op = 1; ArrayList<LinhaEncomenda> ret= new ArrayList<>(); String codProd = null; String desc = null; double qntd = 0.0; double valuni = 0.0; while(op != 0){ LinhaEncomenda le = new LinhaEncomenda(); int val = 1; Scanner in = new Scanner(System.in); while(val != 0){ System.out.println("Insira codigo do produto (pXX)"); codProd = in.nextLine(); try{ isCodProd(codProd); val = 0; }catch(CodProdInvalidoException e){ System.out.println("Valor invalido"); val = 1; } } val = 1; while(val != 0){ System.out.println("Insira descricao do produto"); desc = in.nextLine(); try{ nomeValido(desc); val = 0; }catch(NomeInvalidoException e){ System.out.println("Valor invalido"); val = 1; } } val = 1; while(val != 0){ System.out.println("Insira a quantidade"); try{ qntd = in.nextDouble(); val = 0; }catch(InputMismatchException e){ System.out.println("Valor invalido"); val = 1; } } val = 1; while(val != 0){ System.out.println("Insira o valor unitario"); valuni = -1; try{ valuni = in.nextInt(); val = 0; }catch(InputMismatchException e){ System.out.println("Valor invalido"); val = 1; } } le.setCodProduto(codProd); le.setDescricao(desc); le.setQuantidade(qntd); le.setValorUni(valuni); ret.add(le.clone()); val = 1; int insmais = -1; while(val != 0){ System.out.println("Inserir mais produtos?\n(0 - NAO) (1 - SIM)"); try{ insmais = in.nextInt(); val = 0; }catch (InputMismatchException e){ System.out.println("Valor invalido"); val = 1; } } op = insmais; } return ret; } public void criarEncomenda(String codUser){ Encomenda e = new Encomenda(); e.setCodUser(codUser); int op = 1; Scanner inp = new Scanner(System.in); while(op != 0){ System.out.println("(0 - Sair)\nInsira codigo da loja: "); String in = inp.nextLine(); try { if (Integer.parseInt(in) == 0) return; }catch (NumberFormatException ignored){} Loja l = codLojaToL(in); if(l.getEmail() == null) System.out.println("Loja inexistente"); else{ e.setCodLoja(in); op = 0; } } op = 1; while(op != 0) { System.out.println("(0 - Sair)\nInsira o peso da encomenda: "); double in; try { in = inp.nextInt(); if (in == 0) return; op = 0; e.setPeso((double)in); } catch (Exception ex) { System.out.println("Valor invalido!"); op = 1; } } op = 1; System.out.println("\nEncomenda medica? (0 - SIM)"); double in = -1; try{in = inp.nextInt();}catch (InputMismatchException ignored) {} if(in == 0)e.setMed(true); else e.setMed(false); e.setEstado(1); e.setCodEnc(newCodEnc()); e.setProdutos(criarProdutos()); encomendas.add(e); updateEncs(); } /** * Metodo que informa o sistema que uma encomenda de uma loja esta pronta * * @param l loja em causa */ public void reqEntrega(Loja l) { List<Encomenda> enc = l.getEncomendasEstado(1); if (enc.size() != 0){ String[] encs = new String[enc.size()]; int i = 0; for (Encomenda e : enc) { //System.out.println(e); encs[i] = e.getCodEnc(); i++; } UInterface ui = new UInterface(encs); int op = ui.exec(); if (op == 0) return; Encomenda es = enc.get(op - 1); es.setEstado(2); int indd = 0; for (Encomenda e : encomendas) { if (es.getCodEnc().equals(e.getCodEnc())) break; indd++; } encomendas.set(indd, es.clone()); System.out.println("\nEncomenda disponibilizada com pronta para entrega!\n"); //System.out.println("abcd"); } else System.out.println("\nNao ha encomendas pendentes!\n"); updateEncs(); } public void veAvaliacoes(String codVolTran){ int vol = 0; Voluntario v = codVolToV(codVolTran); Transportadora t = codTranToT(codVolTran); if(v.getEmail()==null){ vol = 1;} List<Encomenda> encs = new ArrayList<>(); if(vol == 0){ encs = v.getEncomendasEstado(0);} else{encs = t.getEncomendasEstado(0);} Map<String, Double> classif = new TreeMap<>(); for(String codE : classificacoes.keySet()){ for(Encomenda e : encs){ if(codE.equals(e.getCodEnc())){ classif.put(codE, classificacoes.get(codE)); } } } double size = classif.size(); if(size == 0) System.out.println("Nao existem classificacoes!"); else{ double media = 0; for(String e : classif.keySet()){ Double d = classif.get(e); System.out.println("Encomenda " + e + " obteve classificacao de " + d); media += d; } media = media/size; System.out.println("Media: " + media); } } public void avaliaEncomenda(String codUser){ Utilizador u = codUserToU(codUser); List<Encomenda> encs = u.getEncomendasEstado(0); for(Encomenda e : encs){ for(String s : classificacoes.keySet()){ if(s.equals(e.getCodEnc())){ encs.remove(e); } } } int i = 0; String[] str = new String[encs.size()]; System.out.println("Escolha encomenda a avaliar:"); for(Encomenda e : encs){ str[i] = ("Encomenda " + e.getCodEnc() + " da loja " + e.getCodLoja()); i++; } UInterface ui = new UInterface(str); int op = ui.exec(); if(op != 0){ Encomenda e = encs.get(op-1); System.out.println("Avalie a encomenda "+ e.getCodEnc() + " (0-5):"); Scanner ss = new Scanner(System.in); double avaliacao = 0.0; int val = 1; while(val!=0) { try { avaliacao = ss.nextInt(); if(avaliacao > 5.0) avaliacao = 5.0; val = 0; } catch (InputMismatchException g) { System.out.print("Valor inválido!"); val = 1; } } classificacoes.put(e.getCodEnc(),avaliacao); System.out.println("Encomenda avaliada com sucesso!\n\n" + avaliacao); } } /** * Metodo imprime o historico de encomendas de um objeto do tipo utilizador, voluntario, transportadora, loja * * @param o objeto em questao */ public void histEncomendas(Object o){ List <Encomenda> encomendas = new ArrayList<>(); if(o instanceof Utilizador){ Utilizador u = (Utilizador) o; encomendas = u.getEncomendasEstado(0); } if(o instanceof Voluntario){ Voluntario v = (Voluntario) o; encomendas = v.getEncomendasEstado(0); } if(o instanceof Transportadora){ Transportadora t = (Transportadora) o; encomendas = t.getEncomendasEstado(0); } if(o instanceof Loja){ Loja l = (Loja) o; encomendas = l.getEncomendasEstado(0); } Scanner input = new Scanner(System.in); int inp = 1; int op = 0; if(encomendas.size() != 0) { while (inp != 0) { System.out.println("(0) - Por data\n(1) - Todas"); try { op = input.nextInt(); inp = 0; } catch (InputMismatchException e) { System.out.println("Valor invalido!"); inp = 1; } } if (op == 0) { input.nextLine(); int val = 1; LocalDateTime date1 = null; LocalDateTime date2 = null; while (val != 0) { System.out.print("\n(aaaa-mm-dd)\nEntre a data: \n"); String dateString = input.nextLine(); dateString += "T00:00:00"; try { date1 = LocalDateTime.parse(dateString); val = 0; } catch (DateTimeParseException e) { System.out.println("Data invalida!"); val = 1; } } val = 1; while (val != 0) { System.out.print("e a data :"); String dateString = input.nextLine(); dateString += "T00:00:00"; try { date2 = LocalDateTime.parse(dateString); val = 0; } catch (DateTimeParseException e) { System.out.println("Data invalida!"); val = 1; } } List<Encomenda> encomendasInData = new ArrayList<>(); LocalDateTime dataEnc; for (Encomenda e : encomendas) { if (e.getData() != null) { dataEnc = LocalDateTime.parse(e.getData()); if (dataEnc.isAfter(date1) && dataEnc.isBefore(date2)) encomendasInData.add(e); } } int arrSize = encomendasInData.size(); if (arrSize != 0) { System.out.println("Encomendas:"); for (Encomenda e : encomendasInData) System.out.println("-" + e.getCodEnc() + " (" + e.getDataPrint() + ")"); } else System.out.println("\nNao existem encomendas terminadas nestas datas!\n"); } else { System.out.println("Encomendas:"); for (Encomenda e : encomendas) { System.out.println("-" + e.getCodEnc() + " (" + e.getDataPrint() + ")"); } } }else{ System.out.println("\nNao existem encomendas terminadas!\n"); } System.out.println(""); } /** * Metodo que povoa alguns dados apos o import de logs */ public void povoaDados() { for (Encomenda e : encomendas) { Utilizador u = codUserToU(e.getCodUser()); int ind1 = 0; int indU = -1; for (Encomenda en : u.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encU = u.getEncomendas(); encU.set(ind1, e.clone()); u.setEncomendas(encU); utilizadores.put(u.getEmail(), u.clone()); //System.out.println("++++++++++++++++++++++\n" + u); indU = ind1; } ind1++; } if (indU == -1) { List<Encomenda> encU = u.getEncomendas(); encU.add(e.clone()); u.setEncomendas(encU); utilizadores.put(u.getEmail(), u); } Voluntario v = codVolToV(e.getCodUser()); int ind2 = 0; for (Encomenda en : v.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encV = v.getEncomendas(); encV.set(ind2, e.clone()); v.setEncomendas(encV); voluntarios.put(v.getEmail(), v.clone()); //System.out.println("++++++++++++++++++++++\n" + v); } ind2++; } Transportadora t = codTranToT(e.getCodUser()); int ind3 = 0; for (Encomenda en : t.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encT = t.getEncomendas(); encT.set(ind3, e.clone()); t.setEncomendas(encT); transportadoras.put(t.getEmail(), t.clone()); //System.out.println("++++++++++++++++++++++\n" + t); } ind3++; } Loja l = codLojaToL(e.getCodLoja()); int ind4 = 0; int indL = -1; for (Encomenda en : l.getEncomendas()) { if (e.getCodEnc().equals(en.getCodEnc())) { List<Encomenda> encL = l.getEncomendas(); encL.set(ind4, e.clone()); l.setEncomendas(encL); lojas.put(l.getEmail(), l); indL = ind4; } ind4++; } if (indL == -1) { List<Encomenda> encL = l.getEncomendas(); ; encL.add(e.clone()); l.setEncomendas(encL); lojas.put(l.getEmail(), l); } } } /** * Metodo que faz parse dos logs para a estrutura dados * * @param file ficheiro de logs */ public void parse(String file) { int pov = 0; List<String> linhas = lerFicheiro(file); //alterar nome do ficheiro String[] linhaPartida; for (String linha : linhas) { linhaPartida = linha.split(":", 2); switch (linhaPartida[0]) { case "Utilizador": Utilizador u = parseUtilizador(linhaPartida[1]); // criar um Utilizador //System.out.println(u.toString()); //enviar para o ecra apenas para teste utilizadores.put(u.getEmail(), u); break; case "Loja": Loja l = parseLoja(linhaPartida[1]); //System.out.println(l.toString()); lojas.put(l.getEmail(), l); break; case "Voluntario": Voluntario v = parseVoluntario(linhaPartida[1]); voluntarios.put(v.getEmail(), v); //System.out.println(v.toString()); povoaDados(); break; case "Transportadora": Transportadora t = parseTransportadora(linhaPartida[1]); transportadoras.put(t.getEmail(), t); //System.out.println(t.toString()); break; case "Encomenda": Encomenda e = parseEncomenda(linhaPartida[1]); //System.out.println(e.toString()); encomendas.add(e); break; case "Aceite": if (pov == 0) povoaDados(); encAceiteLogs(linhaPartida[1]); pov = 1; break; default: System.out.println("Linha invalida."); break; } } updateEncs(); System.out.println("\n\n\n\nLogs importados com sucesso!\n"); } /** * Metodo que faz parse de uma linha de logs correspondente a um utilizador * * @param input linha de logs * @return utilizador obtido */ public Utilizador parseUtilizador(String input) { Utilizador u = new Utilizador(); String[] campos = input.split(","); String codUtilizador = campos[0]; String nome = campos[1]; double gpsX = Double.parseDouble(campos[2]); double gpsY = Double.parseDouble(campos[3]); String password = nome.replace(" ", "").toLowerCase(); String email = password + "@<PASSWORD>"; u.setCodUser(codUtilizador); u.setNome(nome); u.setGPS(gpsX, gpsY); u.setEmail(email); u.setPassword(<PASSWORD>); return u; } /** * Metodo que faz parse de uma linha de logs correspondente a um voluntario * * @param input linha de logs * @return voluntario obtido */ public Voluntario parseVoluntario(String input) { Voluntario v = new Voluntario(); String[] campos = input.split(","); String codVol = campos[0]; String nome = campos[1]; double gpsX = Double.parseDouble(campos[2]); double gpsY = Double.parseDouble(campos[3]); double raio = Double.parseDouble(campos[4]); String password = nome.replace(" ", "").toLowerCase(); String email = password + "@<PASSWORD>"; v.setCodVol(codVol); v.setNome(nome); v.setGPS(gpsX, gpsY); v.setEmail(email); v.setPassword(password); v.setRaio(raio); return v; } /** * Metodo que faz parse de uma linha de logs correspondente a uma transportadora * * @param input linha de logs * @return transportadora obtida */ public Transportadora parseTransportadora(String input) { Transportadora t = new Transportadora(); String[] campos = input.split(","); String codTran = campos[0]; String nome = campos[1]; double gpsX = Double.parseDouble(campos[2]); double gpsY = Double.parseDouble(campos[3]); long nif = Long.parseLong(campos[4]); double raio = Double.parseDouble(campos[5]); double precokm = Double.parseDouble(campos[6]); String password = nome.replace(" ", "").toLowerCase(); String email = password + "@<PASSWORD>"; t.setCodTran(codTran); t.setNome(nome); t.setGPS(gpsX, gpsY); t.setNIF(nif); t.setRaio(raio); t.setPrecoKM(precokm); t.setEmail(email); t.setPassword(password); return t; } /** * Metodo que faz parse de uma linha de logs correspondente a uma loja * * @param input linha de logs * @return loja obtida */ public Loja parseLoja(String input) { double x = ThreadLocalRandom.current().nextDouble(-100, 100); double y = ThreadLocalRandom.current().nextDouble(-100, 100); Loja l = new Loja(); String[] campos = input.split(","); String codLoja = campos[0]; String nome = campos[1]; String password = nome.replace(" ", "").toLowerCase(); String email = password + "@<PASSWORD>"; l.setCodLoja(codLoja); l.setnome(nome); l.setGPS(x, y); l.setEmail(email); l.setPassword(<PASSWORD>); return l; } /** * Metodo que faz parse de uma linha de logs correspondente a uma lista de produtos * * @param input linha de logs * @return lista de produtos obtida */ public ArrayList<LinhaEncomenda> parseProdutos(String input) { String[] campos = input.split(","); ArrayList<LinhaEncomenda> produtos = new ArrayList<>(); int camposLength = campos.length; int done = 0; for (int i = 0; done != 1; i += 4) { LinhaEncomenda le = new LinhaEncomenda(); String codProduto = campos[i]; String descricao = campos[i + 1]; double quantidade = Double.parseDouble(campos[i + 2]); double valorUni = Double.parseDouble(campos[i + 3]); le.setCodProduto(codProduto); le.setDescricao(descricao); le.setQuantidade(quantidade); le.setValorUni(valorUni); produtos.add(le); if (i + 4 >= camposLength) done = 1; } return produtos; } /** * Metodo que faz parse de uma linha de logs correspondente a uma encomenda * * @param input linha de logs * @return encomenda obtida */ public Encomenda parseEncomenda(String input) { Encomenda e = new Encomenda(); String[] campos = input.split(",", 5); String codEnc = campos[0]; String codUser = campos[1]; String codLoja = campos[2]; double peso = Double.parseDouble(campos[3]); ArrayList<LinhaEncomenda> produtos = parseProdutos(campos[4]); e.setCodEnc(codEnc); e.setCodUser(codUser); e.setCodLoja(codLoja); e.setPeso(peso); e.setProdutos(produtos); return e; } /** * Metodo le todas as linhas de um ficheiro * * @param nomeFich nome do ficheiro * @return linhas obtidas */ public List<String> lerFicheiro(String nomeFich) { List<String> lines = new ArrayList<>(); try { lines = Files.readAllLines(Paths.get(nomeFich), StandardCharsets.UTF_8); } catch (IOException exc) { System.out.println(exc.getMessage()); } return lines; } /** * Metodo que calcula a distancia entre duas entidades * * @param gpsX1 coordenada x da primeira entidade * @param gpsY1 coordenada y da primeira entidade * @param gpsX2 coordenada x da segunda entidade * @param gpsY2 coordenada y da segunda entidade * @return distancia */ public static double distanciaGPS(double gpsX1, double gpsY1, double gpsX2, double gpsY2) { return Math.sqrt(Math.pow((gpsX2 - gpsX1 + gpsY2 - gpsY1), 2.0)); } /** * Metodo que calcula se uma entidade se encontra no raio de outra * * @param raio raio * @param gpsX1 coordenada x da primeira entidade * @param gpsY1 coordenada y da primeira entidade * @param gpsX2 coordenada x da segunda entidade * @param gpsY2 coordenada y da segunda entidade * @return true se estiver, false se nao estiver */ public static boolean isInRaio(double raio, double gpsX1, double gpsY1, double gpsX2, double gpsY2) { return distanciaGPS(gpsX1, gpsY1, gpsX2, gpsY2) <= raio; } /** * Metodo que verifica se existe uma resposta pendente de um utilizador * * @param u utilizador em causa * @return true se existir, false se nao existir */ public boolean existeRespPend(Utilizador u){ List<Encomenda> aux = u.getEncomendasEstado(3); return aux.size() != 0; } public Transportadora getTranEnc(String codEnc){ for(Transportadora t : transportadoras.values()){ List<Encomenda> aux = t.getEncomendas(); for(Encomenda e : aux){ if(e.getCodEnc().equals(codEnc)) return t.clone(); } } return null; } public double getDistTotalTran(Transportadora t, Loja l, Utilizador u){ return distanciaGPS(t.getGPSX(),t.getGPSY(),l.getGPSX(),l.getGPSY()) + distanciaGPS(l.getGPSX(),l.getGPSY(),u.getGPSX(),u.getGPSY()); } public double getDistTotalVol(Voluntario v, Loja l, Utilizador u){ return distanciaGPS(v.getGPSX(),v.getGPSY(),l.getGPSX(),l.getGPSY()) + distanciaGPS(l.getGPSX(),l.getGPSY(),u.getGPSX(),u.getGPSY()); } public double getPreco(double peso, Transportadora t, Loja l, Utilizador u){ double custoKM = t.getPrecoKM(); return (peso/1.5)*(getDistTotalTran(t,l,u)*custoKM); } /** * Metodo que gere uma resposta pendesnte de um utilizador * * @param u utilizador em causa */ public void gereRespPend(Utilizador u){ List<Encomenda> aux = u.getEncomendasEstado(3); for(Encomenda e : aux){ Transportadora t = getTranEnc(e.getCodEnc()); Loja l = codLojaToL(e.getCodLoja()); double precoD = getPreco(e.getPeso(),t,l,u); String preco = String.format("%.02d", precoD); System.out.println("Encomenda: " + e.getCodEnc() + "\nTransportadora: " + t.getCodTran() + "\nPreco esperado: " + preco); System.out.println("(0) - Recusar\n(1) - Aceitar"); int op = 0; int inp = 1; Scanner s = new Scanner(System.in); while(inp != 0) { try{ op = s.nextInt(); inp = 0; }catch(InputMismatchException i) { System.out.println("Valor invalido!"); inp = 1; } } if(op == 0){ List<Encomenda> auxt = t.getEncomendas(); auxt.remove(e); t.setEncomendas(auxt); transportadoras.put(t.getEmail(),t.clone()); e.setEstado(2); }else{ e.setEstado(0); e.setData(geraDataTran(t,l,u)); e.setPrecoEntrega(precoD); } int ind = 0; for(Encomenda ed : encomendas){ if(e.getCodEnc().equals(ed.getCodEnc())){ break; } ind++; } encomendas.set(ind,e.clone()); updateEncs(); } } public void totFatTrans(){ List<Transportadora> trans = new ArrayList<>(transportadoras.values()); String[] str = new String[trans.size()]; int ind = 0; for(Transportadora t : trans){ str[ind] = t.getCodTran(); ind++; } while(true){ UInterface ui = new UInterface(str); int op = ui.exec(); if(op != 0){ Transportadora tp = trans.get(op-1); System.out.println("Total faturado pela transportadora " + tp.getCodTran() + " e: " + totFatTran(tp) + "€"); }else break; } } public double totFatTran(Transportadora t){ double total = 0; List<Encomenda> encs = t.getEncomendas(); for(Encomenda e : encs){ if(e.getEstado() == 0) total += e.getPrecoEntrega(); } return total; } public void dezUsrMaisUsaram(){ List<Utilizador> usrs = new ArrayList<>(utilizadores.values()); usrs.sort(UserComparator); int i = 1; for(Utilizador u : usrs){ if(i > 10) break; System.out.println(i + " - " + u.getNome() + "(" + u.getEncomendasEstado(0).size() + " Encomendas)"); i++; } System.out.println("\n"); } public void dezTranMaisUsaram(){ Map<Double, Transportadora> mapTran = new TreeMap<>(); for(Transportadora t : transportadoras.values()){ System.out.println(getKmDone(t)); double kmd = getKmDone(t); while(mapTran.containsKey(kmd)){ kmd += 0.00001; } mapTran.put(kmd,t.clone()); } List<Double> sortedKeys = new ArrayList<>(mapTran.keySet()); sortedKeys.sort(Collections.reverseOrder()); List<Transportadora> trans = new ArrayList<>(); for(Double d : sortedKeys){ trans.add(mapTran.get(d)); } int i = 1; for(Transportadora t : trans){ if(i > 10) break; System.out.println(i + " - " + t.getNome() + "(" + getKmDone(t) + " KM)"); i++; } System.out.println("\n"); } public void verPerfilTran(Transportadora o){ int opcao = -1; while(opcao != 0){ System.out.print(o.toString()); System.out.print("\n(1) - Ficar indisponivel" + "\n(2) - Ficar disponivel" + "\n(3) - Ficar disponivel para encomendas medicas" + "\n(0) - Sair\n"); Scanner input = new Scanner(System.in); try{ opcao = input.nextInt(); } catch(InputMismatchException e){ // Não foi escolhido um inteiro opcao = -1; } if(opcao < 0 || opcao > 3){ System.out.println("Valor Inválido!"); opcao = -1; } if(opcao == 1){ o.setDisp(0); } if(opcao == 2){ o.setDisp(1); } if(opcao == 3){ o.setDisp(2); } } transportadoras.put(o.getEmail(),o.clone()); } public void verPerfilVol(Voluntario o){ int opcao = -1; while(opcao != 0){ System.out.print(o.toString()); System.out.print("\n(1) - Ficar indisponivel" + "\n(2) - Ficar disponivel" + "\n(3) - Ficar disponivel para encomendas medicas" + "\n(0) - Sair\n"); Scanner input = new Scanner(System.in); try{ opcao = input.nextInt(); } catch(InputMismatchException e){ // Não foi escolhido um inteiro opcao = -1; } if(opcao < 0 || opcao > 3){ System.out.println("Valor Inválido!"); opcao = -1; } if(opcao == 1){ o.setDisp(0); } if(opcao == 2){ o.setDisp(1); } if(opcao == 3){ o.setDisp(2); } } voluntarios.put(o.getEmail(),o.clone()); } public double getKmDone(Transportadora t){ List<Encomenda> encsT = t.getEncomendasEstado(0); double kms = 0; for(Encomenda e : encsT){ if(e.getEstado() == 0) { Utilizador u = codUserToU(e.getCodUser()); Loja l = codLojaToL(e.getCodLoja()); kms += getPreco(e.getPeso(),t, l, u); } } return kms; } public List<Encomenda> encAccessiveisVol(Voluntario v) { List<Encomenda> ret = new ArrayList<>(); for (Loja lj : lojas.values()) { if (isInRaio(v.getRaio(), v.getGPSX(), v.getGPSY(), lj.getGPSX(), lj.getGPSY())) ret = lj.getEncomendas(); } return ret; } public List<Encomenda> encAccessiveisTra(Transportadora t) { List<Encomenda> ret = new ArrayList<>(); for (Loja lj : lojas.values()) { if (isInRaio(t.getRaio(), t.getGPSX(), t.getGPSY(), lj.getGPSX(), lj.getGPSY())) ret = lj.getEncomendas(); } return ret; } public static Comparator<Utilizador> UserComparator = new Comparator<Utilizador>(){ public int compare(Utilizador u1, Utilizador u2) { int nEncsu1 = u1.getEncomendasEstado(0).size(); int nEncsu2 = u2.getEncomendasEstado(0).size(); return nEncsu2 - nEncsu1; } }; }
62,127
0.50642
0.499501
1,902
31.677181
23.558102
200
false
false
0
0
0
0
0
0
0.554154
false
false
13
468b733eb49e1ca11421493ca05ae7db0a0b4322
6,562,710,031,725
ce05826237700d34fde7e15c14f5efa684ee0fcc
/Backend/src/main/java/com/intern/student/dto/StudentDTO.java
d7070b29468dda7089619ca5d0c5cfaf1c88d749
[]
no_license
tuans1/VinhUni-Clone
https://github.com/tuans1/VinhUni-Clone
0ece0c43eeb38d85dbf412772dddf37b0e51d431
27f8a982ea4e612ef8919ae7cfba9b973d6ebc2a
refs/heads/master
2023-06-30T15:13:33.379000
2021-08-06T09:53:58
2021-08-06T09:53:58
383,824,600
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.intern.student.dto; import java.util.List; import lombok.Data; @Data public class StudentDTO { private String id; private String name; private String dob; // private ClassesDTO classes; private List<ClassDetailDTO> courses; }
UTF-8
Java
259
java
StudentDTO.java
Java
[]
null
[]
package com.intern.student.dto; import java.util.List; import lombok.Data; @Data public class StudentDTO { private String id; private String name; private String dob; // private ClassesDTO classes; private List<ClassDetailDTO> courses; }
259
0.72973
0.72973
23
10.26087
12.290744
38
false
false
0
0
0
0
0
0
0.782609
false
false
13
bd889221b2a95bfab45b54ebdcf1799eab7611ea
31,714,038,547,344
483e7f6bf7c12cb304090243f12ce67a3d13c3c3
/Archivos_Java/MyPaint/src/arreglo/Defensa.java
87890e9fd6c061555e26c2e0aafe9619681b6394
[]
no_license
AxelOrdonez98/Universidad_Proyectos_All
https://github.com/AxelOrdonez98/Universidad_Proyectos_All
87542611c4b3ac858d3d1a69dd87f912544c9bb6
457857b32e1419216c3a0a2de5cc992769483b4b
refs/heads/main
2023-04-09T22:01:08.662000
2021-04-21T00:12:59
2021-04-21T00:12:59
213,707,490
0
0
null
false
2020-11-16T20:41:08
2019-10-08T17:26:20
2020-10-13T13:15:31
2020-11-16T20:41:07
47,254
0
0
4
C++
false
false
package Persona; public final class Defensa extends Jugador { private boolean titular; private boolean resistenciaAGolpes; //------------------------------- public Defensa() { super(); } //------------------------------- public Defensa(boolean titular, boolean resistenciaAGolpes) { this.titular = titular; this.resistenciaAGolpes = resistenciaAGolpes; } //------------------------------- public boolean isTitular() { return titular; } public void setTitular(boolean titular) { this.titular = titular; } //------------------------------- public boolean isResistenciaAGolpes() { return resistenciaAGolpes; } public void setResistenciaAGolpes(boolean resistenciaAGolpes) { this.resistenciaAGolpes = resistenciaAGolpes; } //------------------------------- public String toString() { return super.toString() + "Defensa{" + "titular=" + titular + ", resistenciaAGolpes=" + resistenciaAGolpes + '}'; } }
UTF-8
Java
1,045
java
Defensa.java
Java
[]
null
[]
package Persona; public final class Defensa extends Jugador { private boolean titular; private boolean resistenciaAGolpes; //------------------------------- public Defensa() { super(); } //------------------------------- public Defensa(boolean titular, boolean resistenciaAGolpes) { this.titular = titular; this.resistenciaAGolpes = resistenciaAGolpes; } //------------------------------- public boolean isTitular() { return titular; } public void setTitular(boolean titular) { this.titular = titular; } //------------------------------- public boolean isResistenciaAGolpes() { return resistenciaAGolpes; } public void setResistenciaAGolpes(boolean resistenciaAGolpes) { this.resistenciaAGolpes = resistenciaAGolpes; } //------------------------------- public String toString() { return super.toString() + "Defensa{" + "titular=" + titular + ", resistenciaAGolpes=" + resistenciaAGolpes + '}'; } }
1,045
0.543541
0.543541
32
31.6875
24.047398
121
false
false
0
0
0
0
0
0
0.40625
false
false
13
571a2f2df1c7db35d71640c945222e482f7d1ac8
28,114,855,936,240
9da9de551f2fb049fdf26adc0c3b82e2e531aef7
/module_2_3/practicals/Array1.java
5c93c0694ebc79fe1fbdcc202d67caf3ded68a33
[]
no_license
Priyalsoni227/JavaPractice
https://github.com/Priyalsoni227/JavaPractice
647e2c0edd1dda4b0a0b1d73b97e3f0488bc8798
04cee7e8e5bd22eb2d95d52994a575c7a662ef58
refs/heads/main
2023-08-08T08:23:12.257000
2021-09-16T11:40:32
2021-09-16T11:40:32
401,671,923
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package practicals; import java.util.Scanner; public class Array1 { public static int getDuplicate(int[] arr,int n) { int sum=0; int nsum=(n-1)*n/2; for(int i:arr) { sum+=i; } return sum-nsum; } public static void main(String[] args) { int n; Scanner s = new Scanner(System.in); System.out.println("Enter number of elements: "); n=s.nextInt(); int[] arr=new int[n]; System.out.println("Enter elements: "); for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } System.out.println("Dupplicate element is: "+getDuplicate(arr,n)); } }
UTF-8
Java
616
java
Array1.java
Java
[]
null
[]
package practicals; import java.util.Scanner; public class Array1 { public static int getDuplicate(int[] arr,int n) { int sum=0; int nsum=(n-1)*n/2; for(int i:arr) { sum+=i; } return sum-nsum; } public static void main(String[] args) { int n; Scanner s = new Scanner(System.in); System.out.println("Enter number of elements: "); n=s.nextInt(); int[] arr=new int[n]; System.out.println("Enter elements: "); for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } System.out.println("Dupplicate element is: "+getDuplicate(arr,n)); } }
616
0.582792
0.574675
34
16.117647
17.509266
68
false
false
0
0
0
0
0
0
2
false
false
13
e0ac182f43405b59042c4008fc58d2c8426f59f9
17,471,926,969,697
4778cb84d25deb384eea6b276811733be0562354
/src/main/java/seven/principle/LSP/demo01/Client.java
ceeda29343aacef1417a7085b5ffb7be360f178d
[]
no_license
sanwen88/testRepository
https://github.com/sanwen88/testRepository
3c546d5b7ab39cc48bdebf13785ec68b755e5258
cc8fc347d90642f9c28037b3cffdc5f1cf89f582
refs/heads/master
2020-09-24T01:05:36.429000
2019-12-05T11:37:03
2019-12-05T11:37:03
225,574,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package seven.principle.LSP.demo01; /** * * @author sanwen88 * @date 2019年8月28日 下午2:28:35 * * @Description: 在实际的编程中,我们常常通过重写父类方法,完成新的功能,这样写起来简单,但破坏了整个继承体系。 * * @version V1.0 */ public class Client { public static void main(String[] args) { A a = new A(); System.out.println("10-3="+a.func1(10, 3)); System.out.println("1-10="+a.func1(1, 10)); B b = new B(); System.out.println("10-3="+b.func1(10, 3));//本意是B继承A,通过B调用A中func1()实现减法逻辑,然而实际却是实现加法算法 System.out.println("1+10+9="+b.func2(1, 10)); } }
UTF-8
Java
692
java
Client.java
Java
[ { "context": "ge seven.principle.LSP.demo01;\n\n/**\n * \n * @author sanwen88 \n * @date 2019年8月28日 下午2:28:35 \n *\n * @Descripti", "end": 64, "score": 0.9996066093444824, "start": 56, "tag": "USERNAME", "value": "sanwen88" } ]
null
[]
package seven.principle.LSP.demo01; /** * * @author sanwen88 * @date 2019年8月28日 下午2:28:35 * * @Description: 在实际的编程中,我们常常通过重写父类方法,完成新的功能,这样写起来简单,但破坏了整个继承体系。 * * @version V1.0 */ public class Client { public static void main(String[] args) { A a = new A(); System.out.println("10-3="+a.func1(10, 3)); System.out.println("1-10="+a.func1(1, 10)); B b = new B(); System.out.println("10-3="+b.func1(10, 3));//本意是B继承A,通过B调用A中func1()实现减法逻辑,然而实际却是实现加法算法 System.out.println("1+10+9="+b.func2(1, 10)); } }
692
0.638258
0.547348
23
21.956522
23.326563
88
false
false
0
0
0
0
0
0
1.26087
false
false
13
525ea30ea3194e3204f60088277c41033ebb95ad
13,340,168,484,726
1b0db0eee57a8b109c8e39af090f147d4925a2e1
/src/main/java/com/ctrip/xpipe/echoserver/checker/Reporter.java
97bc06485e6201d8fbda78e89dbb53cf0bcbe4dd
[]
no_license
NickNYU/EchoServer
https://github.com/NickNYU/EchoServer
f08e6e3e934453efb42d73672a2cdc84e27e4272
d384cdc85d2ec89f238b9322f9772b61581859d5
refs/heads/master
2020-03-18T17:46:41.792000
2018-06-12T12:38:37
2018-06-12T12:38:37
135,049,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ctrip.xpipe.echoserver.checker; import com.dianping.cat.Cat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; public class Reporter { private Logger logger = LoggerFactory.getLogger(Reporter.class); private SimpleDateFormat formatter = new SimpleDateFormat(); private static Reporter instance = new Reporter(); private Reporter(){} public static Reporter getInstance() { return instance; } public void reportNullMessage() { formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); report("message.null", formatter.format(new Date())); } public void reportMissing(String message) { report("message.missing", message); } public void reportUnexpected(String message) { report("message.unexpected", message); } public void report(String type, String message) { logger.info("[report] [type] {}, [message]: {}", type, message); Cat.logEvent(type, message); } }
UTF-8
Java
1,053
java
Reporter.java
Java
[]
null
[]
package com.ctrip.xpipe.echoserver.checker; import com.dianping.cat.Cat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; public class Reporter { private Logger logger = LoggerFactory.getLogger(Reporter.class); private SimpleDateFormat formatter = new SimpleDateFormat(); private static Reporter instance = new Reporter(); private Reporter(){} public static Reporter getInstance() { return instance; } public void reportNullMessage() { formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); report("message.null", formatter.format(new Date())); } public void reportMissing(String message) { report("message.missing", message); } public void reportUnexpected(String message) { report("message.unexpected", message); } public void report(String type, String message) { logger.info("[report] [type] {}, [message]: {}", type, message); Cat.logEvent(type, message); } }
1,053
0.679012
0.677113
41
24.682926
23.525221
72
false
false
0
0
0
0
0
0
0.585366
false
false
13
0ff22de18d60e931f0d4f2f7dc152c5364234775
20,899,310,887,237
49a0cedbd7bd3af9a90ba4c3dfc2521a5a80ca51
/limsproduct/src/main/java/net/zjcclims/service/construction/CProjectStatusService.java
75366ef0d35d5e01286e0926b4245d9967e0fc9f
[]
no_license
sangjiexun/limsproduct2
https://github.com/sangjiexun/limsproduct2
a08c611e4197609f36f52c4762585664defe8248
7eedf8fa2944ebbd3b3769f1c4cba61864c66b3a
refs/heads/master
2023-05-05T07:47:11.293000
2019-07-21T12:39:48
2019-07-21T12:39:48
234,906,524
0
0
null
false
2023-04-14T17:11:46
2020-01-19T13:39:52
2020-04-09T15:58:28
2023-04-14T17:11:45
102,317
0
0
2
null
false
false
package net.zjcclims.service.construction; import net.zjcclims.domain.CProjectStatus; import java.util.List; import java.util.Set; /** * Spring service that handles CRUD requests for CProjectStatus entities * */ public interface CProjectStatusService { /** * Save an existing CProjectStatus entity * */ public void saveCProjectStatus(CProjectStatus cprojectstatus); /** * Return a count of all CProjectStatus entity * */ public Integer countCProjectStatuss(); /** * Return all CProjectStatus entity * */ public List<CProjectStatus> findAllCProjectStatuss(Integer startResult, Integer maxRows); /** */ public CProjectStatus findCProjectStatusByPrimaryKey(Integer id); /** * Delete an existing CProjectStatus entity * */ public void deleteCProjectStatus(CProjectStatus cprojectstatus_1); /** * Load an existing CProjectStatus entity * */ public Set<CProjectStatus> loadCProjectStatuss(); }
UTF-8
Java
951
java
CProjectStatusService.java
Java
[]
null
[]
package net.zjcclims.service.construction; import net.zjcclims.domain.CProjectStatus; import java.util.List; import java.util.Set; /** * Spring service that handles CRUD requests for CProjectStatus entities * */ public interface CProjectStatusService { /** * Save an existing CProjectStatus entity * */ public void saveCProjectStatus(CProjectStatus cprojectstatus); /** * Return a count of all CProjectStatus entity * */ public Integer countCProjectStatuss(); /** * Return all CProjectStatus entity * */ public List<CProjectStatus> findAllCProjectStatuss(Integer startResult, Integer maxRows); /** */ public CProjectStatus findCProjectStatusByPrimaryKey(Integer id); /** * Delete an existing CProjectStatus entity * */ public void deleteCProjectStatus(CProjectStatus cprojectstatus_1); /** * Load an existing CProjectStatus entity * */ public Set<CProjectStatus> loadCProjectStatuss(); }
951
0.739222
0.73817
49
18.428572
24.243662
90
false
false
0
0
0
0
0
0
0.795918
false
false
13
e3c1cca0f7c78f8d9856f17c28dbbb33e5ff8c11
223,338,338,857
9098e2960400321a8a77c785912ae53f1381941f
/elastic_MonIII/src/main/java/com/trgr/elasticMon/command/PageVisitorBase.java
dddb255bf571dd25164aac415311b0f1dc2ffd72
[]
no_license
vikas-flutter/Plastic
https://github.com/vikas-flutter/Plastic
1c9a5d55732ca1069b465c509c8935f4421e413f
c092ebbb8d5d4628e3068c681dfc319e175c6bd9
refs/heads/master
2023-02-22T20:02:48.987000
2017-07-06T04:44:47
2017-07-06T04:44:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.trgr.elasticMon.command; public class PageVisitorBase implements Command{ private final PageVisit pageVis; public PageVisitorBase(PageVisit rece){ pageVis=rece; } @Override public Object execute() { return null; } @Override public Object execute(final Object obj) { return pageVis.Action(obj); } }
UTF-8
Java
331
java
PageVisitorBase.java
Java
[]
null
[]
package com.trgr.elasticMon.command; public class PageVisitorBase implements Command{ private final PageVisit pageVis; public PageVisitorBase(PageVisit rece){ pageVis=rece; } @Override public Object execute() { return null; } @Override public Object execute(final Object obj) { return pageVis.Action(obj); } }
331
0.746224
0.746224
20
15.55
16.384367
48
false
false
0
0
0
0
0
0
1.05
false
false
13
88ecbf6ebdc25300fdb4eab379000c7662610011
21,595,095,581,372
dadb63dc41f4ae4b6d0924c76d577f07af90e1e5
/src/org/mbakkokom/simpleregex/interpreter/ast/entities/SetEntity.java
98982aec04017d18467ce7da32da87191d6f9b99
[]
no_license
mbakkokom/fla_regex
https://github.com/mbakkokom/fla_regex
0fe2d45a7cd75c03ad71dd1e694699d4aae64ce9
73fc7d36ff53302894514cefd2233dbf56af3fee
refs/heads/master
2020-04-24T00:04:20.664000
2019-02-27T14:47:30
2019-02-27T14:54:46
171,554,404
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.mbakkokom.simpleregex.interpreter.ast.entities; import java.util.ArrayList; import java.util.Arrays; public class SetEntity extends ArrayList<Entity> implements Entity { public SetEntity() { super(); } public SetEntity(Entity[] nodes) { super(Arrays.asList(nodes)); } public static SetEntity fromAppendSets(SetEntity s1, SetEntity s2) { SetEntity n = new SetEntity((Entity[]) s1.toArray()); n.addAll((Entity[]) s2.toArray()); return n; } public void addAll(Entity[] nodes) { this.addAll(Arrays.asList(nodes)); } public void replaceLastEntity(Entity replaceWith) { this.set(this.size() - 1, replaceWith); } public boolean replaceLastEntityOf(Entity target, Entity replaceWith) { int i; if ((i = this.lastIndexOf(target)) == -1) { return false; } else { this.set(i, replaceWith); return true; } } public EntityType type() { return EntityType.ENTITY_SET; } public int precedence() { return 1; } }
UTF-8
Java
1,120
java
SetEntity.java
Java
[]
null
[]
package org.mbakkokom.simpleregex.interpreter.ast.entities; import java.util.ArrayList; import java.util.Arrays; public class SetEntity extends ArrayList<Entity> implements Entity { public SetEntity() { super(); } public SetEntity(Entity[] nodes) { super(Arrays.asList(nodes)); } public static SetEntity fromAppendSets(SetEntity s1, SetEntity s2) { SetEntity n = new SetEntity((Entity[]) s1.toArray()); n.addAll((Entity[]) s2.toArray()); return n; } public void addAll(Entity[] nodes) { this.addAll(Arrays.asList(nodes)); } public void replaceLastEntity(Entity replaceWith) { this.set(this.size() - 1, replaceWith); } public boolean replaceLastEntityOf(Entity target, Entity replaceWith) { int i; if ((i = this.lastIndexOf(target)) == -1) { return false; } else { this.set(i, replaceWith); return true; } } public EntityType type() { return EntityType.ENTITY_SET; } public int precedence() { return 1; } }
1,120
0.601786
0.595536
47
22.829786
22.107397
75
false
false
0
0
0
0
0
0
0.425532
false
false
13
503c8afeae92a275ad3be77c9c81b30d6c1e40d1
2,894,807,987,286
0914d1c67dbf0c26e5ea7011fb24444d2a599d78
/src/main/java/com/hjljy/blog/service/system/friends/FriendsServiceImpl.java
71afcc7b085a9de9aa94af615dd222ef5e12cdee
[]
no_license
hjljy/blog
https://github.com/hjljy/blog
5f9dd53cffa08381a1ccb206b5afea0b24232e58
f3416f2542f0ea4da25021bd1b13a3e1bbde1cbc
refs/heads/master
2020-04-07T06:41:24.165000
2019-01-24T06:46:22
2019-01-24T06:46:22
158,146,867
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hjljy.blog.service.system.friends; import com.hjljy.blog.entity.system.Friends; import com.hjljy.blog.service.base.BaseServiceImpl; import org.springframework.stereotype.Service; /** * @Auther: HJLJY * @Date: 2019/1/9 0009 16:56 * @Description: */ @Service public class FriendsServiceImpl extends BaseServiceImpl<Friends> implements FriendsService { }
UTF-8
Java
370
java
FriendsServiceImpl.java
Java
[ { "context": "ringframework.stereotype.Service;\n\n/**\n * @Auther: HJLJY\n * @Date: 2019/1/9 0009 16:56\n * @Description:\n *", "end": 214, "score": 0.9996371269226074, "start": 209, "tag": "USERNAME", "value": "HJLJY" } ]
null
[]
package com.hjljy.blog.service.system.friends; import com.hjljy.blog.entity.system.Friends; import com.hjljy.blog.service.base.BaseServiceImpl; import org.springframework.stereotype.Service; /** * @Auther: HJLJY * @Date: 2019/1/9 0009 16:56 * @Description: */ @Service public class FriendsServiceImpl extends BaseServiceImpl<Friends> implements FriendsService { }
370
0.783784
0.745946
14
25.428572
26.253473
92
false
false
0
0
0
0
0
0
0.285714
false
false
13
09c272dec8e81035223be548e7039141a11b27eb
27,934,467,312,288
d220657464c1922dc145e907bbbb1012df032116
/src/main/java/BaseActions.java
5dee7b63457cc01fec2f1db86b1abe4eeed019c6
[]
no_license
nargizhuss/LiquibaseTests
https://github.com/nargizhuss/LiquibaseTests
f3370db78f59085aab710602bc1ea851aaa62f15
5a4c8a566ff34c3ddd411b6b824489a55ad568c2
refs/heads/master
2023-01-13T00:11:24.740000
2020-11-18T14:56:41
2020-11-18T14:56:41
313,969,798
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.apache.commons.lang3.RandomStringUtils; public class BaseActions { protected WebDriver driver; protected WebDriverWait wait; public BaseActions(WebDriver driver, WebDriverWait wait) { this.driver = driver; this.wait = wait; } public void ajaxClick(WebElement element) { ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element); } public void ajaxClick(By by) { wait.until(ExpectedConditions.presenceOfElementLocated(by)); wait.until(ExpectedConditions.elementToBeClickable(by)); ajaxClick(driver.findElement(by)); } public void ajaxSendKeys(By locator,int index, String text){ ((JavascriptExecutor)driver).executeScript("arguments[0].setAttribute('value','"+ text +"')",driver.findElements(locator).get(index)); } public static String generateNewWord(int length) { return RandomStringUtils.random(length, "abcnjdfllgl"); } }
UTF-8
Java
1,241
java
BaseActions.java
Java
[]
null
[]
import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.apache.commons.lang3.RandomStringUtils; public class BaseActions { protected WebDriver driver; protected WebDriverWait wait; public BaseActions(WebDriver driver, WebDriverWait wait) { this.driver = driver; this.wait = wait; } public void ajaxClick(WebElement element) { ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element); } public void ajaxClick(By by) { wait.until(ExpectedConditions.presenceOfElementLocated(by)); wait.until(ExpectedConditions.elementToBeClickable(by)); ajaxClick(driver.findElement(by)); } public void ajaxSendKeys(By locator,int index, String text){ ((JavascriptExecutor)driver).executeScript("arguments[0].setAttribute('value','"+ text +"')",driver.findElements(locator).get(index)); } public static String generateNewWord(int length) { return RandomStringUtils.random(length, "abcnjdfllgl"); } }
1,241
0.700242
0.697019
40
29.700001
33.359558
142
false
false
0
0
0
0
0
0
0.625
false
false
13
202375c1ea8e5bc78467e6a8058d00bee5332472
29,008,209,136,757
474ba263b9ddf211613f6ef6a03744696350349a
/designPatter/src/main/java/com/jimg/strategy/duck/MallardDuck.java
604952b989bb3ca12c9574c843db9e98242ddb67
[ "MIT" ]
permissive
Unchastity/DesignPattern
https://github.com/Unchastity/DesignPattern
70651065d3d10241f5ddaa3c9a40cb79db0f00e2
88d348ea1b98a2252d7afc38c189dea416dc46ae
refs/heads/master
2021-09-09T03:30:06.836000
2018-03-13T14:07:05
2018-03-13T14:07:05
109,199,610
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jimg.strategy.duck; import com.jimg.strategy.duck.fly.flyImpl.FlyWithWings; import com.jimg.strategy.duck.quack.quackImpl.Quack; public class MallardDuck extends Duck { public MallardDuck() { flyBehavior = new FlyWithWings(); quackBehavior = new Quack(); } @Override public void swim() { System.out.println("I'm mallard duck, and can swim"); } @Override public void display() { System.out.println("I'm mallard duck"); } }
UTF-8
Java
503
java
MallardDuck.java
Java
[]
null
[]
package com.jimg.strategy.duck; import com.jimg.strategy.duck.fly.flyImpl.FlyWithWings; import com.jimg.strategy.duck.quack.quackImpl.Quack; public class MallardDuck extends Duck { public MallardDuck() { flyBehavior = new FlyWithWings(); quackBehavior = new Quack(); } @Override public void swim() { System.out.println("I'm mallard duck, and can swim"); } @Override public void display() { System.out.println("I'm mallard duck"); } }
503
0.654076
0.654076
22
21.863636
20.222164
61
false
false
0
0
0
0
0
0
0.363636
false
false
13
a1e73af098ea5c91e453a26544df404bb354c3cc
5,978,594,503,518
f8b4ad6fa69a8dae265c4351748c4a4cda855898
/src/com/sony/npc/workflow/common/NPCProcessRejectAction.java
91e75794fafa1b961e55c9b4dac46fab73abee7f
[]
no_license
sprinng/newsisAP
https://github.com/sprinng/newsisAP
f614611a9212b41d53de79ac6c0d9345c4c0def4
8c853bfdcdc639af174a116275e6a1de1ce11c38
refs/heads/master
2016-08-04T15:51:16.746000
2015-07-08T07:14:44
2015-07-08T07:14:44
35,209,366
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sony.npc.workflow.common; import java.util.ArrayList; import java.util.Map; import org.apache.log4j.Logger; import cn.com.sony.newsis.common.mail.SendMail; import cn.com.sony.newsis.common.tools.CommonSearch; import cn.com.sony.newsis.util.SpringContextUtil; import cn.com.sony.newsis.util.action.ControlAction; import com.sony.npc.workflow.WorkFlowConstant; import com.sony.npc.workflow.bo.WorkFlowBo; import com.sony.npc.workflow.business.bo.NpcStockAdjustBo; import com.sony.npc.workflow.business.pojo.NpcStockAdjust; import com.sony.npc.workflow.pojo.NpcWorkFlow; import com.sony.npc.workflow.pojo.NpcWorkFlowInfo; import com.ibm.bpe.WorkflowException; import com.ibm.bpe.core.action.IAction; import com.ibm.bpe.core.exec.ContextInstance; public class NPCProcessRejectAction implements IAction{ private Logger logger = Logger.getLogger(getClass()); WorkFlowBo workFlowBo= new WorkFlowBo(); NpcStockAdjustBo stockAdjustBo=new NpcStockAdjustBo(); private CommonSearch cs = ((CommonSearch) SpringContextUtil .getBean("commonSearch")); @Override public Object execute(ContextInstance context, Map map) throws WorkflowException { String processID=(String)context.getTransientVarValue("varWorkFlowNo"); String processType=(String)context.getTransientVarValue("varProcessType"); String adjustId=(String)context.getTransientVarValue("varAdjustId"); String userId=(String)context.getTransientVarValue("varUserId"); String orgCode=(String)context.getTransientVarValue("varOrgCode"); try{ if(processType.equals(WorkFlowConstant.NPC_STOCK_FLOW_TEMP)){ NpcStockAdjust npcStockAdjustment=stockAdjustBo.getNpcStockAdjust(Long.valueOf(processID)); logger.info("comming to NPC stock flow invoke back method"); workFlowBo.doProcessEnd(false, processID, WorkFlowConstant.NPC_STOCK_FLOW,Long.valueOf(orgCode)); NpcStockAdjustBo stockAdjustBo=new NpcStockAdjustBo(); stockAdjustBo.approveReject(adjustId, "appN",Long.valueOf(userId)); //TODO 回调方法。 boolean IsSend=cs.IsSendMail("N"); // System.out.println("是否发送邮件:"+IsSend); if(IsSend){ // System.out.println("Npc stock approved flow send mail........."); //---------Email通知--------------- ArrayList al = new ArrayList(); al.add(0,"C");//表示为启动邮件 al.add(1,npcStockAdjustment.getAdjustId());//流程ID al.add(2,"N");//流程类型 al.add(3,npcStockAdjustment.getAppBy());//流程启动者 al.add(4,new Boolean(false)); //审批结果,成功 al.add(5,npcStockAdjustment); //申请原始Form SendMail sm = new SendMail(); sm.sendMail(al); } //TODO 邮件发送 } }catch(Exception ex){ throw new WorkflowException(ex.getMessage()); } return null; } }
UTF-8
Java
2,871
java
NPCProcessRejectAction.java
Java
[]
null
[]
package com.sony.npc.workflow.common; import java.util.ArrayList; import java.util.Map; import org.apache.log4j.Logger; import cn.com.sony.newsis.common.mail.SendMail; import cn.com.sony.newsis.common.tools.CommonSearch; import cn.com.sony.newsis.util.SpringContextUtil; import cn.com.sony.newsis.util.action.ControlAction; import com.sony.npc.workflow.WorkFlowConstant; import com.sony.npc.workflow.bo.WorkFlowBo; import com.sony.npc.workflow.business.bo.NpcStockAdjustBo; import com.sony.npc.workflow.business.pojo.NpcStockAdjust; import com.sony.npc.workflow.pojo.NpcWorkFlow; import com.sony.npc.workflow.pojo.NpcWorkFlowInfo; import com.ibm.bpe.WorkflowException; import com.ibm.bpe.core.action.IAction; import com.ibm.bpe.core.exec.ContextInstance; public class NPCProcessRejectAction implements IAction{ private Logger logger = Logger.getLogger(getClass()); WorkFlowBo workFlowBo= new WorkFlowBo(); NpcStockAdjustBo stockAdjustBo=new NpcStockAdjustBo(); private CommonSearch cs = ((CommonSearch) SpringContextUtil .getBean("commonSearch")); @Override public Object execute(ContextInstance context, Map map) throws WorkflowException { String processID=(String)context.getTransientVarValue("varWorkFlowNo"); String processType=(String)context.getTransientVarValue("varProcessType"); String adjustId=(String)context.getTransientVarValue("varAdjustId"); String userId=(String)context.getTransientVarValue("varUserId"); String orgCode=(String)context.getTransientVarValue("varOrgCode"); try{ if(processType.equals(WorkFlowConstant.NPC_STOCK_FLOW_TEMP)){ NpcStockAdjust npcStockAdjustment=stockAdjustBo.getNpcStockAdjust(Long.valueOf(processID)); logger.info("comming to NPC stock flow invoke back method"); workFlowBo.doProcessEnd(false, processID, WorkFlowConstant.NPC_STOCK_FLOW,Long.valueOf(orgCode)); NpcStockAdjustBo stockAdjustBo=new NpcStockAdjustBo(); stockAdjustBo.approveReject(adjustId, "appN",Long.valueOf(userId)); //TODO 回调方法。 boolean IsSend=cs.IsSendMail("N"); // System.out.println("是否发送邮件:"+IsSend); if(IsSend){ // System.out.println("Npc stock approved flow send mail........."); //---------Email通知--------------- ArrayList al = new ArrayList(); al.add(0,"C");//表示为启动邮件 al.add(1,npcStockAdjustment.getAdjustId());//流程ID al.add(2,"N");//流程类型 al.add(3,npcStockAdjustment.getAppBy());//流程启动者 al.add(4,new Boolean(false)); //审批结果,成功 al.add(5,npcStockAdjustment); //申请原始Form SendMail sm = new SendMail(); sm.sendMail(al); } //TODO 邮件发送 } }catch(Exception ex){ throw new WorkflowException(ex.getMessage()); } return null; } }
2,871
0.725081
0.722562
70
37.700001
24.883356
100
false
false
0
0
0
0
0
0
2.542857
false
false
13
22631b82436e351cb8b08055b273cba01678b8e7
27,479,200,798,869
b27a23becaa220af480821ff50f74c74aa0a5ca7
/src/main/java/com/songoda/skyblock/command/commands/admin/SetAlwaysLoadedCommand.java
c388a822598a1008b95d370692b2d1592652eab2
[ "LicenseRef-scancode-other-permissive" ]
permissive
dirtysololil/FabledSkyBlock
https://github.com/dirtysololil/FabledSkyBlock
febc36c949a5de389daa84e5afa7ceb705a45e44
6bdfb0ace418c9148dca8dc8644b002b6ea76253
refs/heads/master
2021-05-19T14:20:17.860000
2020-03-31T11:23:56
2020-03-31T11:23:56
251,753,227
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.songoda.skyblock.command.commands.admin; import java.io.File; import java.util.UUID; import com.songoda.core.compatibility.CompatibleSound; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import com.songoda.skyblock.command.SubCommand; import com.songoda.skyblock.config.FileManager; import com.songoda.skyblock.config.FileManager.Config; import com.songoda.skyblock.island.Island; import com.songoda.skyblock.island.IslandManager; import com.songoda.skyblock.message.MessageManager; import com.songoda.skyblock.playerdata.PlayerDataManager; import com.songoda.skyblock.sound.SoundManager; import com.songoda.skyblock.utils.player.OfflinePlayer; public class SetAlwaysLoadedCommand extends SubCommand { @Override public void onCommandByPlayer(Player player, String[] args) { onCommand(player, args); } @Override public void onCommandByConsole(ConsoleCommandSender sender, String[] args) { onCommand(sender, args); } public void onCommand(CommandSender sender, String[] args) { FileManager fileManager = skyblock.getFileManager(); Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); FileConfiguration configLoad = config.getFileConfiguration(); MessageManager messageManager = skyblock.getMessageManager(); if (args.length == 0) { messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.No-Player-Input.Message")); return; } PlayerDataManager playerDataManager = skyblock.getPlayerDataManager(); IslandManager islandManager = skyblock.getIslandManager(); SoundManager soundManager = skyblock.getSoundManager(); if (args.length == 1) { Player targetPlayer = Bukkit.getServer().getPlayer(args[0]); UUID islandOwnerUUID; if (targetPlayer == null) { OfflinePlayer targetPlayerOffline = new OfflinePlayer(args[0]); islandOwnerUUID = targetPlayerOffline.getOwner(); } else { islandOwnerUUID = playerDataManager.getPlayerData(targetPlayer).getOwner(); } if (islandManager.containsIsland(islandOwnerUUID)) { Island island = islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(islandOwnerUUID)); if (island.isAlwaysLoaded()) { messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.IsOff.Message")); soundManager.playSound(sender, CompatibleSound.BLOCK_ANVIL_LAND.getSound(), 1.0F, 1.0F); island.setAlwaysLoaded(false); } else { messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.IsOn.Message")); soundManager.playSound(sender, CompatibleSound.BLOCK_ANVIL_LAND.getSound(), 1.0F, 1.0F); island.setAlwaysLoaded(true); } } } } @Override public String getName() { return "setalwaysloaded"; } @Override public String getInfoMessagePath() { return "Command.Island.Admin.SetAlwaysLoaded.Info.Message"; } @Override public String[] getAliases() { return new String[0]; } @Override public String[] getArguments() { return new String[0]; } }
UTF-8
Java
3,708
java
SetAlwaysLoadedCommand.java
Java
[]
null
[]
package com.songoda.skyblock.command.commands.admin; import java.io.File; import java.util.UUID; import com.songoda.core.compatibility.CompatibleSound; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import com.songoda.skyblock.command.SubCommand; import com.songoda.skyblock.config.FileManager; import com.songoda.skyblock.config.FileManager.Config; import com.songoda.skyblock.island.Island; import com.songoda.skyblock.island.IslandManager; import com.songoda.skyblock.message.MessageManager; import com.songoda.skyblock.playerdata.PlayerDataManager; import com.songoda.skyblock.sound.SoundManager; import com.songoda.skyblock.utils.player.OfflinePlayer; public class SetAlwaysLoadedCommand extends SubCommand { @Override public void onCommandByPlayer(Player player, String[] args) { onCommand(player, args); } @Override public void onCommandByConsole(ConsoleCommandSender sender, String[] args) { onCommand(sender, args); } public void onCommand(CommandSender sender, String[] args) { FileManager fileManager = skyblock.getFileManager(); Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); FileConfiguration configLoad = config.getFileConfiguration(); MessageManager messageManager = skyblock.getMessageManager(); if (args.length == 0) { messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.No-Player-Input.Message")); return; } PlayerDataManager playerDataManager = skyblock.getPlayerDataManager(); IslandManager islandManager = skyblock.getIslandManager(); SoundManager soundManager = skyblock.getSoundManager(); if (args.length == 1) { Player targetPlayer = Bukkit.getServer().getPlayer(args[0]); UUID islandOwnerUUID; if (targetPlayer == null) { OfflinePlayer targetPlayerOffline = new OfflinePlayer(args[0]); islandOwnerUUID = targetPlayerOffline.getOwner(); } else { islandOwnerUUID = playerDataManager.getPlayerData(targetPlayer).getOwner(); } if (islandManager.containsIsland(islandOwnerUUID)) { Island island = islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(islandOwnerUUID)); if (island.isAlwaysLoaded()) { messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.IsOff.Message")); soundManager.playSound(sender, CompatibleSound.BLOCK_ANVIL_LAND.getSound(), 1.0F, 1.0F); island.setAlwaysLoaded(false); } else { messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.IsOn.Message")); soundManager.playSound(sender, CompatibleSound.BLOCK_ANVIL_LAND.getSound(), 1.0F, 1.0F); island.setAlwaysLoaded(true); } } } } @Override public String getName() { return "setalwaysloaded"; } @Override public String getInfoMessagePath() { return "Command.Island.Admin.SetAlwaysLoaded.Info.Message"; } @Override public String[] getAliases() { return new String[0]; } @Override public String[] getArguments() { return new String[0]; } }
3,708
0.669364
0.665588
102
35.35294
31.029602
110
false
false
0
0
0
0
0
0
0.588235
false
false
13
012ba42c4575fc35eda3720059861b011af9f68d
5,411,658,799,493
36e229e751ce9b23fe864b097f3971fefd2c0c10
/app/src/main/java/com/jprarama/courtcounterapp/CourtScoreFragment.java
474a31c9fa73b1770809c52897330d84fc59d55f
[]
no_license
jrarama/nd803_02_CourtCounterApp
https://github.com/jrarama/nd803_02_CourtCounterApp
4f7521fd39b431dbfbe12eeea9c4323176451f67
7d1d0a6d076a1e8b36c05f7e8648ae8dd8a9def2
refs/heads/master
2021-01-09T20:11:46.423000
2016-07-01T14:57:06
2016-07-01T14:57:06
62,331,857
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jprarama.courtcounterapp; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; /** * Created by joshua on 1/7/16. */ public class CourtScoreFragment extends Fragment { private TextView tvTeamName; private TextView tvScore; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.court_score_item, container, false); tvTeamName = (TextView) rootView.findViewById(R.id.teamName); tvScore = (TextView) rootView.findViewById(R.id.score); Button btn1Point = (Button) rootView.findViewById(R.id.btn1point); Button btn2Points = (Button) rootView.findViewById(R.id.btn2points); Button btn3Points = (Button) rootView.findViewById(R.id.btn3points); btn1Point.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increaseScore(1); } }); btn2Points.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increaseScore(2); } }); btn3Points.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increaseScore(3); } }); return rootView; } private void increaseScore(int points) { int score = Integer.parseInt(tvScore.getText().toString().trim()) + points; String newScore = String.format("%02d", score); tvScore.setText(newScore); } public TextView getTvTeamName() { return tvTeamName; } public void resetScore() { tvScore.setText(getString(R.string.score)); } }
UTF-8
Java
2,051
java
CourtScoreFragment.java
Java
[ { "context": "import android.widget.TextView;\n\n/**\n * Created by joshua on 1/7/16.\n */\npublic class CourtScoreFragment ex", "end": 329, "score": 0.753431499004364, "start": 323, "tag": "NAME", "value": "joshua" } ]
null
[]
package com.jprarama.courtcounterapp; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; /** * Created by joshua on 1/7/16. */ public class CourtScoreFragment extends Fragment { private TextView tvTeamName; private TextView tvScore; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.court_score_item, container, false); tvTeamName = (TextView) rootView.findViewById(R.id.teamName); tvScore = (TextView) rootView.findViewById(R.id.score); Button btn1Point = (Button) rootView.findViewById(R.id.btn1point); Button btn2Points = (Button) rootView.findViewById(R.id.btn2points); Button btn3Points = (Button) rootView.findViewById(R.id.btn3points); btn1Point.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increaseScore(1); } }); btn2Points.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increaseScore(2); } }); btn3Points.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increaseScore(3); } }); return rootView; } private void increaseScore(int points) { int score = Integer.parseInt(tvScore.getText().toString().trim()) + points; String newScore = String.format("%02d", score); tvScore.setText(newScore); } public TextView getTvTeamName() { return tvTeamName; } public void resetScore() { tvScore.setText(getString(R.string.score)); } }
2,051
0.649439
0.640176
68
29.161764
25.715416
103
false
false
0
0
0
0
0
0
0.5
false
false
13
24eae8999aebe892e40fa68c14f77967a535da2b
7,499,012,919,558
ca7198884285b3a40a756a0541a6c2865f15b900
/code/LeetCode/src/binarysearch/DivideTwoIntegers.java
32ca2091282c36dfa65dad2b25b658b962f4dbbf
[]
no_license
zgpeace/awesome-java-leetcode
https://github.com/zgpeace/awesome-java-leetcode
bce273a69dd1f9cac0017b05c1eac9d52d39e42d
c6fcafdf0bb1eeb7e3220ed6a85143489c5791a8
refs/heads/master
2021-06-06T06:06:03.107000
2020-06-14T08:09:42
2020-06-14T08:09:42
144,134,083
1
0
null
true
2018-08-09T09:55:11
2018-08-09T09:55:11
2018-08-09T06:19:29
2018-05-17T03:40:14
472
0
0
0
null
false
null
package binarysearch; // https://leetcode.com/problems/divide-two-integers/ public class DivideTwoIntegers { //int maxOfHalf = Integer.MAX_VALUE >> 1; // //public static void main(String[] args) { // DivideTwoIntegers obj = new DivideTwoIntegers(); // int result = obj.divide(-2147483648, -1); // System.out.println("result > " + result); //} // //public int divide(int dividend, int divisor) { // // Reduce the problem to positive long integer to make it easier. // // Use long to avoid integer overflow case. // int sign = -1; // if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) { // sign = 1; // } // long ldividend = Math.abs((long)dividend); // long ldivisor = Math.abs((long)divisor); // // // Take care the edge cases. // if (ldivisor == 0) return Integer.MAX_VALUE; // if ((ldividend == 0 || (ldividend < ldivisor))) return 0; // // long lans = ldivide(ldividend, ldivisor); // // int ans; // if (lans > Integer.MAX_VALUE) { // // Handle overflow. // ans = (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; // } else { // ans = (int)((sign == 1) ? lans : -lans); // } // // return ans; //} // //private long ldivide(long ldividend, long ldivisor) { // // Recursion exit condition // if (ldividend < ldivisor) { // return 0; // } // // // Find the largest multiple so that (divisor * multiple <= dividend), // // whereas we are moving with stride 1, 2, 4, 8, 16...2^n for performance reason. // // Think this as a binary search. // long sum = ldivisor; // long multiple = 1; // while ((sum << 1) <= ldividend) { // multiple <<= 1; // sum <<= 1; // } // // // Look for additional value for the multiple from the reminder (dividend - sum) recursively. // return multiple + ldivide(ldividend - sum, ldivisor); //} public int divide(int dividend, int divisor) { //sign int sign = 1; if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) { sign = -1; } // long type long ldividend = Math.abs((long)dividend); long ldivisor = Math.abs((long)divisor); // edge if (ldivisor == 0) { return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; } if (ldividend < ldivisor) { return 0; } long result = ldivide(ldividend, ldivisor); if (result > Integer.MAX_VALUE) { return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; } int intResult = (int)result; return (sign == 1) ? intResult : - intResult; } public long ldivide(long ldividend, long ldivisor) { // exit condition if (ldividend < ldivisor) { return 0; } long multiple = 1; long sum = ldivisor; while ((sum << 1) <= ldividend) { sum <<= 1; multiple <<= 1; } return multiple + ldivide(ldividend - sum, ldivisor); } }
UTF-8
Java
2,926
java
DivideTwoIntegers.java
Java
[]
null
[]
package binarysearch; // https://leetcode.com/problems/divide-two-integers/ public class DivideTwoIntegers { //int maxOfHalf = Integer.MAX_VALUE >> 1; // //public static void main(String[] args) { // DivideTwoIntegers obj = new DivideTwoIntegers(); // int result = obj.divide(-2147483648, -1); // System.out.println("result > " + result); //} // //public int divide(int dividend, int divisor) { // // Reduce the problem to positive long integer to make it easier. // // Use long to avoid integer overflow case. // int sign = -1; // if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) { // sign = 1; // } // long ldividend = Math.abs((long)dividend); // long ldivisor = Math.abs((long)divisor); // // // Take care the edge cases. // if (ldivisor == 0) return Integer.MAX_VALUE; // if ((ldividend == 0 || (ldividend < ldivisor))) return 0; // // long lans = ldivide(ldividend, ldivisor); // // int ans; // if (lans > Integer.MAX_VALUE) { // // Handle overflow. // ans = (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; // } else { // ans = (int)((sign == 1) ? lans : -lans); // } // // return ans; //} // //private long ldivide(long ldividend, long ldivisor) { // // Recursion exit condition // if (ldividend < ldivisor) { // return 0; // } // // // Find the largest multiple so that (divisor * multiple <= dividend), // // whereas we are moving with stride 1, 2, 4, 8, 16...2^n for performance reason. // // Think this as a binary search. // long sum = ldivisor; // long multiple = 1; // while ((sum << 1) <= ldividend) { // multiple <<= 1; // sum <<= 1; // } // // // Look for additional value for the multiple from the reminder (dividend - sum) recursively. // return multiple + ldivide(ldividend - sum, ldivisor); //} public int divide(int dividend, int divisor) { //sign int sign = 1; if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) { sign = -1; } // long type long ldividend = Math.abs((long)dividend); long ldivisor = Math.abs((long)divisor); // edge if (ldivisor == 0) { return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; } if (ldividend < ldivisor) { return 0; } long result = ldivide(ldividend, ldivisor); if (result > Integer.MAX_VALUE) { return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; } int intResult = (int)result; return (sign == 1) ? intResult : - intResult; } public long ldivide(long ldividend, long ldivisor) { // exit condition if (ldividend < ldivisor) { return 0; } long multiple = 1; long sum = ldivisor; while ((sum << 1) <= ldividend) { sum <<= 1; multiple <<= 1; } return multiple + ldivide(ldividend - sum, ldivisor); } }
2,926
0.570745
0.553315
102
27.686274
23.445799
99
false
false
0
0
0
0
0
0
0.568627
false
false
13
f0a5d0dc281602490cd4a157d3c035e7ebc07c9e
17,308,718,221,671
4b3a5c70ea0a47da01b1dd14ed0d42b7cb46fc13
/src/test/java/be/ugent/rml/SourceNotPresentTest.java
56c177847ca1a20853f4b2377467d54ffb5730c2
[ "MIT", "LGPL-3.0-only", "EPL-1.0", "MPL-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RMLio/rmlmapper-java
https://github.com/RMLio/rmlmapper-java
02d1b650c6af0e869a9fbddcc060bbbbd1b2cb24
c2109d5edcf730b6342f8c5c23e297b368327c1d
refs/heads/master
2023-08-30T07:38:10.078000
2023-07-06T08:48:55
2023-07-06T08:48:55
138,707,242
137
68
MIT
false
2023-07-28T11:10:14
2018-06-26T08:22:17
2023-07-24T02:50:11
2023-07-28T11:08:11
88,503
130
57
54
Java
false
false
package be.ugent.rml; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.URL; import static org.junit.jupiter.api.Assertions.assertThrows; public class SourceNotPresentTest extends TestFunctionCore{ @Test public void evaluate_1035_CSV() throws Exception { Executor executor = this.createExecutor("./test-cases/RMLTC1035-CSV/mapping.ttl"); ClassLoader classLoader = getClass().getClassLoader(); // execute mapping file URL url = classLoader.getResource("./test-cases/RMLTC1035-CSV"); assert url != null; assertThrows(IOException.class,() -> executor.verifySources( url.getPath())); } @Test public void evaluate_1036_CSV() throws Exception { Executor executor = this.createExecutor("./test-cases/RMLTC1036-CSV/mapping.ttl"); ClassLoader classLoader = getClass().getClassLoader(); // execute mapping file URL url = classLoader.getResource("./test-cases/RMLTC1036-CSV"); assert url != null; executor.verifySources( url.getPath()); } }
UTF-8
Java
1,088
java
SourceNotPresentTest.java
Java
[]
null
[]
package be.ugent.rml; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.URL; import static org.junit.jupiter.api.Assertions.assertThrows; public class SourceNotPresentTest extends TestFunctionCore{ @Test public void evaluate_1035_CSV() throws Exception { Executor executor = this.createExecutor("./test-cases/RMLTC1035-CSV/mapping.ttl"); ClassLoader classLoader = getClass().getClassLoader(); // execute mapping file URL url = classLoader.getResource("./test-cases/RMLTC1035-CSV"); assert url != null; assertThrows(IOException.class,() -> executor.verifySources( url.getPath())); } @Test public void evaluate_1036_CSV() throws Exception { Executor executor = this.createExecutor("./test-cases/RMLTC1036-CSV/mapping.ttl"); ClassLoader classLoader = getClass().getClassLoader(); // execute mapping file URL url = classLoader.getResource("./test-cases/RMLTC1036-CSV"); assert url != null; executor.verifySources( url.getPath()); } }
1,088
0.685662
0.663603
34
31
29.826952
90
false
false
0
0
0
0
0
0
0.470588
false
false
13
d006b214ab3d6c8ec7b460b1f0c4d7e02012cf54
22,144,851,387,989
af942d7dfef0838e5eff1f27fc5d57bdfae534c1
/src/Modelo/Inserir.java
07f1f083f9aece8f689cb88c72284bdffe2103d0
[]
no_license
rafaelneto2/FitSociety
https://github.com/rafaelneto2/FitSociety
cd2e280930af40a4ec2e2be8759bcb9a23ea2bc6
f9e8bbdcd0a4c07c056e9b00cc93d685176be67e
refs/heads/master
2021-01-19T23:32:35.971000
2017-11-30T19:13:11
2017-11-30T19:13:11
88,990,446
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Modelo; /** * * @author Alfredo Myranda */ public class Inserir { private String muculo; private String exercicio; private int rep; private int descanso; private int serie; public String getMuculo() { return muculo; } public void setMuculo(String muculo) { this.muculo = muculo; } public String getExercicio() { return exercicio; } public void setExercicio(String exercicio) { this.exercicio = exercicio; } public int getRep() { return rep; } public void setRep(int rep) { this.rep = rep; } public int getDescanso() { return descanso; } public void setDescanso(int descanso) { this.descanso = descanso; } public int getSerie() { return serie; } public void setSerie(int serie) { this.serie = serie; } }
UTF-8
Java
1,148
java
Inserir.java
Java
[ { "context": "itor.\r\n */\r\npackage Modelo;\r\n\r\n/**\r\n *\r\n * @author Alfredo Myranda\r\n */\r\npublic class Inserir {\r\n private String ", "end": 244, "score": 0.9998860359191895, "start": 229, "tag": "NAME", "value": "Alfredo Myranda" } ]
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 Modelo; /** * * @author <NAME> */ public class Inserir { private String muculo; private String exercicio; private int rep; private int descanso; private int serie; public String getMuculo() { return muculo; } public void setMuculo(String muculo) { this.muculo = muculo; } public String getExercicio() { return exercicio; } public void setExercicio(String exercicio) { this.exercicio = exercicio; } public int getRep() { return rep; } public void setRep(int rep) { this.rep = rep; } public int getDescanso() { return descanso; } public void setDescanso(int descanso) { this.descanso = descanso; } public int getSerie() { return serie; } public void setSerie(int serie) { this.serie = serie; } }
1,139
0.577526
0.577526
58
17.793104
17.115992
79
false
false
0
0
0
0
0
0
0.327586
false
false
13
2fb28c9aa6dc9de40ceb1900a070e40220c52b50
29,824,252,929,737
1cb9c9d41e72b2703890f90c62379d77c8aa9a49
/src/main/java/com/sarki/micro/controller/ConfigController.java
2dd51077b2a830ac8bba840098071e4a04bebf10
[]
no_license
miguelngansop/sarkifinances
https://github.com/miguelngansop/sarkifinances
bd698d773dfdc63c3a593d336ba0eedc0703ec42
ee249ddef92c1c17a971aa6288d394551c831944
refs/heads/master
2020-05-31T07:58:50.391000
2019-08-05T10:11:08
2019-08-05T10:11:08
190,177,663
4
0
null
false
2019-07-25T16:05:22
2019-06-04T10:12:21
2019-07-25T15:13:20
2019-07-25T16:05:21
106
0
0
0
Java
false
false
package com.sarki.micro.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.sarki.micro.model.Agence; import com.sarki.micro.model.Agent; import com.sarki.micro.repository.AgenceRepository; import com.sarki.micro.repository.AgentRepository; @RestController @RequestMapping("/config") public class ConfigController { @Autowired AgentRepository agentRepo; @Autowired AgenceRepository agenceRepo; // Create a new Agent @PostMapping("/agent/{id}") public Agent createAgent(@Valid @RequestBody Agent a, @PathVariable(value="id") Long agenceId) { Agence agence = agenceRepo.getOne(agenceId); a.setAgence(agence); return agentRepo.save(a); } // Create a new Agence @PostMapping("/agence") public Agence createAgence(@Valid @RequestBody Agence agce) { return agenceRepo.save(agce); } }
UTF-8
Java
1,270
java
ConfigController.java
Java
[]
null
[]
package com.sarki.micro.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.sarki.micro.model.Agence; import com.sarki.micro.model.Agent; import com.sarki.micro.repository.AgenceRepository; import com.sarki.micro.repository.AgentRepository; @RestController @RequestMapping("/config") public class ConfigController { @Autowired AgentRepository agentRepo; @Autowired AgenceRepository agenceRepo; // Create a new Agent @PostMapping("/agent/{id}") public Agent createAgent(@Valid @RequestBody Agent a, @PathVariable(value="id") Long agenceId) { Agence agence = agenceRepo.getOne(agenceId); a.setAgence(agence); return agentRepo.save(a); } // Create a new Agence @PostMapping("/agence") public Agence createAgence(@Valid @RequestBody Agence agce) { return agenceRepo.save(agce); } }
1,270
0.741732
0.741732
42
28.238094
21.85429
65
false
false
0
0
0
0
0
0
1.333333
false
false
13
3cfd6d9784e2cf508d7a3447877d9cc078705b0e
10,359,461,134,443
4f603d88cc29b0c49853afea5c7e3952e70c505a
/app/src/main/java/com/example/vinaykl/bs2/Payment_Submit.java
c6c04ddc08711e61a640b97af2e4628937bb3968
[]
no_license
vinaykl/Medicare-Android-app
https://github.com/vinaykl/Medicare-Android-app
f6e43dd69d738b0e304804e444da34d2a9075671
4388e16d95c205f7cdeb56e4262b29c087decadd
refs/heads/master
2021-01-19T21:33:23.018000
2017-04-18T19:52:14
2017-04-18T19:52:14
88,665,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.vinaykl.bs2; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class Payment_Submit extends AppCompatActivity { String dbName="vkl.db"; SQLiteDatabase db; LoginDataBase_adapter Patient_loginDataBase_Adapter; Button Pay_and_Rate; TextView textView,doc_name,textView6; String val,val1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_payment__submission); Bundle bundle = getIntent().getExtras(); val = bundle.getString("DEMAIL"); val1 = bundle.getString("PEMAIL"); Patient_loginDataBase_Adapter = new LoginDataBase_adapter(this); Patient_loginDataBase_Adapter = Patient_loginDataBase_Adapter.open(); String name = Patient_loginDataBase_Adapter.getPatientName(val1); String docname = Patient_loginDataBase_Adapter.getDoctorName(val); doc_name=(TextView)findViewById(R.id.editDoctorName); doc_name.setText("DOCTOR NAME : "+docname); System.out.println(name); textView=(TextView)findViewById(R.id.textView); textView6=(TextView)findViewById(R.id.textView6); //String amount = get_doctor_amount(name); Pay_and_Rate = (Button)findViewById(R.id.buttonAuthorize); try { db = getApplicationContext().openOrCreateDatabase(dbName, getApplicationContext().MODE_APPEND, null); if (db == null) { Toast.makeText(getApplicationContext(), "Erron in DB0", Toast.LENGTH_SHORT).show(); return; } } catch (SQLException E) { Toast.makeText(this, E.getMessage(), Toast.LENGTH_LONG).show(); } catch (Exception E) { Toast.makeText(getApplicationContext(), E.getMessage(), Toast.LENGTH_SHORT).show(); } finally { //db.endTransaction(); } String d="null"; //String query="SELECT FEES FROM PRESCRIPTION WHERE PATIENTNAME = '"+patient_name+"'"; Cursor c = db.rawQuery("SELECT * FROM PRESCRIPTION WHERE PATIENTNAME = '"+name+"'",null); System.out.println(name); c.moveToFirst(); //while(c.moveToNext()) while(c.isAfterLast() == false) { d = c.getString(c.getColumnIndex("FEES")); System.out.println("string "+d); c.moveToNext(); } c.close(); textView.setText("AMOUNT TO BE PAID : $"+d); Pay_and_Rate.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //Toast.makeText(getApplicationContext(),"Average Rating = "+tot, Toast.LENGTH_SHORT).show(); insert_ratedr(val,val1); Intent intent = new Intent(getApplicationContext(),DoctorRating_Activity.class); Bundle bundle = getIntent().getExtras(); intent.putExtra("DEMAIL", val); String val = bundle.getString("PEMAIL"); intent.putExtra("PEMAIL", val1); startActivity(intent); } }); } public void insert_ratedr(String dname,String pname){ try { db.execSQL("UPDATE APPOINTMENTS SET AMOUNT = 'PAID' WHERE DID = '"+ dname+"'"+"AND PID = '"+pname+"'"); //Toast.makeText(this,"Inserted",Toast.LENGTH_SHORT).show(); Cursor c = db.rawQuery("Select Drating from Doctor Where Demail = '"+dname+"'",null); while(c.moveToNext()) { String d = c.getString(c.getColumnIndex("Drating")); System.out.println("Doctor:" + d); } }catch (Exception e){ e.printStackTrace(); } } public String get_doctor_amount(String patient_name) { String d=""; //String query="SELECT FEES FROM PRESCRIPTION WHERE PATIENTNAME = '"+patient_name+"'"; Cursor c = db.rawQuery("SELECT FEES FROM PRESCRIPTION WHERE PATIENTNAME = '"+patient_name+"'",null); c.moveToFirst(); while(c.moveToNext()) { d = c.getString(c.getColumnIndex("FEES")); } c.close(); return d; } }
UTF-8
Java
4,818
java
Payment_Submit.java
Java
[ { "context": "package com.example.vinaykl.bs2;\r\n\r\nimport android.content.Intent;\r\nimport an", "end": 27, "score": 0.9618081450462341, "start": 20, "tag": "USERNAME", "value": "vinaykl" } ]
null
[]
package com.example.vinaykl.bs2; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class Payment_Submit extends AppCompatActivity { String dbName="vkl.db"; SQLiteDatabase db; LoginDataBase_adapter Patient_loginDataBase_Adapter; Button Pay_and_Rate; TextView textView,doc_name,textView6; String val,val1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_payment__submission); Bundle bundle = getIntent().getExtras(); val = bundle.getString("DEMAIL"); val1 = bundle.getString("PEMAIL"); Patient_loginDataBase_Adapter = new LoginDataBase_adapter(this); Patient_loginDataBase_Adapter = Patient_loginDataBase_Adapter.open(); String name = Patient_loginDataBase_Adapter.getPatientName(val1); String docname = Patient_loginDataBase_Adapter.getDoctorName(val); doc_name=(TextView)findViewById(R.id.editDoctorName); doc_name.setText("DOCTOR NAME : "+docname); System.out.println(name); textView=(TextView)findViewById(R.id.textView); textView6=(TextView)findViewById(R.id.textView6); //String amount = get_doctor_amount(name); Pay_and_Rate = (Button)findViewById(R.id.buttonAuthorize); try { db = getApplicationContext().openOrCreateDatabase(dbName, getApplicationContext().MODE_APPEND, null); if (db == null) { Toast.makeText(getApplicationContext(), "Erron in DB0", Toast.LENGTH_SHORT).show(); return; } } catch (SQLException E) { Toast.makeText(this, E.getMessage(), Toast.LENGTH_LONG).show(); } catch (Exception E) { Toast.makeText(getApplicationContext(), E.getMessage(), Toast.LENGTH_SHORT).show(); } finally { //db.endTransaction(); } String d="null"; //String query="SELECT FEES FROM PRESCRIPTION WHERE PATIENTNAME = '"+patient_name+"'"; Cursor c = db.rawQuery("SELECT * FROM PRESCRIPTION WHERE PATIENTNAME = '"+name+"'",null); System.out.println(name); c.moveToFirst(); //while(c.moveToNext()) while(c.isAfterLast() == false) { d = c.getString(c.getColumnIndex("FEES")); System.out.println("string "+d); c.moveToNext(); } c.close(); textView.setText("AMOUNT TO BE PAID : $"+d); Pay_and_Rate.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //Toast.makeText(getApplicationContext(),"Average Rating = "+tot, Toast.LENGTH_SHORT).show(); insert_ratedr(val,val1); Intent intent = new Intent(getApplicationContext(),DoctorRating_Activity.class); Bundle bundle = getIntent().getExtras(); intent.putExtra("DEMAIL", val); String val = bundle.getString("PEMAIL"); intent.putExtra("PEMAIL", val1); startActivity(intent); } }); } public void insert_ratedr(String dname,String pname){ try { db.execSQL("UPDATE APPOINTMENTS SET AMOUNT = 'PAID' WHERE DID = '"+ dname+"'"+"AND PID = '"+pname+"'"); //Toast.makeText(this,"Inserted",Toast.LENGTH_SHORT).show(); Cursor c = db.rawQuery("Select Drating from Doctor Where Demail = '"+dname+"'",null); while(c.moveToNext()) { String d = c.getString(c.getColumnIndex("Drating")); System.out.println("Doctor:" + d); } }catch (Exception e){ e.printStackTrace(); } } public String get_doctor_amount(String patient_name) { String d=""; //String query="SELECT FEES FROM PRESCRIPTION WHERE PATIENTNAME = '"+patient_name+"'"; Cursor c = db.rawQuery("SELECT FEES FROM PRESCRIPTION WHERE PATIENTNAME = '"+patient_name+"'",null); c.moveToFirst(); while(c.moveToNext()) { d = c.getString(c.getColumnIndex("FEES")); } c.close(); return d; } }
4,818
0.601079
0.598589
138
32.913044
30.023777
115
false
false
0
0
0
0
0
0
0.702899
false
false
13
9ce7629a0236005ac5a79374ac33154fc476e90b
30,777,735,660,781
000688d559dbddf4a1c832c7ed7143dfe2d423f5
/src/framework/factories/IPartyFactory.java
a67a17945451b166d1355c4184a5db4dd2d19fee
[]
no_license
abdullahashik/BankingFramework
https://github.com/abdullahashik/BankingFramework
3e33d6f0a4d0021b51ecba721d9c47744d2e2a4f
ad3e53e68423486f3e26d43c898c8a554032fd02
refs/heads/master
2021-01-12T13:39:35.581000
2016-04-14T20:10:19
2016-04-14T20:10:19
70,059,417
1
0
null
true
2016-10-05T12:44:59
2016-10-05T12:44:58
2016-04-14T20:15:49
2016-04-14T20:10:52
118
0
0
0
null
null
null
package framework.factories; import framework.dto.PartyDTO; import framework.entities.Party; /** * * @author AFL * @param <T> * */ public interface IPartyFactory extends IFactory<PartyDTO, Party>{ @Override public Party create(PartyDTO dto); }
UTF-8
Java
253
java
IPartyFactory.java
Java
[ { "context": "port framework.entities.Party;\n\n/**\n * \n * @author AFL\n * @param <T>\n *\n */\npublic interface IPartyFacto", "end": 117, "score": 0.9962562322616577, "start": 114, "tag": "USERNAME", "value": "AFL" } ]
null
[]
package framework.factories; import framework.dto.PartyDTO; import framework.entities.Party; /** * * @author AFL * @param <T> * */ public interface IPartyFactory extends IFactory<PartyDTO, Party>{ @Override public Party create(PartyDTO dto); }
253
0.735178
0.735178
15
15.933333
17.975786
65
false
false
0
0
0
0
0
0
0.466667
false
false
13