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
81e21b59bc56312d816c9769093a3f211fa8cb15
20,736,102,121,848
7df7621ab36bb08d5492d81c5bd55fc213bb86f4
/src/main/java/be/bt/repository/AuthorityReository.java
dcc432559ada962837508ac511a7f7c10d74e37c
[]
no_license
tareqhb/products-app-back
https://github.com/tareqhb/products-app-back
41c19baa5ff1b388025f589905b861df4227e252
5455b590495fca2fd93ed38428fe0ce3e27af607
refs/heads/master
2020-03-28T14:21:49.571000
2018-09-12T13:00:44
2018-09-12T13:00:44
148,481,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.bt.repository; import be.bt.domain.security.Authority; import org.springframework.data.jpa.repository.JpaRepository; public interface AuthorityReository extends JpaRepository<Authority, Long> { }
UTF-8
Java
209
java
AuthorityReository.java
Java
[]
null
[]
package be.bt.repository; import be.bt.domain.security.Authority; import org.springframework.data.jpa.repository.JpaRepository; public interface AuthorityReository extends JpaRepository<Authority, Long> { }
209
0.832536
0.832536
7
28.857143
28.82176
76
false
false
0
0
0
0
0
0
0.571429
false
false
2
65d3ca079490b21c3fb3ce8afccb32a9161b1826
19,370,302,519,727
187d61038c998c769b857667531cda5e95842676
/src/test/java/com/sqa/sxd/core/IETest.java
57292e8e20b5991a4cc29b5864abd43f1165ad60
[]
no_license
sxd-hobo/basic-project
https://github.com/sxd-hobo/basic-project
1cba9d3647ffe2777d2b17ffd3aa5a55014d217e
4f40787061d787147f80d56c2a12d238bea75e21
refs/heads/master
2021-07-21T21:02:08.180000
2017-10-27T05:03:22
2017-10-27T05:03:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sqa.sxd.core; import java.util.concurrent.*; import org.openqa.selenium.ie.*; import org.testng.annotations.*; public class IETest extends Core { public IETest(String baseURL) { super(baseURL); } @BeforeMethod public void setIEDriver() { System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe"); setDriver(new InternetExplorerDriver()); getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Set up other window options such as fullscreen // getDriver().manage().window().fullscreen(); getDriver().get(getBaseUrl()); } @AfterMethod public void tearDown() { this.driver.quit(); } }
UTF-8
Java
656
java
IETest.java
Java
[]
null
[]
package com.sqa.sxd.core; import java.util.concurrent.*; import org.openqa.selenium.ie.*; import org.testng.annotations.*; public class IETest extends Core { public IETest(String baseURL) { super(baseURL); } @BeforeMethod public void setIEDriver() { System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe"); setDriver(new InternetExplorerDriver()); getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Set up other window options such as fullscreen // getDriver().manage().window().fullscreen(); getDriver().get(getBaseUrl()); } @AfterMethod public void tearDown() { this.driver.quit(); } }
656
0.722561
0.719512
28
22.428572
21.039806
74
false
false
0
0
0
0
0
0
1.321429
false
false
2
fb8c719e5041d5908748fea05b2b42a3626ca4bf
16,363,825,445,934
9f1ddb370c6abe869bb08496758c08eb8583f73f
/app/src/main/java/grk/impala/model/HistoryModel.java
00820d6083bd136e512c8428056fdad0694a6fb9
[]
no_license
cnaveen1403/DialFood
https://github.com/cnaveen1403/DialFood
6a9ae01f9db30401c8063d651b050b92adda23b4
1c1d58dd3764e2958d209707b107d7abac754e33
refs/heads/master
2021-01-13T03:26:17.346000
2016-12-28T18:57:34
2016-12-28T18:57:34
74,341,772
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package grk.impala.model; import java.util.ArrayList; import java.util.HashMap; /** * Created by Samsung on 7/15/2015. */ public class HistoryModel { String id, dat, total, status; ArrayList<HashMap<String, String>> hashMapArrayList; public HistoryModel() { } public HistoryModel(String id, String dat, String total, String status, ArrayList<HashMap<String, String>> hashMapArrayList) { this.id = id; this.dat = dat; this.total = total; this.status = status; this.hashMapArrayList = hashMapArrayList; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDat() { return dat; } public void setDat(String dat) { this.dat = dat; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public ArrayList<HashMap<String, String>> getHashMapArrayList() { return hashMapArrayList; } public void setHashMapArrayList(ArrayList<HashMap<String, String>> hashMapArrayList) { this.hashMapArrayList = hashMapArrayList; } }
UTF-8
Java
1,353
java
HistoryModel.java
Java
[ { "context": "List;\nimport java.util.HashMap;\n\n/**\n * Created by Samsung on 7/15/2015.\n */\npublic class HistoryModel {\n ", "end": 107, "score": 0.9332166314125061, "start": 100, "tag": "NAME", "value": "Samsung" } ]
null
[]
package grk.impala.model; import java.util.ArrayList; import java.util.HashMap; /** * Created by Samsung on 7/15/2015. */ public class HistoryModel { String id, dat, total, status; ArrayList<HashMap<String, String>> hashMapArrayList; public HistoryModel() { } public HistoryModel(String id, String dat, String total, String status, ArrayList<HashMap<String, String>> hashMapArrayList) { this.id = id; this.dat = dat; this.total = total; this.status = status; this.hashMapArrayList = hashMapArrayList; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDat() { return dat; } public void setDat(String dat) { this.dat = dat; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public ArrayList<HashMap<String, String>> getHashMapArrayList() { return hashMapArrayList; } public void setHashMapArrayList(ArrayList<HashMap<String, String>> hashMapArrayList) { this.hashMapArrayList = hashMapArrayList; } }
1,353
0.620103
0.61493
63
20.476191
23.342077
130
false
false
0
0
0
0
0
0
0.492063
false
false
2
bbb308e56b9f64242da7bb8a91cae2aadc35ff95
11,304,353,948,007
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634947029139456_1/java/xiaowuc1/A.java
d0a91c895148993c53d85de4e79d48af09bbd907
[]
no_license
alexandraback/datacollection
https://github.com/alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417000
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class A { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static int maxLen; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("a.in")); pw = new PrintWriter(new BufferedWriter(new FileWriter("a.out"))); final int MAX_CASES = readInt(); for(int casenum = 1; casenum <= MAX_CASES; casenum++) { pw.printf("Case #%d: ", casenum); int n = readInt(); int l = readInt(); maxLen = l; String[] list = new String[n]; for(int i = 0; i < n; i++) { list[i] = nextToken(); } HashMap<String, Integer> map = new HashMap<String, Integer>(); for(int i = 0; i < n; i++) { String s = nextToken(); for(int a = 1; a <= l; a++) { String key = s.substring(0, a); if(!map.containsKey(key)) { map.put(key, 0); } map.put(key, 1 + map.get(key)); } } int ret = Math.min(solve(list, 0, 1, map), solve(list, 1, 1, map)); if(ret >= 200) { pw.println("NOT POSSIBLE"); } else { pw.println(ret); } } pw.close(); } public static int solve(String[] list, long mask, int len, Map<String, Integer> map) { Map<String, Integer> temp = new HashMap<String, Integer>(); for(String out: list) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < len; i++) { int val = out.charAt(i) - '0'; if((mask&(1L<<i)) != 0) { val ^= 1; } sb.append(val); } String key = sb.toString(); if(!temp.containsKey(key)) { temp.put(key, 0); } temp.put(key, 1 + temp.get(key)); } for(String out: temp.keySet()) { if(!map.containsKey(out) || map.get(out).intValue() != temp.get(out).intValue()) { return 200; } } if(len == maxLen) { return Long.bitCount(mask); } return Math.min(solve(list, mask, len+1, map), solve(list, mask | (1L << len), len+1, map)); } public static int readInt() throws IOException { return Integer.parseInt(nextToken()); } public static long readLong() throws IOException { return Long.parseLong(nextToken()); } public static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } public static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { pw.close(); System.exit(0); } st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static String readLine() throws IOException { st = null; return br.readLine(); } }
UTF-8
Java
2,757
java
A.java
Java
[ { "context": "\n\t\t\t\t}\r\n\t\t\t\tsb.append(val);\r\n\t\t\t}\r\n\t\t\tString key = sb.toString();\r\n\t\t\tif(!temp.containsKey(key)) {\r\n\t\t\t\ttemp.put", "end": 1678, "score": 0.9197786450386047, "start": 1667, "tag": "KEY", "value": "sb.toString" } ]
null
[]
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class A { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static int maxLen; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("a.in")); pw = new PrintWriter(new BufferedWriter(new FileWriter("a.out"))); final int MAX_CASES = readInt(); for(int casenum = 1; casenum <= MAX_CASES; casenum++) { pw.printf("Case #%d: ", casenum); int n = readInt(); int l = readInt(); maxLen = l; String[] list = new String[n]; for(int i = 0; i < n; i++) { list[i] = nextToken(); } HashMap<String, Integer> map = new HashMap<String, Integer>(); for(int i = 0; i < n; i++) { String s = nextToken(); for(int a = 1; a <= l; a++) { String key = s.substring(0, a); if(!map.containsKey(key)) { map.put(key, 0); } map.put(key, 1 + map.get(key)); } } int ret = Math.min(solve(list, 0, 1, map), solve(list, 1, 1, map)); if(ret >= 200) { pw.println("NOT POSSIBLE"); } else { pw.println(ret); } } pw.close(); } public static int solve(String[] list, long mask, int len, Map<String, Integer> map) { Map<String, Integer> temp = new HashMap<String, Integer>(); for(String out: list) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < len; i++) { int val = out.charAt(i) - '0'; if((mask&(1L<<i)) != 0) { val ^= 1; } sb.append(val); } String key = sb.toString(); if(!temp.containsKey(key)) { temp.put(key, 0); } temp.put(key, 1 + temp.get(key)); } for(String out: temp.keySet()) { if(!map.containsKey(out) || map.get(out).intValue() != temp.get(out).intValue()) { return 200; } } if(len == maxLen) { return Long.bitCount(mask); } return Math.min(solve(list, mask, len+1, map), solve(list, mask | (1L << len), len+1, map)); } public static int readInt() throws IOException { return Integer.parseInt(nextToken()); } public static long readLong() throws IOException { return Long.parseLong(nextToken()); } public static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } public static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { pw.close(); System.exit(0); } st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static String readLine() throws IOException { st = null; return br.readLine(); } }
2,757
0.581066
0.57091
106
24.009434
21.009655
94
false
false
0
0
0
0
0
0
3.150943
false
false
2
ba66fff9d144ba404e3b6820e97a59620b113e5a
11,304,353,947,977
e791d4693c019950fd3a5340ceb66ffbf823c5c6
/CSSE230/TwoDTree/src/twodtree/Testing.java
ce8df6b4fac007a283a3294e98ed8acc4b3a3d72
[]
no_license
Trigon/RHIT-Codes
https://github.com/Trigon/RHIT-Codes
d9225982d9393be1e982977b8ad05e1df44dce69
227050226e157b6bbf9c83f6113d40a8004a0270
refs/heads/master
2016-09-17T15:40:15.390000
2016-09-09T18:36:06
2016-09-09T18:36:06
67,822,224
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package twodtree; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import org.junit.AfterClass; import org.junit.Test; import twodtree.TwoDTree.Direction; public class Testing { private static int maxPoints = 60; private static int testPoints = 0; private static int efficiencyPoints = 0; private Point2[] points = new Point2[] { new Point2(0.5, 0.7), new Point2(0.75, 0.5), new Point2(0.7, 0.15), new Point2(0.8, 0.25), new Point2(0.45, 0.4), new Point2(0.9, 0.15), }; String[] labels = new String[] { "A", "B", "C", "D", "E", "F" }; private Point2[] otherPoints = new Point2[] { new Point2(0.49, 0.6), new Point2(0.72, 0.49), new Point2(0.72, 0.14), new Point2(0.81, 0.26), new Point2(0.44, 0.34), new Point2(0.91, 0.14), }; @Test public void testInsert() { TwoDTree t = new TwoDTree(); assertEquals("()", t.toString()); String[] answers = new String[] { "A(0.50,0.70)", "A(0.50,0.70)(B(0.75,0.50))", "A(0.50,0.70)((C(0.70,0.15))B(0.75,0.50))", "A(0.50,0.70)((C(0.70,0.15)(D(0.80,0.25)))B(0.75,0.50))", "(E(0.45,0.40))A(0.50,0.70)((C(0.70,0.15)(D(0.80,0.25)))B(0.75,0.50))", "(E(0.45,0.40))A(0.50,0.70)((C(0.70,0.15)((F(0.90,0.15))D(0.80,0.25)))B(0.75,0.50))" }; for (int i = 0; i < answers.length; i++) { t.insert(points[i], labels[i]); assertEquals(answers[i], t.toString()); testPoints += 3; } } @Test public void testContains() { TwoDTree t = new TwoDTree(); assertFalse(t.contains(new Point2(0.4, 0.6))); testPoints += 2; for (int i = 0; i < points.length; i++) { t.insert(points[i], labels[i]); } for (int i = 0; i < points.length; i++) { assertTrue(t.contains(points[i])); } testPoints += 2; for (int i = 0; i < otherPoints.length; i++) { assertFalse(t.contains(otherPoints[i])); } testPoints += 2; } @Test public void testContainsRandomTree() { TwoDTree t = new TwoDTree(); Random r = new Random(17); // seed so reproducible int nPoints = 10; List<Point2> points = new ArrayList<Point2>(); for (int i = 0; i < nPoints; i++) { points.add(new Point2(r.nextDouble(), r.nextDouble())); } for (Point2 point : points) { t.insert(point, "X"); } for (int i = 0; i < points.size(); i++) { assertTrue(t.contains(points.get(i))); } testPoints += 3; for (int i = 0; i < nPoints; i++) { assertFalse(t.contains(new Point2(r.nextDouble(), r.nextDouble()))); } testPoints += 3; } @Test public void testNearest() { TwoDTree t = new TwoDTree(); for (int i = 0; i < points.length; i++) { t.insert(points[i], labels[i]); } Point2 query; Point2 expected; query = new Point2(0.6, 0.75); expected = points[0]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.8, 0.4); expected = points[1]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.75, 0.7); expected = points[1]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.75, 0.15); expected = points[2]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.60, 0.05); expected = points[2]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.85, 0.35); expected = points[3]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.4, 0.5); expected = points[4]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.95, 0.10); expected = points[5]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 3; query = new Point2(0.88, 0.20); expected = points[5]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 3; } @Test public void testNearestNeedToLookBothSides() { TwoDTree t = new TwoDTree(); Point2[] morePoints = new Point2[] { new Point2(0.5, 0.2), new Point2(0.75, 0.5), new Point2(0.4, 0.75) }; for (int i = 0; i < morePoints.length; i++) { t.insert(morePoints[i], labels[i]); } Point2 query; Point2 expected; query = new Point2(0.55, 0.75); expected = morePoints[2]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 10; } public static TwoDTree buildTest(TwoDTree t, int nLevels) { double x1 = 0.5; double y1 = 0.5; double nX = 1; double nY = 1; double deltaX = 1; double deltaY = 1; TwoDTree.Direction direction = TwoDTree.Direction.X; for (int level = 1; level <= nLevels; level++) { populateLevel(t, x1, y1, nX, nY, deltaX, deltaY, direction, level); // Alternate which direction we are splitting in. if (direction == TwoDTree.Direction.X) { deltaX /= 2; x1 /= 2; nX *= 2; direction = TwoDTree.Direction.Y; } else { deltaY /= 2; y1 /= 2; nY *= 2; direction = TwoDTree.Direction.X; } } return t; } private static void populateLevel(TwoDTree t, double x1, double y1, double nX, double nY, double deltaX, double deltaY, Direction direction, int level) { double x = x1; for (int nXCreated = 0; nXCreated < nX; nXCreated++) { double y = y1; for (int nYCreated = 0; nYCreated < nY; nYCreated++) { Point2 point = new Point2(x, y); t.insert(point, "" + level); y += deltaY; } x += deltaX; } } @Test public void testNearestEfficient() { TwoDTree tree = new TwoDTree(); buildTest(tree, 20); long startTime, elapsedTime; startTime = System.currentTimeMillis(); Point2 query = new Point2(0.99, 0.99); tree.nearestNeighbor(query); elapsedTime = (System.currentTimeMillis() - startTime); if (elapsedTime < 10) { efficiencyPoints = 10; } } @AfterClass public static void displayPoints() { String efficiencyMessage; if (testPoints == maxPoints) { testPoints += efficiencyPoints; efficiencyMessage = "Nearest was efficient"; } else { efficiencyMessage = "Nearest was not efficient"; } maxPoints += 10; System.out.printf("%2d/%2d points earned on unit tests.\n", testPoints, maxPoints); System.out.printf(efficiencyMessage); } }
UTF-8
Java
6,330
java
Testing.java
Java
[]
null
[]
package twodtree; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import org.junit.AfterClass; import org.junit.Test; import twodtree.TwoDTree.Direction; public class Testing { private static int maxPoints = 60; private static int testPoints = 0; private static int efficiencyPoints = 0; private Point2[] points = new Point2[] { new Point2(0.5, 0.7), new Point2(0.75, 0.5), new Point2(0.7, 0.15), new Point2(0.8, 0.25), new Point2(0.45, 0.4), new Point2(0.9, 0.15), }; String[] labels = new String[] { "A", "B", "C", "D", "E", "F" }; private Point2[] otherPoints = new Point2[] { new Point2(0.49, 0.6), new Point2(0.72, 0.49), new Point2(0.72, 0.14), new Point2(0.81, 0.26), new Point2(0.44, 0.34), new Point2(0.91, 0.14), }; @Test public void testInsert() { TwoDTree t = new TwoDTree(); assertEquals("()", t.toString()); String[] answers = new String[] { "A(0.50,0.70)", "A(0.50,0.70)(B(0.75,0.50))", "A(0.50,0.70)((C(0.70,0.15))B(0.75,0.50))", "A(0.50,0.70)((C(0.70,0.15)(D(0.80,0.25)))B(0.75,0.50))", "(E(0.45,0.40))A(0.50,0.70)((C(0.70,0.15)(D(0.80,0.25)))B(0.75,0.50))", "(E(0.45,0.40))A(0.50,0.70)((C(0.70,0.15)((F(0.90,0.15))D(0.80,0.25)))B(0.75,0.50))" }; for (int i = 0; i < answers.length; i++) { t.insert(points[i], labels[i]); assertEquals(answers[i], t.toString()); testPoints += 3; } } @Test public void testContains() { TwoDTree t = new TwoDTree(); assertFalse(t.contains(new Point2(0.4, 0.6))); testPoints += 2; for (int i = 0; i < points.length; i++) { t.insert(points[i], labels[i]); } for (int i = 0; i < points.length; i++) { assertTrue(t.contains(points[i])); } testPoints += 2; for (int i = 0; i < otherPoints.length; i++) { assertFalse(t.contains(otherPoints[i])); } testPoints += 2; } @Test public void testContainsRandomTree() { TwoDTree t = new TwoDTree(); Random r = new Random(17); // seed so reproducible int nPoints = 10; List<Point2> points = new ArrayList<Point2>(); for (int i = 0; i < nPoints; i++) { points.add(new Point2(r.nextDouble(), r.nextDouble())); } for (Point2 point : points) { t.insert(point, "X"); } for (int i = 0; i < points.size(); i++) { assertTrue(t.contains(points.get(i))); } testPoints += 3; for (int i = 0; i < nPoints; i++) { assertFalse(t.contains(new Point2(r.nextDouble(), r.nextDouble()))); } testPoints += 3; } @Test public void testNearest() { TwoDTree t = new TwoDTree(); for (int i = 0; i < points.length; i++) { t.insert(points[i], labels[i]); } Point2 query; Point2 expected; query = new Point2(0.6, 0.75); expected = points[0]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.8, 0.4); expected = points[1]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.75, 0.7); expected = points[1]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.75, 0.15); expected = points[2]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.60, 0.05); expected = points[2]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.85, 0.35); expected = points[3]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.4, 0.5); expected = points[4]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 2; query = new Point2(0.95, 0.10); expected = points[5]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 3; query = new Point2(0.88, 0.20); expected = points[5]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 3; } @Test public void testNearestNeedToLookBothSides() { TwoDTree t = new TwoDTree(); Point2[] morePoints = new Point2[] { new Point2(0.5, 0.2), new Point2(0.75, 0.5), new Point2(0.4, 0.75) }; for (int i = 0; i < morePoints.length; i++) { t.insert(morePoints[i], labels[i]); } Point2 query; Point2 expected; query = new Point2(0.55, 0.75); expected = morePoints[2]; assertEquals(expected, t.nearestNeighbor(query)); testPoints += 10; } public static TwoDTree buildTest(TwoDTree t, int nLevels) { double x1 = 0.5; double y1 = 0.5; double nX = 1; double nY = 1; double deltaX = 1; double deltaY = 1; TwoDTree.Direction direction = TwoDTree.Direction.X; for (int level = 1; level <= nLevels; level++) { populateLevel(t, x1, y1, nX, nY, deltaX, deltaY, direction, level); // Alternate which direction we are splitting in. if (direction == TwoDTree.Direction.X) { deltaX /= 2; x1 /= 2; nX *= 2; direction = TwoDTree.Direction.Y; } else { deltaY /= 2; y1 /= 2; nY *= 2; direction = TwoDTree.Direction.X; } } return t; } private static void populateLevel(TwoDTree t, double x1, double y1, double nX, double nY, double deltaX, double deltaY, Direction direction, int level) { double x = x1; for (int nXCreated = 0; nXCreated < nX; nXCreated++) { double y = y1; for (int nYCreated = 0; nYCreated < nY; nYCreated++) { Point2 point = new Point2(x, y); t.insert(point, "" + level); y += deltaY; } x += deltaX; } } @Test public void testNearestEfficient() { TwoDTree tree = new TwoDTree(); buildTest(tree, 20); long startTime, elapsedTime; startTime = System.currentTimeMillis(); Point2 query = new Point2(0.99, 0.99); tree.nearestNeighbor(query); elapsedTime = (System.currentTimeMillis() - startTime); if (elapsedTime < 10) { efficiencyPoints = 10; } } @AfterClass public static void displayPoints() { String efficiencyMessage; if (testPoints == maxPoints) { testPoints += efficiencyPoints; efficiencyMessage = "Nearest was efficient"; } else { efficiencyMessage = "Nearest was not efficient"; } maxPoints += 10; System.out.printf("%2d/%2d points earned on unit tests.\n", testPoints, maxPoints); System.out.printf(efficiencyMessage); } }
6,330
0.629226
0.566983
252
24.119047
21.362
120
false
false
0
0
0
0
0
0
2.777778
false
false
2
206c9b7c1d0cc1431b70c32f266ca30a67e2658f
2,465,311,256,825
d75fd0b7dd5f88129a764842f92fb1c470060114
/UVA/Problem_11494.java
1de061874847e91cd0a2ddb1ce2c9f7a1a47c3c5
[]
no_license
renatoaf/renatoaf
https://github.com/renatoaf/renatoaf
e74ba7ca304581db08bea55818a3dcbaf8eaf133
2c09f19273cad8a88983f5b793c33c8975a9fac1
refs/heads/master
2020-04-16T03:23:26.449000
2015-10-01T04:33:03
2015-10-01T04:33:03
33,736,906
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Queen */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; class Problem_11494 { static int nextInt(StringTokenizer config) { return Integer.parseInt(config.nextToken()); } public static void main(String[] args) throws IOException { StringBuilder saida = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { StringTokenizer config = new StringTokenizer(in.readLine()); int X1 = nextInt(config); int Y1 = nextInt(config); int X2 = nextInt(config); int Y2 = nextInt(config); if (X1 == 0 && X2 == 0 && Y1 == 0 && Y2 == 0) { break; } if (X1 == X2 && Y1 == Y2) { saida.append("0"); } else if (X1 == X2 || Y1 == Y2 || (Math.abs(X1 - X2) == Math.abs(Y1 - Y2))) { saida.append("1"); } else { saida.append("2"); } saida.append("\n"); } System.out.print(saida); } }
UTF-8
Java
1,018
java
Problem_11494.java
Java
[]
null
[]
/* * Queen */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; class Problem_11494 { static int nextInt(StringTokenizer config) { return Integer.parseInt(config.nextToken()); } public static void main(String[] args) throws IOException { StringBuilder saida = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { StringTokenizer config = new StringTokenizer(in.readLine()); int X1 = nextInt(config); int Y1 = nextInt(config); int X2 = nextInt(config); int Y2 = nextInt(config); if (X1 == 0 && X2 == 0 && Y1 == 0 && Y2 == 0) { break; } if (X1 == X2 && Y1 == Y2) { saida.append("0"); } else if (X1 == X2 || Y1 == Y2 || (Math.abs(X1 - X2) == Math.abs(Y1 - Y2))) { saida.append("1"); } else { saida.append("2"); } saida.append("\n"); } System.out.print(saida); } }
1,018
0.599214
0.56778
43
21.72093
19.731129
75
false
false
0
0
0
0
0
0
2.209302
false
false
2
a52a30f2d1b7f2029bbaec224f2b796be60708b8
11,149,735,145,744
f051d87b9fe6e5280a9f55cd142302cd0dc894e2
/contrib/storage-kafka/src/main/java/org/apache/drill/exec/store/kafka/decoders/JsonMessageReader.java
32396646465e47c681b8c107b2c213ab40edf571
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-unknown" ]
permissive
parthchandra/drill
https://github.com/parthchandra/drill
6e469840c3746fb7dd6d07d53face80da78ff1cf
865ea2f3f233abc2bf5854f272f5455d2f93d97b
refs/heads/master
2021-04-06T03:54:37.536000
2018-05-04T17:47:28
2018-05-15T21:50:52
17,526,683
1
1
Apache-2.0
true
2018-09-05T21:52:12
2014-03-07T20:40:04
2018-05-15T21:55:31
2018-08-03T01:15:15
45,987
2
2
0
Java
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.store.kafka.decoders; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_MSG_KEY; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_OFFSET; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_PARTITION_ID; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_TIMESTAMP; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_TOPIC; import java.io.IOException; import java.util.List; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.exec.store.kafka.KafkaStoragePlugin; import org.apache.drill.exec.vector.complex.fn.JsonReader; import org.apache.drill.exec.vector.complex.impl.VectorContainerWriter; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.netty.buffer.DrillBuf; /** * MessageReader class which will convert ConsumerRecord into JSON and writes to * VectorContainerWriter of JsonReader * */ public class JsonMessageReader implements MessageReader { private static final Logger logger = LoggerFactory.getLogger(JsonMessageReader.class); private JsonReader jsonReader; private VectorContainerWriter writer; @Override public void init(DrillBuf buf, List<SchemaPath> columns, VectorContainerWriter writer, boolean allTextMode, boolean readNumbersAsDouble) { // set skipOuterList to false as it doesn't applicable for JSON records and it's only applicable for JSON files. this.jsonReader = new JsonReader.Builder(buf) .schemaPathColumns(columns) .allTextMode(allTextMode) .readNumbersAsDouble(readNumbersAsDouble) .build(); this.writer = writer; } @Override public void readMessage(ConsumerRecord<?, ?> record) { try { byte[] recordArray = (byte[]) record.value(); JsonObject jsonObj = (new JsonParser()).parse(new String(recordArray, Charsets.UTF_8)).getAsJsonObject(); jsonObj.addProperty(KAFKA_TOPIC.getFieldName(), record.topic()); jsonObj.addProperty(KAFKA_PARTITION_ID.getFieldName(), record.partition()); jsonObj.addProperty(KAFKA_OFFSET.getFieldName(), record.offset()); jsonObj.addProperty(KAFKA_TIMESTAMP.getFieldName(), record.timestamp()); jsonObj.addProperty(KAFKA_MSG_KEY.getFieldName(), record.key() != null ? record.key().toString() : null); jsonReader.setSource(jsonObj.toString().getBytes(Charsets.UTF_8)); jsonReader.write(writer); } catch (IOException e) { throw UserException.dataReadError(e).message(e.getMessage()) .addContext("MessageReader", JsonMessageReader.class.getName()).build(logger); } } @Override public void ensureAtLeastOneField() { jsonReader.ensureAtLeastOneField(writer); } @Override public KafkaConsumer<byte[], byte[]> getConsumer(KafkaStoragePlugin plugin) { return plugin.registerConsumer(new KafkaConsumer<>(plugin.getConfig().getKafkaConsumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer())); } @Override public void close() throws IOException { this.writer.clear(); try { this.writer.close(); } catch (Exception e) { logger.warn("Error while closing JsonMessageReader", e); } } }
UTF-8
Java
4,398
java
JsonMessageReader.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.store.kafka.decoders; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_MSG_KEY; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_OFFSET; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_PARTITION_ID; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_TIMESTAMP; import static org.apache.drill.exec.store.kafka.MetaDataField.KAFKA_TOPIC; import java.io.IOException; import java.util.List; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.exec.store.kafka.KafkaStoragePlugin; import org.apache.drill.exec.vector.complex.fn.JsonReader; import org.apache.drill.exec.vector.complex.impl.VectorContainerWriter; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.netty.buffer.DrillBuf; /** * MessageReader class which will convert ConsumerRecord into JSON and writes to * VectorContainerWriter of JsonReader * */ public class JsonMessageReader implements MessageReader { private static final Logger logger = LoggerFactory.getLogger(JsonMessageReader.class); private JsonReader jsonReader; private VectorContainerWriter writer; @Override public void init(DrillBuf buf, List<SchemaPath> columns, VectorContainerWriter writer, boolean allTextMode, boolean readNumbersAsDouble) { // set skipOuterList to false as it doesn't applicable for JSON records and it's only applicable for JSON files. this.jsonReader = new JsonReader.Builder(buf) .schemaPathColumns(columns) .allTextMode(allTextMode) .readNumbersAsDouble(readNumbersAsDouble) .build(); this.writer = writer; } @Override public void readMessage(ConsumerRecord<?, ?> record) { try { byte[] recordArray = (byte[]) record.value(); JsonObject jsonObj = (new JsonParser()).parse(new String(recordArray, Charsets.UTF_8)).getAsJsonObject(); jsonObj.addProperty(KAFKA_TOPIC.getFieldName(), record.topic()); jsonObj.addProperty(KAFKA_PARTITION_ID.getFieldName(), record.partition()); jsonObj.addProperty(KAFKA_OFFSET.getFieldName(), record.offset()); jsonObj.addProperty(KAFKA_TIMESTAMP.getFieldName(), record.timestamp()); jsonObj.addProperty(KAFKA_MSG_KEY.getFieldName(), record.key() != null ? record.key().toString() : null); jsonReader.setSource(jsonObj.toString().getBytes(Charsets.UTF_8)); jsonReader.write(writer); } catch (IOException e) { throw UserException.dataReadError(e).message(e.getMessage()) .addContext("MessageReader", JsonMessageReader.class.getName()).build(logger); } } @Override public void ensureAtLeastOneField() { jsonReader.ensureAtLeastOneField(writer); } @Override public KafkaConsumer<byte[], byte[]> getConsumer(KafkaStoragePlugin plugin) { return plugin.registerConsumer(new KafkaConsumer<>(plugin.getConfig().getKafkaConsumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer())); } @Override public void close() throws IOException { this.writer.clear(); try { this.writer.close(); } catch (Exception e) { logger.warn("Error while closing JsonMessageReader", e); } } }
4,398
0.753752
0.751933
108
39.722221
31.553551
116
false
false
0
0
0
0
0
0
0.583333
false
false
2
204be7f54a90f423875e4811e34f2d4107e47b42
9,689,446,248,709
529bb13bea4470929733c6ac6c654d760b0a1c23
/src/doctest/Test.java
34d13f1778d03424291536277392df0c6dfd9c9b
[]
no_license
xuzhiyou/FirstRpt
https://github.com/xuzhiyou/FirstRpt
06ac21cc4102e896187962b3a2372a05062c45f6
036e431464d3e4a7a169e5b4ad565b5ad61e6fc5
refs/heads/master
2020-05-21T20:11:08.236000
2017-01-05T03:16:10
2017-01-05T03:16:10
63,239,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package doctest; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import xzy.*; import java.util.Arrays; /** * Description: * <br> 第一个javadoc测试类 * 2016-09-02<br> * 这是在utf-8下新加入的中文 * this is a test * @author xuzhiyou * @author x z y * @author xzy--xzy2--xzy3 * @version 1.0 * @version 1.1 * @version %I%, %G% * See the <a href="{@docRoot}/../testDoc/overview-tree.html">Copyright</a>.<br> */ public class Test extends HighArray implements TestInterface{ /** * private:password */ private int password; /** * public:name */ public String name; protected String sex = "men"; /** * the num is 20 * HighArray.VALUE:{@value xzy.HighArray#VALUE} */ public static int num = 20; /** * distances of point (x,y) */ public int x, y; /** * value * static final: {@value} * static ID: {@value #ID} */ public static final double ID = 12345678; /** * password name * @param password int���ͣ����� * @param name String���ͣ����� * */ public Test(int password ,String name){ this.password = password; this.name = name; } /** * {@code Map<Strting, Double>} code-map <br> * {@literal Map<Strting, Double>} literal-map <br> * {@code Map<Strting, Double>} code-map <br> * @param name String * 查看{@link HighArray#find(long)} 方法-111 * 查看{@link HighArray#find(long) find} 方法-111-2 * 查看{@linkplain HighArray#find(long)} 方法-222 * 查看{@linkplain HighArray#find(long) find} 方法-222-2 * 查看{@linkplain String#equals} 方法-333 * 查看{@linkplain String#equals(Object)} 方法-333-2 * HighArray#find(long) 方法-333 * * * 查看: @see #getName() * 查看: @see {@link #getName()} * @see #getName() * @see #getName() {@link #getName()} * @see #getName() <br> * @see #getName() getName1 @see #getName() getName4 * @see #getName() getName2 * @see #getName() getName3 <br> * @see String * @see String#equals * @see String#equals(Object) bbbbb * @see String#equals(Object) * @see #getName() getName4 * @see xzy.HighArray#insert(long) * @see HighArray#find(long) * @see HighArray * @see HighArray#find * @see Arrays#toString(int[]) * @see xzy.MainTest#main(String[]) * * code test: * {@code List<String>} code-list * {@literal Map<Strting, Double>} literal-map */ public void setName(String name){ this.name = name; } /** * @return name */ public String getName(){ return name; } /** * 继承 HighArray 方法 * @param value delete-value-Test * @return {@inheritDoc} * @see #getName() * @see <a href="spec.html#section">Java Spec</a> * @exception IOException exception-Test * @throws FileNotFoundException file-exception-Test */ @Override public boolean delete(long value) throws IOException, FileNotFoundException{ return true; } /** * 继承 HighArray 方法 * @param num find the number */ public boolean find(long num){ return true; } @Override /** * this method contains override * @param string input a string */ public String doctest_In_1(String string) { // TODO Auto-generated method stub return null; } /** * this method no override. * implements interface * @param line the inputtttttt */ public void doctest_In_2(String line) { // TODO Auto-generated method stub } /** * comments-Test {@inheritDoc} * @param line input-Test */ public String getString(String line) throws FileNotFoundException { // TODO Auto-generated method stub return null; } /** * the method override object method-Test * @return nothing-Test */ public String toString() { return ""; } /** * seTest-Test * @serial include */ public void seTest(){ } /** * type parameter-Test * @param highRrary parameter-Test */ public void typePara(HighArray highRrary){ } /** * type parameter-test * @param string the string to be converted-Test * @param type the type to convert the string to-Test * @param <T> the type of the element * @param <V> the value of the elemen * @return nothing-Test */ public <T, V extends T> V convert(String string, Class<T> type) { return null; } /** * two parameter test public * @param s1 the first parameter */ public void twoPara(String s1,String s2){ } @Override public void twoPara2(String s1, String s2){ } /** * a method * @param file file-path * @exception IOException test-exception * @throws IOException when read file the exception would be occur * @return a string line */ public String firstLine(String file) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(file))); String line = bufferedReader.readLine(); return line; } /** * Save the state of this object to a stream. * * @serialData serialData-test */ public void output(){} /** * native-method-test * @return nothing */ public native static double getPassword(); /** * synchronized-test * @return nothing * @throws IOException there-nothing */ public static int get() throws IOException{ synchronized (Test.class) { return 0; } } /** * new data test data、author不显示 * @param string * @author xuzhiyou * @data 2016年9月7日 下午4:05:11 */ public void testNewBiaoqain(String string) { } protected void dispaly(String str){ /** * line-test */ String line = str; /** * The X-coordinate of the component * @see #password */ int x = 10; /** * for-test */ for(int i = 0; i < 3; i++){ System.out.println("Done."); } } /** * code-literal-test. * <br> * No.1<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.2-new-no-code<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new Translator<String, Integer>(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.3-no-code<br> * <pre> * new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </pre> * * No.4-no-pre<br> * <code>new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * * <br> * No.5-new-literal<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new{@literal Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.6-Override-code<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@code @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.7-no-*-<br> <pre> <code>new BeanTranslator.Builder() .translate( new{@code Translator<String, Integer>}(String.class, Integer.class){ {@code @}Override public Integer translate(String instance) { return Integer.valueOf(instance); }}) .build(); </code> </pre> * * N0.9-code * <pre> * {@code * public List<Object> getObjects() { * return objects; * } * } * </pre> * * {@code public List<Object> getObjects()} <br> * {@literal public List<Object> getObjects()} <br> * public List<Object> getObjects()<br> * <pre> public List<Object> getObjects() </pre><br> * <code>{@code public List<Object> getObjects()} </code><br> * <code>{@literal public List<Object> getObjects()} </code><br> * @param line input-string */ public void codeTest(String line) { } /** * 静态块-test. */ static { /** * string-test */ String string = "abc"; } /** * this <code>Date</code> object. * <blockquote><pre> * (this.getTime() - UTC(this.getYear(), * this.getMonth(), * this.getDate(), * this.getHours(), * this.getMinutes(), * this.getSeconds())) / (60 * 1000) * </pre></blockquote> * * @deprecated As of JDK version 1.1. * <br> * replaced by {@link #output()}. * @since 1.2 * */ public void output2(){} }
UTF-8
Java
10,065
java
Test.java
Java
[ { "context": "r>\r\n* 这是在utf-8下新加入的中文\r\n* this is a test\r\n* @author xuzhiyou\r\n* @author x z y\r\n* @author xzy--xzy2--xzy3\r\n* @v", "end": 327, "score": 0.9994719624519348, "start": 319, "tag": "USERNAME", "value": "xuzhiyou" }, { "context": "st\r\n* @author xuzhiyou\r\n* @auth...
null
[]
package doctest; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import xzy.*; import java.util.Arrays; /** * Description: * <br> 第一个javadoc测试类 * 2016-09-02<br> * 这是在utf-8下新加入的中文 * this is a test * @author xuzhiyou * @author x z y * @author xzy--xzy2--xzy3 * @version 1.0 * @version 1.1 * @version %I%, %G% * See the <a href="{@docRoot}/../testDoc/overview-tree.html">Copyright</a>.<br> */ public class Test extends HighArray implements TestInterface{ /** * private:password */ private int password; /** * public:name */ public String name; protected String sex = "men"; /** * the num is 20 * HighArray.VALUE:{@value xzy.HighArray#VALUE} */ public static int num = 20; /** * distances of point (x,y) */ public int x, y; /** * value * static final: {@value} * static ID: {@value #ID} */ public static final double ID = 12345678; /** * password name * @param password int���ͣ����� * @param name String���ͣ����� * */ public Test(int password ,String name){ this.password = <PASSWORD>; this.name = name; } /** * {@code Map<Strting, Double>} code-map <br> * {@literal Map<Strting, Double>} literal-map <br> * {@code Map<Strting, Double>} code-map <br> * @param name String * 查看{@link HighArray#find(long)} 方法-111 * 查看{@link HighArray#find(long) find} 方法-111-2 * 查看{@linkplain HighArray#find(long)} 方法-222 * 查看{@linkplain HighArray#find(long) find} 方法-222-2 * 查看{@linkplain String#equals} 方法-333 * 查看{@linkplain String#equals(Object)} 方法-333-2 * HighArray#find(long) 方法-333 * * * 查看: @see #getName() * 查看: @see {@link #getName()} * @see #getName() * @see #getName() {@link #getName()} * @see #getName() <br> * @see #getName() getName1 @see #getName() getName4 * @see #getName() getName2 * @see #getName() getName3 <br> * @see String * @see String#equals * @see String#equals(Object) bbbbb * @see String#equals(Object) * @see #getName() getName4 * @see xzy.HighArray#insert(long) * @see HighArray#find(long) * @see HighArray * @see HighArray#find * @see Arrays#toString(int[]) * @see xzy.MainTest#main(String[]) * * code test: * {@code List<String>} code-list * {@literal Map<Strting, Double>} literal-map */ public void setName(String name){ this.name = name; } /** * @return name */ public String getName(){ return name; } /** * 继承 HighArray 方法 * @param value delete-value-Test * @return {@inheritDoc} * @see #getName() * @see <a href="spec.html#section">Java Spec</a> * @exception IOException exception-Test * @throws FileNotFoundException file-exception-Test */ @Override public boolean delete(long value) throws IOException, FileNotFoundException{ return true; } /** * 继承 HighArray 方法 * @param num find the number */ public boolean find(long num){ return true; } @Override /** * this method contains override * @param string input a string */ public String doctest_In_1(String string) { // TODO Auto-generated method stub return null; } /** * this method no override. * implements interface * @param line the inputtttttt */ public void doctest_In_2(String line) { // TODO Auto-generated method stub } /** * comments-Test {@inheritDoc} * @param line input-Test */ public String getString(String line) throws FileNotFoundException { // TODO Auto-generated method stub return null; } /** * the method override object method-Test * @return nothing-Test */ public String toString() { return ""; } /** * seTest-Test * @serial include */ public void seTest(){ } /** * type parameter-Test * @param highRrary parameter-Test */ public void typePara(HighArray highRrary){ } /** * type parameter-test * @param string the string to be converted-Test * @param type the type to convert the string to-Test * @param <T> the type of the element * @param <V> the value of the elemen * @return nothing-Test */ public <T, V extends T> V convert(String string, Class<T> type) { return null; } /** * two parameter test public * @param s1 the first parameter */ public void twoPara(String s1,String s2){ } @Override public void twoPara2(String s1, String s2){ } /** * a method * @param file file-path * @exception IOException test-exception * @throws IOException when read file the exception would be occur * @return a string line */ public String firstLine(String file) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(file))); String line = bufferedReader.readLine(); return line; } /** * Save the state of this object to a stream. * * @serialData serialData-test */ public void output(){} /** * native-method-test * @return nothing */ public native static double getPassword(); /** * synchronized-test * @return nothing * @throws IOException there-nothing */ public static int get() throws IOException{ synchronized (Test.class) { return 0; } } /** * new data test data、author不显示 * @param string * @author xuzhiyou * @data 2016年9月7日 下午4:05:11 */ public void testNewBiaoqain(String string) { } protected void dispaly(String str){ /** * line-test */ String line = str; /** * The X-coordinate of the component * @see #password */ int x = 10; /** * for-test */ for(int i = 0; i < 3; i++){ System.out.println("Done."); } } /** * code-literal-test. * <br> * No.1<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.2-new-no-code<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new Translator<String, Integer>(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.3-no-code<br> * <pre> * new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </pre> * * No.4-no-pre<br> * <code>new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * * <br> * No.5-new-literal<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new{@literal Translator<String, Integer>}(String.class, Integer.class){ * {@literal @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.6-Override-code<br> * <pre> * <code>new BeanTranslator.Builder() * .translate( * new{@code Translator<String, Integer>}(String.class, Integer.class){ * {@code @}Override * public Integer translate(String instance) { * return Integer.valueOf(instance); * }}) * .build(); * </code> * </pre> * * No.7-no-*-<br> <pre> <code>new BeanTranslator.Builder() .translate( new{@code Translator<String, Integer>}(String.class, Integer.class){ {@code @}Override public Integer translate(String instance) { return Integer.valueOf(instance); }}) .build(); </code> </pre> * * N0.9-code * <pre> * {@code * public List<Object> getObjects() { * return objects; * } * } * </pre> * * {@code public List<Object> getObjects()} <br> * {@literal public List<Object> getObjects()} <br> * public List<Object> getObjects()<br> * <pre> public List<Object> getObjects() </pre><br> * <code>{@code public List<Object> getObjects()} </code><br> * <code>{@literal public List<Object> getObjects()} </code><br> * @param line input-string */ public void codeTest(String line) { } /** * 静态块-test. */ static { /** * string-test */ String string = "abc"; } /** * this <code>Date</code> object. * <blockquote><pre> * (this.getTime() - UTC(this.getYear(), * this.getMonth(), * this.getDate(), * this.getHours(), * this.getMinutes(), * this.getSeconds())) / (60 * 1000) * </pre></blockquote> * * @deprecated As of JDK version 1.1. * <br> * replaced by {@link #output()}. * @since 1.2 * */ public void output2(){} }
10,067
0.557733
0.547631
452
19.900442
18.756269
85
false
false
0
0
0
0
0
0
1.130531
false
false
2
b71c6b4ff82ebed66460e346266984b94c622dcd
12,945,031,461,696
9c7899f41c97260ce59f9d875635955b15bcb195
/source/RuntimeTest/src/com/huaqin/runtime/TesterCamera.java
777e57841d63705329682f7a8db8927c099e9068
[]
no_license
davidlcc/tools
https://github.com/davidlcc/tools
9fffe2b60b0d7c2b07caabf6edcc4ebc78d90399
e94de12580aff55af2c873d79e5519bb54ea9b9b
HEAD
2016-08-06T07:15:42.313000
2015-08-14T10:04:01
2015-08-14T10:36:40
40,168,895
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huaqin.runtime; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.os.ConditionVariable; import android.view.SurfaceView; import android.view.SurfaceHolder; import android.view.KeyEvent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.*; public class TesterCamera extends Activity implements Testerthread.TesterInterface, SurfaceHolder.Callback { public String TAG = "TesterCamera"; public SurfaceView mSurfaceView = null; private Camera mCamera = null; private static int MSG_BEGIN_CAMERA_TEST = 400; private static int MSG_STOP_CAMERA_TEST = 401; private static int MSG_STOP_CAMERA_PREVIEW = 402; private static int MSG_NOTIFY_TEST_RESULT = 403; private static int MSG_STOP_CAMERA_TEST_FROM_NOTIFY = 410; private boolean mbRunningFlag = false; private SurfaceHolder mSurfaceHolder = null; private static final int CAMERA_ID = 1; private RawPreviewCallback mRawPreviewCallback = new RawPreviewCallback(); private boolean rawPreviewCallbackResult = false; private final ConditionVariable mPreviewDone = new ConditionVariable(); private static long WAIT_FOR_COMMAND_TO_COMPLETE = 10000; // Milliseconds. private Testerthread mTesterthread = null; private static Handler mCommHandler = null; private boolean mbUserPressBack = false; private boolean mbPaused = false; //added for handle more than 1 cameras. private int mNumberofCameras = 0; private int mCameraIndex = 0; private static String ACTION_STOP_CAMERATEST = "com.huaqin.runtime.cameratest.stop"; private Handler mInnerHandler = new Handler() { public void handleMessage(Message msg) { Log.d(TAG, "handleMessage:msg:" + msg.what); if(msg.what == MSG_BEGIN_CAMERA_TEST) { openCamera(mCameraIndex); mCameraIndex ++; } else if(msg.what == MSG_STOP_CAMERA_PREVIEW) { Log.d(TAG, "handleMessage:STOP_CAMERA_PREVIEW:index:" + mCameraIndex + ",number:" + mNumberofCameras); if(mCameraIndex == mNumberofCameras) //stop camera,notify test_result { stopCamera(); mInnerHandler.sendEmptyMessageDelayed(MSG_NOTIFY_TEST_RESULT, getsleepafterstop()); } else //stop current camera, start new camera preview. { stopCamera(); mInnerHandler.sendEmptyMessageDelayed(MSG_BEGIN_CAMERA_TEST, 1000); } } /* mCamera = Camera.open(0); if(mCamera == null) { notifyTestResult(0, "open error"); return ; } mCamera.setPreviewCallback(mRawPreviewCallback); try { mCamera.setPreviewDisplay(mSurfaceHolder); } catch (IOException exception) { mCamera.release(); mCamera = null; notifyTestResult(0, "setpreview error"+exception); return; } mCamera.startPreview(); } else if(msg.what == MSG_STOP_CAMERA_PREVIEW) { if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; mInnerHandler.sendEmptyMessageDelayed(MSG_NOTIFY_TEST_RESULT, getsleepafterstop()); } } */ else if(msg.what == MSG_NOTIFY_TEST_RESULT) { notifyTestResult(1, null); } else if(msg.what == MSG_STOP_CAMERA_TEST) { /* if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } */ stopCamera(); //clear MSG_NOTIFY_TEST_RESULT message(may already in the message queue mInnerHandler.removeMessages(MSG_NOTIFY_TEST_RESULT); if(mbPaused == false) { finish();//quit testcamera ui. } } else if(msg.what == MSG_STOP_CAMERA_TEST_FROM_NOTIFY) { //release camera(do not notify test result) /* if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } */ //clear MSG_NOTIFY_TEST_RESULT message(may already in the message queue stopCamera(); mInnerHandler.removeMessages(MSG_NOTIFY_TEST_RESULT); finish();//quit testcamera ui. } } }; //processing event sent form runtimetest service(mostly for battery test failed,all other test should be stopped). private BroadcastReceiver mReceiver = new BroadcastReceiver(){ public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "mReceiver: action:" + action); if(action.equals(ACTION_STOP_CAMERATEST)) { mInnerHandler.sendEmptyMessage(MSG_STOP_CAMERA_TEST_FROM_NOTIFY); } } }; private void notifyTestResult(int result, String extra) { //tell tester thread that one round is done,may begin a new round. Handler workingHandler = mTesterthread.getworkingHandler(); Message msg = workingHandler.obtainMessage((result ==1)?Testerthread.MSG_ONEROUND_FINISHED:Testerthread.MSG_ONEROUND_FAILED); Bundle bundle = new Bundle(); bundle.putInt("result", result); // 0, failed.1,success. if(result != 1) { bundle.putString("error_code", extra); } msg.setData(bundle); workingHandler.sendMessage(msg); //send message to workingthread. } public static void setCommHandler(Handler handler) { mCommHandler = handler; } @Override public void onCreate(Bundle paramBundle) { // TODO Auto-generated method stub super.onCreate(paramBundle); setContentView(R.layout.camera); getWindow().setFormat(0); mSurfaceView = (SurfaceView)findViewById(R.id.surface_view); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); Intent intent = getIntent(); int testcount = intent.getIntExtra("count", 10); int caseid = intent.getIntExtra("caseid", 0); //get camera number mNumberofCameras = Camera.getNumberOfCameras(); mCameraIndex = 0; Log.d(TAG, "onCreate:mNumberofCameras:" + mNumberofCameras); //register filter for processing stop event sent from runtimetestservice(mostly for battery test failed) IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_STOP_CAMERATEST); registerReceiver(mReceiver, filter); mTesterthread = new Testerthread(TAG, caseid, Testerthread.TESTTYPE_COUNT, testcount); mTesterthread.setTesterInterface(this); mTesterthread.setoutHandler(mCommHandler); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause:mbUserPressBack:" + mbUserPressBack); if(mbUserPressBack == true) { onstopTest(); //stop tester thread: ABORTED msg will be notified from the tester thread. mTesterthread.stopTesterThread(); } else { mbPaused = true; //should be set before call onstopTest() onstopTest(); } } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume:mbPaused:" + mbPaused); if(mbPaused == true) { //start camera onstartTest(); } } //only process user back key public boolean onKeyDown(int keyCode, KeyEvent event) { int keycode = event.getKeyCode(); Log.d(TAG, "onKeyDown:keycode:" + keycode); if(keycode == KeyEvent.KEYCODE_BACK) { mbUserPressBack = true; } return super.onKeyDown(keyCode, event); } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated:mbPaued:" + mbPaused); //start tester thread after surface view created.otherwise,preview can not be displayed. if(mbPaused == false) //for paused conditon,test thread is still running. { mTesterthread.startTesterThread(); //begin the test thread. } else { mbPaused = false; } } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "surfaceDestroyed:mbPaued:" + mbPaused); //do something } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Log.d(TAG, "surfaceChanged:mbPaued:" + mbPaused); //do something } /* * (non-Javadoc) * @see com.huaqin.runtime.Testerthread.TesterInterface */ public void onstartTest() { mCameraIndex = 0; //reset camera index. mInnerHandler.sendEmptyMessage(MSG_BEGIN_CAMERA_TEST); } public void onstopTest() { // TODO Auto-generated method stub mInnerHandler.sendEmptyMessage(MSG_STOP_CAMERA_TEST); } public int onsleepbeforestart() { // TODO Auto-generated method stub return 5000; } public int getsleepafterstop() { return 1000; } private void openCamera(int camera_index) { Log.d(TAG, "openCamera:index" + camera_index); mCamera = Camera.open(camera_index); if(mCamera == null) { notifyTestResult(0, "open error"); return ; } mCamera.setPreviewCallback(mRawPreviewCallback); try { mCamera.setPreviewDisplay(mSurfaceHolder); } catch (IOException exception) { mCamera.release(); mCamera = null; notifyTestResult(0, "setpreview error"+exception); return; } mCamera.startPreview(); } private void stopCamera() { if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } } private void waitForPreviewDone() { if (!mPreviewDone.block(WAIT_FOR_COMMAND_TO_COMPLETE)) { Log.v(TAG, "waitForPreviewDone: timeout"); } mPreviewDone.close(); } private final class RawPreviewCallback implements PreviewCallback { public void onPreviewFrame(byte [] rawData, Camera camera) { Log.v(TAG, "Preview callback start"); mCamera.setPreviewCallback(null); mInnerHandler.sendEmptyMessageDelayed(MSG_STOP_CAMERA_PREVIEW, 3000); //preview success, wait 5s before stop preview. } }; }
UTF-8
Java
12,426
java
TesterCamera.java
Java
[]
null
[]
package com.huaqin.runtime; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.os.ConditionVariable; import android.view.SurfaceView; import android.view.SurfaceHolder; import android.view.KeyEvent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.*; public class TesterCamera extends Activity implements Testerthread.TesterInterface, SurfaceHolder.Callback { public String TAG = "TesterCamera"; public SurfaceView mSurfaceView = null; private Camera mCamera = null; private static int MSG_BEGIN_CAMERA_TEST = 400; private static int MSG_STOP_CAMERA_TEST = 401; private static int MSG_STOP_CAMERA_PREVIEW = 402; private static int MSG_NOTIFY_TEST_RESULT = 403; private static int MSG_STOP_CAMERA_TEST_FROM_NOTIFY = 410; private boolean mbRunningFlag = false; private SurfaceHolder mSurfaceHolder = null; private static final int CAMERA_ID = 1; private RawPreviewCallback mRawPreviewCallback = new RawPreviewCallback(); private boolean rawPreviewCallbackResult = false; private final ConditionVariable mPreviewDone = new ConditionVariable(); private static long WAIT_FOR_COMMAND_TO_COMPLETE = 10000; // Milliseconds. private Testerthread mTesterthread = null; private static Handler mCommHandler = null; private boolean mbUserPressBack = false; private boolean mbPaused = false; //added for handle more than 1 cameras. private int mNumberofCameras = 0; private int mCameraIndex = 0; private static String ACTION_STOP_CAMERATEST = "com.huaqin.runtime.cameratest.stop"; private Handler mInnerHandler = new Handler() { public void handleMessage(Message msg) { Log.d(TAG, "handleMessage:msg:" + msg.what); if(msg.what == MSG_BEGIN_CAMERA_TEST) { openCamera(mCameraIndex); mCameraIndex ++; } else if(msg.what == MSG_STOP_CAMERA_PREVIEW) { Log.d(TAG, "handleMessage:STOP_CAMERA_PREVIEW:index:" + mCameraIndex + ",number:" + mNumberofCameras); if(mCameraIndex == mNumberofCameras) //stop camera,notify test_result { stopCamera(); mInnerHandler.sendEmptyMessageDelayed(MSG_NOTIFY_TEST_RESULT, getsleepafterstop()); } else //stop current camera, start new camera preview. { stopCamera(); mInnerHandler.sendEmptyMessageDelayed(MSG_BEGIN_CAMERA_TEST, 1000); } } /* mCamera = Camera.open(0); if(mCamera == null) { notifyTestResult(0, "open error"); return ; } mCamera.setPreviewCallback(mRawPreviewCallback); try { mCamera.setPreviewDisplay(mSurfaceHolder); } catch (IOException exception) { mCamera.release(); mCamera = null; notifyTestResult(0, "setpreview error"+exception); return; } mCamera.startPreview(); } else if(msg.what == MSG_STOP_CAMERA_PREVIEW) { if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; mInnerHandler.sendEmptyMessageDelayed(MSG_NOTIFY_TEST_RESULT, getsleepafterstop()); } } */ else if(msg.what == MSG_NOTIFY_TEST_RESULT) { notifyTestResult(1, null); } else if(msg.what == MSG_STOP_CAMERA_TEST) { /* if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } */ stopCamera(); //clear MSG_NOTIFY_TEST_RESULT message(may already in the message queue mInnerHandler.removeMessages(MSG_NOTIFY_TEST_RESULT); if(mbPaused == false) { finish();//quit testcamera ui. } } else if(msg.what == MSG_STOP_CAMERA_TEST_FROM_NOTIFY) { //release camera(do not notify test result) /* if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } */ //clear MSG_NOTIFY_TEST_RESULT message(may already in the message queue stopCamera(); mInnerHandler.removeMessages(MSG_NOTIFY_TEST_RESULT); finish();//quit testcamera ui. } } }; //processing event sent form runtimetest service(mostly for battery test failed,all other test should be stopped). private BroadcastReceiver mReceiver = new BroadcastReceiver(){ public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "mReceiver: action:" + action); if(action.equals(ACTION_STOP_CAMERATEST)) { mInnerHandler.sendEmptyMessage(MSG_STOP_CAMERA_TEST_FROM_NOTIFY); } } }; private void notifyTestResult(int result, String extra) { //tell tester thread that one round is done,may begin a new round. Handler workingHandler = mTesterthread.getworkingHandler(); Message msg = workingHandler.obtainMessage((result ==1)?Testerthread.MSG_ONEROUND_FINISHED:Testerthread.MSG_ONEROUND_FAILED); Bundle bundle = new Bundle(); bundle.putInt("result", result); // 0, failed.1,success. if(result != 1) { bundle.putString("error_code", extra); } msg.setData(bundle); workingHandler.sendMessage(msg); //send message to workingthread. } public static void setCommHandler(Handler handler) { mCommHandler = handler; } @Override public void onCreate(Bundle paramBundle) { // TODO Auto-generated method stub super.onCreate(paramBundle); setContentView(R.layout.camera); getWindow().setFormat(0); mSurfaceView = (SurfaceView)findViewById(R.id.surface_view); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); Intent intent = getIntent(); int testcount = intent.getIntExtra("count", 10); int caseid = intent.getIntExtra("caseid", 0); //get camera number mNumberofCameras = Camera.getNumberOfCameras(); mCameraIndex = 0; Log.d(TAG, "onCreate:mNumberofCameras:" + mNumberofCameras); //register filter for processing stop event sent from runtimetestservice(mostly for battery test failed) IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_STOP_CAMERATEST); registerReceiver(mReceiver, filter); mTesterthread = new Testerthread(TAG, caseid, Testerthread.TESTTYPE_COUNT, testcount); mTesterthread.setTesterInterface(this); mTesterthread.setoutHandler(mCommHandler); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause:mbUserPressBack:" + mbUserPressBack); if(mbUserPressBack == true) { onstopTest(); //stop tester thread: ABORTED msg will be notified from the tester thread. mTesterthread.stopTesterThread(); } else { mbPaused = true; //should be set before call onstopTest() onstopTest(); } } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume:mbPaused:" + mbPaused); if(mbPaused == true) { //start camera onstartTest(); } } //only process user back key public boolean onKeyDown(int keyCode, KeyEvent event) { int keycode = event.getKeyCode(); Log.d(TAG, "onKeyDown:keycode:" + keycode); if(keycode == KeyEvent.KEYCODE_BACK) { mbUserPressBack = true; } return super.onKeyDown(keyCode, event); } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated:mbPaued:" + mbPaused); //start tester thread after surface view created.otherwise,preview can not be displayed. if(mbPaused == false) //for paused conditon,test thread is still running. { mTesterthread.startTesterThread(); //begin the test thread. } else { mbPaused = false; } } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "surfaceDestroyed:mbPaued:" + mbPaused); //do something } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Log.d(TAG, "surfaceChanged:mbPaued:" + mbPaused); //do something } /* * (non-Javadoc) * @see com.huaqin.runtime.Testerthread.TesterInterface */ public void onstartTest() { mCameraIndex = 0; //reset camera index. mInnerHandler.sendEmptyMessage(MSG_BEGIN_CAMERA_TEST); } public void onstopTest() { // TODO Auto-generated method stub mInnerHandler.sendEmptyMessage(MSG_STOP_CAMERA_TEST); } public int onsleepbeforestart() { // TODO Auto-generated method stub return 5000; } public int getsleepafterstop() { return 1000; } private void openCamera(int camera_index) { Log.d(TAG, "openCamera:index" + camera_index); mCamera = Camera.open(camera_index); if(mCamera == null) { notifyTestResult(0, "open error"); return ; } mCamera.setPreviewCallback(mRawPreviewCallback); try { mCamera.setPreviewDisplay(mSurfaceHolder); } catch (IOException exception) { mCamera.release(); mCamera = null; notifyTestResult(0, "setpreview error"+exception); return; } mCamera.startPreview(); } private void stopCamera() { if(mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } } private void waitForPreviewDone() { if (!mPreviewDone.block(WAIT_FOR_COMMAND_TO_COMPLETE)) { Log.v(TAG, "waitForPreviewDone: timeout"); } mPreviewDone.close(); } private final class RawPreviewCallback implements PreviewCallback { public void onPreviewFrame(byte [] rawData, Camera camera) { Log.v(TAG, "Preview callback start"); mCamera.setPreviewCallback(null); mInnerHandler.sendEmptyMessageDelayed(MSG_STOP_CAMERA_PREVIEW, 3000); //preview success, wait 5s before stop preview. } }; }
12,426
0.558345
0.553758
409
29.378973
26.076166
142
false
false
0
0
0
0
0
0
0.518337
false
false
2
012a98bf85db43b8e9ac95ad1c431421c7bb049e
28,621,662,093,347
ae9aa7105bed87bbf884dbce15aba7b1d136f24f
/src/main/java/net/canarymod/api/world/blocks/Dispenser.java
ff50065bfdaa4c2552ac42cba830cbd614a60d1a
[]
no_license
zaurek/CanaryLib
https://github.com/zaurek/CanaryLib
636e2e3be77ac681483106249a2bf598a669c407
acad4689be37f17ab6467db8710a6591f26096ce
refs/heads/master
2021-01-20T23:52:09.999000
2012-07-13T18:06:50
2012-07-13T18:06:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.canarymod.api.world.blocks; import net.canarymod.api.entity.Entity; import net.canarymod.api.inventory.Container; import net.canarymod.api.inventory.Inventory; import net.canarymod.api.inventory.Item; public interface Dispenser extends ComplexBlock, Container<Item>{ /** * Get this dispensers inventory * @return inventory */ public Inventory getInventory(); /** * Activate the dispenser: spawns an item from a random slot. * @return the entity spawned */ public Entity activate(); /** * Dispense the item from the given slot. * @param slot the slot to dispend from * @return the entity spawned */ public Entity dispenseFromSlot(int slot); }
UTF-8
Java
750
java
Dispenser.java
Java
[]
null
[]
package net.canarymod.api.world.blocks; import net.canarymod.api.entity.Entity; import net.canarymod.api.inventory.Container; import net.canarymod.api.inventory.Inventory; import net.canarymod.api.inventory.Item; public interface Dispenser extends ComplexBlock, Container<Item>{ /** * Get this dispensers inventory * @return inventory */ public Inventory getInventory(); /** * Activate the dispenser: spawns an item from a random slot. * @return the entity spawned */ public Entity activate(); /** * Dispense the item from the given slot. * @param slot the slot to dispend from * @return the entity spawned */ public Entity dispenseFromSlot(int slot); }
750
0.677333
0.677333
29
24.862068
20.052902
65
false
false
0
0
0
0
0
0
0.310345
false
false
2
f760c38182d70d1c0ed37d5b25df2dd351f0ea5e
23,467,701,342,781
67e735ab2b0f3190968aa248e80a7b3a570f1101
/hcl_java_tools/Demo_JDBC/src/com/jdbc/demo/AddEmployee.java
556fd11c5de47f5caa56cb08ec4a7261880465e6
[]
no_license
DivyaMaddipudi/HCL_Training
https://github.com/DivyaMaddipudi/HCL_Training
7ed68a19552310093895e12deacf0f019b07b49c
c7a6bd9fbac7f3398e7d68e8dce5f72ed13d14ec
refs/heads/master
2023-01-28T18:33:04.969000
2020-12-08T18:05:32
2020-12-08T18:05:32
304,354,730
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jdbc.demo; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class AddEmployee { public static void main(String[] args) { Statement stmt = null; ResultSet rs = null; try { Connection connection = ConnectionFactory.getConnection(); PreparedStatement pstmt = connection.prepareStatement("insert into employee(ename, salary, did_fk) values (?, ?, ?)"); pstmt.setString(1, "ali"); pstmt.setInt(2, 3000); pstmt.setInt(3, 4); int numOfRecords = pstmt.executeUpdate(); System.out.println(numOfRecords); } catch (SQLException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }
UTF-8
Java
712
java
AddEmployee.java
Java
[]
null
[]
package com.jdbc.demo; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class AddEmployee { public static void main(String[] args) { Statement stmt = null; ResultSet rs = null; try { Connection connection = ConnectionFactory.getConnection(); PreparedStatement pstmt = connection.prepareStatement("insert into employee(ename, salary, did_fk) values (?, ?, ?)"); pstmt.setString(1, "ali"); pstmt.setInt(2, 3000); pstmt.setInt(3, 4); int numOfRecords = pstmt.executeUpdate(); System.out.println(numOfRecords); } catch (SQLException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }
712
0.698034
0.683989
31
21.967741
24.038254
121
false
false
0
0
0
0
0
0
2.129032
false
false
2
a5d2bc218e1aa607514b41b3778b2fb5d0a5a2ad
10,110,353,060,164
51374109cc5ecf1439545a08a5183488b41d0ea2
/src/main/java/com/epam/wizzair/step/cucumber/ServicePageStepsCuc.java
4816066e1525ecf54e9120ef474340e1a30eb4f8
[]
no_license
AliaksandrKrutsko/wizzair-1
https://github.com/AliaksandrKrutsko/wizzair-1
9e1e75ea970d195d1ab56d40ae4bad1cfac4abc9
a47dd85776677d95af43c750688c13e549400c2e
refs/heads/master
2021-01-17T14:18:20.899000
2017-06-09T12:11:18
2017-06-09T12:11:18
84,049,272
0
0
null
true
2017-03-06T08:36:32
2017-03-06T08:36:32
2017-03-03T14:36:45
2017-03-06T08:31:28
64
0
0
0
null
null
null
package com.epam.wizzair.step.cucumber; import com.epam.wizzair.page.ServicesPage; import cucumber.api.java.en.When; /** * Created by Aliaksandr_Krutsko on 6/8/2017. */ public class ServicePageStepsCuc { private ServicesPage servicesPage = new ServicesPage(); @When("^User passes on services$") public void submitServices(){ servicesPage.continueToNextPage(); } @When("^User declines insurance offer$") public void user_declines_insurance() { servicesPage.declineInsurance(); } }
UTF-8
Java
531
java
ServicePageStepsCuc.java
Java
[ { "context": "port cucumber.api.java.en.When;\n\n/**\n * Created by Aliaksandr_Krutsko on 6/8/2017.\n */\npublic class ServicePageStepsCuc", "end": 155, "score": 0.9326919913291931, "start": 137, "tag": "NAME", "value": "Aliaksandr_Krutsko" } ]
null
[]
package com.epam.wizzair.step.cucumber; import com.epam.wizzair.page.ServicesPage; import cucumber.api.java.en.When; /** * Created by Aliaksandr_Krutsko on 6/8/2017. */ public class ServicePageStepsCuc { private ServicesPage servicesPage = new ServicesPage(); @When("^User passes on services$") public void submitServices(){ servicesPage.continueToNextPage(); } @When("^User declines insurance offer$") public void user_declines_insurance() { servicesPage.declineInsurance(); } }
531
0.702448
0.691149
22
23.136364
20.237892
59
false
false
0
0
0
0
0
0
0.272727
false
false
2
579451269220058fe43e540943541df99171c40c
32,538,672,273,885
92ea52278fd3cda4f3ecdac1f521067cb8eea95c
/code/com/nabeeh/webmail/SettingProcess.java
9064a33089078f92590dfed6fc726a16f77736b3
[]
no_license
nghanem/webmailserver
https://github.com/nghanem/webmailserver
baaae3b14a9466e0c9ca5a736a2e076c76ddb6c3
40b81243ea646641b601ac80b8f8afa5e99530ea
refs/heads/master
2021-01-01T18:22:10.302000
2013-06-09T08:34:05
2013-06-09T08:34:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nabeeh.webmail; import java.io.IOException; import java.util.ArrayList; import javax.servlet.http.*; //import other.ContactAPI; public class SettingProcess extends Page { /** * Webmail server Application for 601 class USF * @author Nabeeh Ghanem * @version 1.0 */ public SettingProcess(HttpServletRequest request, HttpServletResponse response) throws IOException { super(request, response); } public void body() { if (session.getAttribute("user") == null) { try { response.sendRedirect("/login"); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String userName = session.getAttribute("user").toString(); String serverName = session.getAttribute("serverName").toString(); if (request.getParameter("setBasicInfo") != null) { String newPassword = request.getParameter("password1"); DBManager.setBasicInfo(userName, newPassword); } else if (request.getParameter("addEmail") != null) { String newEmail = request.getParameter("newEmailAddress"); String newPassword = request.getParameter("newEmailPass1"); DBManager.addNewEmailAccount(userName, newEmail, newPassword); } else { for (int i = 0; ; ++i) { if (request.getParameter("setEmail" + i) != null) { String newPassword = request.getParameter("emailPass" + i).toString(); DBManager.setExistInfo(i, newPassword); break; } if (request.getParameter("deleteEmail" + i) != null) { if (DBManager.getServerId(serverName) == i) { session.removeAttribute("serverName"); } DBManager.deleteEmailAccount(i); break; } } } try { response.sendRedirect("/mail/inbox?foldername=Inbox"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
1,845
java
SettingProcess.java
Java
[ { "context": "il server Application for 601 class USF\n\t* @author Nabeeh Ghanem\n\t* @version 1.0\n\t*/\n\n\tpublic SettingProcess(HttpS", "end": 267, "score": 0.9998939633369446, "start": 254, "tag": "NAME", "value": "Nabeeh Ghanem" }, { "context": "\");\n\t\t\tString newPassword =...
null
[]
package com.nabeeh.webmail; import java.io.IOException; import java.util.ArrayList; import javax.servlet.http.*; //import other.ContactAPI; public class SettingProcess extends Page { /** * Webmail server Application for 601 class USF * @author <NAME> * @version 1.0 */ public SettingProcess(HttpServletRequest request, HttpServletResponse response) throws IOException { super(request, response); } public void body() { if (session.getAttribute("user") == null) { try { response.sendRedirect("/login"); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String userName = session.getAttribute("user").toString(); String serverName = session.getAttribute("serverName").toString(); if (request.getParameter("setBasicInfo") != null) { String newPassword = request.getParameter("password1"); DBManager.setBasicInfo(userName, newPassword); } else if (request.getParameter("addEmail") != null) { String newEmail = request.getParameter("newEmailAddress"); String newPassword = request.getParameter("<PASSWORD>"); DBManager.addNewEmailAccount(userName, newEmail, newPassword); } else { for (int i = 0; ; ++i) { if (request.getParameter("setEmail" + i) != null) { String newPassword = request.getParameter("emailPass" + i).toString(); DBManager.setExistInfo(i, newPassword); break; } if (request.getParameter("deleteEmail" + i) != null) { if (DBManager.getServerId(serverName) == i) { session.removeAttribute("serverName"); } DBManager.deleteEmailAccount(i); break; } } } try { response.sendRedirect("/mail/inbox?foldername=Inbox"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
1,835
0.676423
0.672087
72
24.638889
22.425993
75
false
false
0
0
0
0
0
0
2.805556
false
false
2
6f09eff091f71a769b74cc6f7fd6128a8969602b
25,537,875,584,011
acb0caa3b73f3b63abd10a98fe125aa10e3919a5
/src/test/java/com/acme/demo/broker/controller/BrokerControllerTest.java
e9fa55af76327eb1b0dc8622f9ec85f1c1a87461
[ "MIT" ]
permissive
ammbra/12factor-kube-broker
https://github.com/ammbra/12factor-kube-broker
16a65546b7bd5070b3d08228bb740ada6d428fe4
21e18404e67a0743a9d3bf8178a271f12e9ae054
refs/heads/master
2023-04-28T08:16:35.036000
2019-08-24T11:43:05
2019-08-24T11:43:05
200,270,933
1
1
MIT
false
2023-04-14T17:39:58
2019-08-02T17:07:31
2019-08-27T17:59:29
2023-04-14T17:39:57
37
1
1
1
Java
false
false
package com.acme.demo.broker.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.acme.demo.broker.App; import com.acme.demo.broker.controller.BrokerController; @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(classes = { com.acme.demo.broker.DatabaseConfig.class, App.class }) @TestPropertySource(locations = "classpath:application.properties") public class BrokerControllerTest { @Autowired private MockMvc mvc; @MockBean private BrokerController service; @Autowired private WebApplicationContext webApplicationContext; @Before public void init() throws Exception { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void getAllBrokers() throws Exception { mvc.perform(get("/broker").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } }
UTF-8
Java
1,683
java
BrokerControllerTest.java
Java
[]
null
[]
package com.acme.demo.broker.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.acme.demo.broker.App; import com.acme.demo.broker.controller.BrokerController; @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(classes = { com.acme.demo.broker.DatabaseConfig.class, App.class }) @TestPropertySource(locations = "classpath:application.properties") public class BrokerControllerTest { @Autowired private MockMvc mvc; @MockBean private BrokerController service; @Autowired private WebApplicationContext webApplicationContext; @Before public void init() throws Exception { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void getAllBrokers() throws Exception { mvc.perform(get("/broker").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } }
1,683
0.827689
0.827094
49
33.346939
29.675491
97
false
false
0
0
0
0
0
0
0.836735
false
false
2
67092bc89c470cd47998dcbdbd773d7607e9b5f7
39,075,612,462,676
c2561b452e407487a276bdbd06ba8f768ebdb9e1
/src/main/java/com/spring/classes/Client.java
61c1ce0b6c40d4c3bd5c98bd3c32439f1a8f3f6b
[]
no_license
AsmaaJittou/Project_Ecommerce_J2EE_SPRING
https://github.com/AsmaaJittou/Project_Ecommerce_J2EE_SPRING
a3a0899922b37a4df0901eb407c9a9ef2d0a8e86
63f908b3207f66b53d1d8f468302e3ae9f43369f
refs/heads/master
2023-01-31T10:08:37.381000
2020-12-18T09:02:00
2020-12-18T09:02:00
322,540,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spring.classes; public class Client { private int id; private String nom; private String prenom; private String password; private String email; private String adresse; private String tel; private String pays; public Client() { super(); } public Client( String nom, String prenom,String password,String email,String adresse,String tel,String pays) {//SetId(id); SetNom( nom); SetPrenom( prenom); SetEmail(email); SetAdresse(adresse); SetPass(password); SetTel(tel); SetPays(pays); } @Override public String toString() { return "Client [id=" + id + ", nom=" + nom + ", prenom=" + prenom + ", password=" + password + ", email=" + email + ", adresse=" + adresse + ", tel=" + tel + ", pays=" + pays + "]"; } public int getId(){ return id;} public String getNom() {return nom;} public String getPrenom() {return prenom;} public String getEmail() {return email;} public String getPass() {return password;} public String getAdresse() {return adresse;} public String getTel() {return tel;} public String getPays() {return pays;} public void SetId(int id) {this.id=id;} public void SetNom(String nom){this.nom=nom;} public void SetPrenom(String prenom){this.prenom=prenom;} public void SetEmail(String email){this.email=email;} public void SetAdresse(String adresse){this.adresse=adresse;} public void SetPass(String password){this.password=password;} public void SetTel( String tel) {this.tel=tel;} public void SetPays(String pays) {this.pays=pays;} }
UTF-8
Java
1,538
java
Client.java
Java
[ { "context": "m=\" + nom + \", prenom=\" + prenom + \", password=\" + password + \", email=\" + email\n\t\t\t+ \", adresse=\" + adresse ", "end": 681, "score": 0.996875524520874, "start": 673, "tag": "PASSWORD", "value": "password" }, { "context": ") {return email;}\n\tpublic String ...
null
[]
package com.spring.classes; public class Client { private int id; private String nom; private String prenom; private String password; private String email; private String adresse; private String tel; private String pays; public Client() { super(); } public Client( String nom, String prenom,String password,String email,String adresse,String tel,String pays) {//SetId(id); SetNom( nom); SetPrenom( prenom); SetEmail(email); SetAdresse(adresse); SetPass(password); SetTel(tel); SetPays(pays); } @Override public String toString() { return "Client [id=" + id + ", nom=" + nom + ", prenom=" + prenom + ", password=" + <PASSWORD> + ", email=" + email + ", adresse=" + adresse + ", tel=" + tel + ", pays=" + pays + "]"; } public int getId(){ return id;} public String getNom() {return nom;} public String getPrenom() {return prenom;} public String getEmail() {return email;} public String getPass() {return <PASSWORD>;} public String getAdresse() {return adresse;} public String getTel() {return tel;} public String getPays() {return pays;} public void SetId(int id) {this.id=id;} public void SetNom(String nom){this.nom=nom;} public void SetPrenom(String prenom){this.prenom=prenom;} public void SetEmail(String email){this.email=email;} public void SetAdresse(String adresse){this.adresse=adresse;} public void SetPass(String password){this.password=<PASSWORD>;} public void SetTel( String tel) {this.tel=tel;} public void SetPays(String pays) {this.pays=pays;} }
1,544
0.691808
0.691808
58
25.517241
25.006372
114
false
false
0
0
0
0
0
0
1.655172
false
false
2
2c59bd706f93e4c06b4b6647529f0ac2334de1fb
35,991,825,971,186
d3a59ef8704a4a6163f2154bd4cbcdedbd859387
/src/com/utils/ConnectionProvider.java
66ae422ec7890f89c89dc9cf4c08aa73764d9c43
[]
no_license
dranandrao/ComponentTracker
https://github.com/dranandrao/ComponentTracker
fb302f9a829e56049f535f0d3b52e89098a0e0cc
be201e75cda9ab4fbc968de580df344a716887f9
refs/heads/master
2021-04-29T20:52:21.650000
2018-04-08T08:38:39
2018-04-08T08:38:39
121,605,416
0
2
null
false
2018-03-27T08:57:33
2018-02-15T08:19:01
2018-03-27T07:53:47
2018-03-27T08:57:33
21
0
1
0
Java
false
null
package com.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author dranandrao * */ public class ConnectionProvider implements Provider { private Connection conn; public Connection getConnection() { try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub return conn; } }
UTF-8
Java
613
java
ConnectionProvider.java
Java
[ { "context": "ger;\nimport java.sql.SQLException;\n\n/**\n * @author dranandrao\n *\n */\npublic class ConnectionProvider implements", "end": 135, "score": 0.999590277671814, "start": 125, "tag": "USERNAME", "value": "dranandrao" } ]
null
[]
package com.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author dranandrao * */ public class ConnectionProvider implements Provider { private Connection conn; public Connection getConnection() { try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub return conn; } }
613
0.719413
0.719413
29
20.137932
17.0187
63
false
false
0
0
0
0
0
0
1.551724
false
false
2
9fead63115bbf156750bacdea760891851d34037
39,513,699,133,427
6201bd61a1a2690a63d7a767cd3be907a748176e
/greendaotest/src/main/java/com/example/greendaotest/MainActivity.java
573b606c86d672f1216e68308f9c01afb0ab36d2
[]
no_license
LiyDzz/Model
https://github.com/LiyDzz/Model
d9b887ab5d88b0b356845c283212ab509e2a9b3d
a91330c4e2f266ee081e46afe64b1e32e0ca3311
refs/heads/master
2021-01-20T14:23:54.220000
2017-05-08T08:28:05
2017-05-08T08:28:05
90,604,227
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.greendaotest; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.db.DaoMaster; import com.example.db.DaoSession; import com.example.db.Student; import com.example.db.StudentDao; import org.greenrobot.greendao.query.Query; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends Activity { @Bind(R.id.et_number) EditText etNumber; @Bind(R.id.et_name) EditText etName; @Bind(R.id.et_sex) EditText etSex; @Bind(R.id.et_age) EditText etAge; @Bind(R.id.bt_save) Button btSave; @Bind(R.id.bt_delete) Button btDelete; @Bind(R.id.bt_update) Button btUpdate; @Bind(R.id.bt_query) Button btQuery; private StudentDao studentDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "Student.db", null); SQLiteDatabase database = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(database); DaoSession daoSession = daoMaster.newSession(); studentDao = daoSession.getStudentDao(); } @OnClick({R.id.bt_save, R.id.bt_delete, R.id.bt_update, R.id.bt_query}) public void onViewClicked(View view) { String number = etNumber.getText().toString().trim(); String name = etName.getText().toString().trim(); String sex = etSex.getText().toString().trim(); String age = etAge.getText().toString().trim(); Student student = new Student(); student.setNumber(number); student.setName(name); student.setAge(age); student.setSex(sex); switch (view.getId()) { case R.id.bt_save: long insert = studentDao.insert(student); Log.e("AAA", "插入了" + insert + "行数据"); break; case R.id.bt_delete: Student student11 = new Student(); student.setId(1L); studentDao.delete(student11); break; case R.id.bt_update: Student stu = new Student(); stu.setId(3L); stu.setName("韩韩"); stu.setAge("25"); stu.setSex("bunanbunv"); studentDao.update(stu); break; case R.id.bt_query: QueryBuilder<Student> studentQueryBuilder = studentDao.queryBuilder(); Query<Student> build = studentQueryBuilder.where(StudentDao.Properties.Name.eq("韩韩")).build(); List<Student> list = build.list(); for (Student student1:list){ Log.e("tag","名字为:"+student1.getName()); } break; } } }
UTF-8
Java
3,218
java
MainActivity.java
Java
[ { "context": "tudent.setNumber(number);\n student.setName(name);\n student.setAge(age);\n student.se", "end": 2013, "score": 0.9854331612586975, "start": 2009, "tag": "NAME", "value": "name" }, { "context": " stu.setId(3L);\n stu.setName(\"韩韩\...
null
[]
package com.example.greendaotest; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.db.DaoMaster; import com.example.db.DaoSession; import com.example.db.Student; import com.example.db.StudentDao; import org.greenrobot.greendao.query.Query; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends Activity { @Bind(R.id.et_number) EditText etNumber; @Bind(R.id.et_name) EditText etName; @Bind(R.id.et_sex) EditText etSex; @Bind(R.id.et_age) EditText etAge; @Bind(R.id.bt_save) Button btSave; @Bind(R.id.bt_delete) Button btDelete; @Bind(R.id.bt_update) Button btUpdate; @Bind(R.id.bt_query) Button btQuery; private StudentDao studentDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "Student.db", null); SQLiteDatabase database = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(database); DaoSession daoSession = daoMaster.newSession(); studentDao = daoSession.getStudentDao(); } @OnClick({R.id.bt_save, R.id.bt_delete, R.id.bt_update, R.id.bt_query}) public void onViewClicked(View view) { String number = etNumber.getText().toString().trim(); String name = etName.getText().toString().trim(); String sex = etSex.getText().toString().trim(); String age = etAge.getText().toString().trim(); Student student = new Student(); student.setNumber(number); student.setName(name); student.setAge(age); student.setSex(sex); switch (view.getId()) { case R.id.bt_save: long insert = studentDao.insert(student); Log.e("AAA", "插入了" + insert + "行数据"); break; case R.id.bt_delete: Student student11 = new Student(); student.setId(1L); studentDao.delete(student11); break; case R.id.bt_update: Student stu = new Student(); stu.setId(3L); stu.setName("韩韩"); stu.setAge("25"); stu.setSex("bunanbunv"); studentDao.update(stu); break; case R.id.bt_query: QueryBuilder<Student> studentQueryBuilder = studentDao.queryBuilder(); Query<Student> build = studentQueryBuilder.where(StudentDao.Properties.Name.eq("韩韩")).build(); List<Student> list = build.list(); for (Student student1:list){ Log.e("tag","名字为:"+student1.getName()); } break; } } }
3,218
0.612226
0.609091
101
30.584158
21.056391
110
false
false
0
0
0
0
0
0
0.693069
false
false
2
353498b83f9723ec81c1d1bdab2cd3e5c43ac49a
27,668,179,388,181
dcdb7b92f3d279b57b80bafd49d3e8484c6d0bef
/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/LogsCLI.java
d3b44a7764aedad560e4c698f192bba329b04b63
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
naver/hadoop
https://github.com/naver/hadoop
87b5684945da4d1a6002bb2039ac35986b64eb64
0c0a80f96283b5a7be234663e815bc04bafc8be2
refs/heads/master
2023-08-24T16:06:00.884000
2022-11-03T00:31:17
2022-11-03T00:31:17
106,681,970
42
39
Apache-2.0
false
2022-11-03T00:31:18
2017-10-12T11:06:22
2022-11-03T00:30:28
2022-11-03T00:31:17
82,150
34
23
1
Java
false
false
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.client.cli; import java.io.IOException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Tool; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.logaggregation.LogCLIHelpers; import org.apache.hadoop.yarn.util.ConverterUtils; import com.google.common.annotations.VisibleForTesting; @Public @Evolving public class LogsCLI extends Configured implements Tool { private static final String CONTAINER_ID_OPTION = "containerId"; private static final String APPLICATION_ID_OPTION = "applicationId"; private static final String NODE_ADDRESS_OPTION = "nodeAddress"; private static final String APP_OWNER_OPTION = "appOwner"; public static final String HELP_CMD = "help"; @Override public int run(String[] args) throws Exception { Options opts = new Options(); opts.addOption(HELP_CMD, false, "Displays help for all commands."); Option appIdOpt = new Option(APPLICATION_ID_OPTION, true, "ApplicationId (required)"); appIdOpt.setRequired(true); opts.addOption(appIdOpt); opts.addOption(CONTAINER_ID_OPTION, true, "ContainerId (must be specified if node address is specified)"); opts.addOption(NODE_ADDRESS_OPTION, true, "NodeAddress in the format " + "nodename:port (must be specified if container id is specified)"); opts.addOption(APP_OWNER_OPTION, true, "AppOwner (assumed to be current user if not specified)"); opts.getOption(APPLICATION_ID_OPTION).setArgName("Application ID"); opts.getOption(CONTAINER_ID_OPTION).setArgName("Container ID"); opts.getOption(NODE_ADDRESS_OPTION).setArgName("Node Address"); opts.getOption(APP_OWNER_OPTION).setArgName("Application Owner"); Options printOpts = new Options(); printOpts.addOption(opts.getOption(HELP_CMD)); printOpts.addOption(opts.getOption(CONTAINER_ID_OPTION)); printOpts.addOption(opts.getOption(NODE_ADDRESS_OPTION)); printOpts.addOption(opts.getOption(APP_OWNER_OPTION)); if (args.length < 1) { printHelpMessage(printOpts); return -1; } if (args[0].equals("-help")) { printHelpMessage(printOpts); return 0; } CommandLineParser parser = new GnuParser(); String appIdStr = null; String containerIdStr = null; String nodeAddress = null; String appOwner = null; try { CommandLine commandLine = parser.parse(opts, args, true); appIdStr = commandLine.getOptionValue(APPLICATION_ID_OPTION); containerIdStr = commandLine.getOptionValue(CONTAINER_ID_OPTION); nodeAddress = commandLine.getOptionValue(NODE_ADDRESS_OPTION); appOwner = commandLine.getOptionValue(APP_OWNER_OPTION); } catch (ParseException e) { System.err.println("options parsing failed: " + e.getMessage()); printHelpMessage(printOpts); return -1; } if (appIdStr == null) { System.err.println("ApplicationId cannot be null!"); printHelpMessage(printOpts); return -1; } ApplicationId appId = null; try { appId = ConverterUtils.toApplicationId(appIdStr); } catch (Exception e) { System.err.println("Invalid ApplicationId specified"); return -1; } try { int resultCode = verifyApplicationState(appId); if (resultCode != 0) { System.out.println("Logs are not avaiable right now."); return resultCode; } } catch (Exception e) { System.err.println("Unable to get ApplicationState." + " Attempting to fetch logs directly from the filesystem."); } LogCLIHelpers logCliHelper = new LogCLIHelpers(); logCliHelper.setConf(getConf()); if (appOwner == null || appOwner.isEmpty()) { appOwner = UserGroupInformation.getCurrentUser().getShortUserName(); } int resultCode = 0; if (containerIdStr == null && nodeAddress == null) { resultCode = logCliHelper.dumpAllContainersLogs(appId, appOwner, System.out); } else if ((containerIdStr == null && nodeAddress != null) || (containerIdStr != null && nodeAddress == null)) { System.out.println("ContainerId or NodeAddress cannot be null!"); printHelpMessage(printOpts); resultCode = -1; } else { resultCode = logCliHelper.dumpAContainersLogs(appIdStr, containerIdStr, nodeAddress, appOwner); } return resultCode; } private int verifyApplicationState(ApplicationId appId) throws IOException, YarnException { YarnClient yarnClient = createYarnClient(); try { ApplicationReport appReport = yarnClient.getApplicationReport(appId); switch (appReport.getYarnApplicationState()) { case NEW: case NEW_SAVING: case SUBMITTED: return -1; case ACCEPTED: case RUNNING: case FAILED: case FINISHED: case KILLED: default: break; } } finally { yarnClient.close(); } return 0; } @VisibleForTesting protected YarnClient createYarnClient() { YarnClient yarnClient = YarnClient.createYarnClient(); yarnClient.init(getConf()); yarnClient.start(); return yarnClient; } public static void main(String[] args) throws Exception { Configuration conf = new YarnConfiguration(); LogsCLI logDumper = new LogsCLI(); logDumper.setConf(conf); int exitCode = logDumper.run(args); System.exit(exitCode); } private void printHelpMessage(Options options) { System.out.println("Retrieve logs for completed YARN applications."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("yarn logs -applicationId <application ID> [OPTIONS]", new Options()); formatter.setSyntaxPrefix(""); formatter.printHelp("general options are:", options); } }
UTF-8
Java
7,374
java
LogsCLI.java
Java
[]
null
[]
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.client.cli; import java.io.IOException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Tool; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.logaggregation.LogCLIHelpers; import org.apache.hadoop.yarn.util.ConverterUtils; import com.google.common.annotations.VisibleForTesting; @Public @Evolving public class LogsCLI extends Configured implements Tool { private static final String CONTAINER_ID_OPTION = "containerId"; private static final String APPLICATION_ID_OPTION = "applicationId"; private static final String NODE_ADDRESS_OPTION = "nodeAddress"; private static final String APP_OWNER_OPTION = "appOwner"; public static final String HELP_CMD = "help"; @Override public int run(String[] args) throws Exception { Options opts = new Options(); opts.addOption(HELP_CMD, false, "Displays help for all commands."); Option appIdOpt = new Option(APPLICATION_ID_OPTION, true, "ApplicationId (required)"); appIdOpt.setRequired(true); opts.addOption(appIdOpt); opts.addOption(CONTAINER_ID_OPTION, true, "ContainerId (must be specified if node address is specified)"); opts.addOption(NODE_ADDRESS_OPTION, true, "NodeAddress in the format " + "nodename:port (must be specified if container id is specified)"); opts.addOption(APP_OWNER_OPTION, true, "AppOwner (assumed to be current user if not specified)"); opts.getOption(APPLICATION_ID_OPTION).setArgName("Application ID"); opts.getOption(CONTAINER_ID_OPTION).setArgName("Container ID"); opts.getOption(NODE_ADDRESS_OPTION).setArgName("Node Address"); opts.getOption(APP_OWNER_OPTION).setArgName("Application Owner"); Options printOpts = new Options(); printOpts.addOption(opts.getOption(HELP_CMD)); printOpts.addOption(opts.getOption(CONTAINER_ID_OPTION)); printOpts.addOption(opts.getOption(NODE_ADDRESS_OPTION)); printOpts.addOption(opts.getOption(APP_OWNER_OPTION)); if (args.length < 1) { printHelpMessage(printOpts); return -1; } if (args[0].equals("-help")) { printHelpMessage(printOpts); return 0; } CommandLineParser parser = new GnuParser(); String appIdStr = null; String containerIdStr = null; String nodeAddress = null; String appOwner = null; try { CommandLine commandLine = parser.parse(opts, args, true); appIdStr = commandLine.getOptionValue(APPLICATION_ID_OPTION); containerIdStr = commandLine.getOptionValue(CONTAINER_ID_OPTION); nodeAddress = commandLine.getOptionValue(NODE_ADDRESS_OPTION); appOwner = commandLine.getOptionValue(APP_OWNER_OPTION); } catch (ParseException e) { System.err.println("options parsing failed: " + e.getMessage()); printHelpMessage(printOpts); return -1; } if (appIdStr == null) { System.err.println("ApplicationId cannot be null!"); printHelpMessage(printOpts); return -1; } ApplicationId appId = null; try { appId = ConverterUtils.toApplicationId(appIdStr); } catch (Exception e) { System.err.println("Invalid ApplicationId specified"); return -1; } try { int resultCode = verifyApplicationState(appId); if (resultCode != 0) { System.out.println("Logs are not avaiable right now."); return resultCode; } } catch (Exception e) { System.err.println("Unable to get ApplicationState." + " Attempting to fetch logs directly from the filesystem."); } LogCLIHelpers logCliHelper = new LogCLIHelpers(); logCliHelper.setConf(getConf()); if (appOwner == null || appOwner.isEmpty()) { appOwner = UserGroupInformation.getCurrentUser().getShortUserName(); } int resultCode = 0; if (containerIdStr == null && nodeAddress == null) { resultCode = logCliHelper.dumpAllContainersLogs(appId, appOwner, System.out); } else if ((containerIdStr == null && nodeAddress != null) || (containerIdStr != null && nodeAddress == null)) { System.out.println("ContainerId or NodeAddress cannot be null!"); printHelpMessage(printOpts); resultCode = -1; } else { resultCode = logCliHelper.dumpAContainersLogs(appIdStr, containerIdStr, nodeAddress, appOwner); } return resultCode; } private int verifyApplicationState(ApplicationId appId) throws IOException, YarnException { YarnClient yarnClient = createYarnClient(); try { ApplicationReport appReport = yarnClient.getApplicationReport(appId); switch (appReport.getYarnApplicationState()) { case NEW: case NEW_SAVING: case SUBMITTED: return -1; case ACCEPTED: case RUNNING: case FAILED: case FINISHED: case KILLED: default: break; } } finally { yarnClient.close(); } return 0; } @VisibleForTesting protected YarnClient createYarnClient() { YarnClient yarnClient = YarnClient.createYarnClient(); yarnClient.init(getConf()); yarnClient.start(); return yarnClient; } public static void main(String[] args) throws Exception { Configuration conf = new YarnConfiguration(); LogsCLI logDumper = new LogsCLI(); logDumper.setConf(conf); int exitCode = logDumper.run(args); System.exit(exitCode); } private void printHelpMessage(Options options) { System.out.println("Retrieve logs for completed YARN applications."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("yarn logs -applicationId <application ID> [OPTIONS]", new Options()); formatter.setSyntaxPrefix(""); formatter.printHelp("general options are:", options); } }
7,374
0.713588
0.711419
204
35.14706
24.838457
94
false
false
0
0
0
0
0
0
0.647059
false
false
2
8a700fa99af1ca9f8f7cd2b5d433837ad4f7940c
8,959,301,846,742
88640ad5fde41cc5a585b561aa2b6c110703aa9f
/src/gettersSetters/ProduitsFinies.java
12dd34a77c0444627089f18385ec5b88cf32ba12
[]
no_license
Landrice/AmicaleGeMaPre
https://github.com/Landrice/AmicaleGeMaPre
0207f27934747b6d3d23ccb44f53a86bd76bc0bd
210185a8249907e8317d3de6aa76bc356c4fe659
refs/heads/master
2020-04-13T23:50:11.882000
2018-12-29T14:27:50
2018-12-29T14:27:50
null
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 gettersSetters; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * * @author Ralande */ public class ProduitsFinies { public String id; public String produit; public String report; public String nombreunite; public String production; public String unite; public String amicale; public String stock; public String date; public String quattiteingredients; public String idingredients; public ObservableList<String> allpr = FXCollections.observableArrayList(); public ObservableList<ListProduitsFinies> prLists = FXCollections.observableArrayList(); }
UTF-8
Java
867
java
ProduitsFinies.java
Java
[ { "context": "collections.ObservableList;\r\n\r\n/**\r\n *\r\n * @author Ralande\r\n */\r\npublic class ProduitsFinies {\r\n public ", "end": 331, "score": 0.9876120090484619, "start": 324, "tag": "NAME", "value": "Ralande" } ]
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 gettersSetters; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * * @author Ralande */ public class ProduitsFinies { public String id; public String produit; public String report; public String nombreunite; public String production; public String unite; public String amicale; public String stock; public String date; public String quattiteingredients; public String idingredients; public ObservableList<String> allpr = FXCollections.observableArrayList(); public ObservableList<ListProduitsFinies> prLists = FXCollections.observableArrayList(); }
867
0.726644
0.726644
29
27.896551
23.746281
92
false
false
0
0
0
0
0
0
0.655172
false
false
2
2cf802fb31b61a5b419f4fb7e8fc61121dc4f59c
38,749,194,994,610
b83a4fe5fa09f20ca872e57bef69b40fde6df4f3
/repository/perseo-backend/src/main/java/com/perseo/backend/models/entity/HistoriasClinicas.java
f55547f816f437a3fc58e8c9badf09207b6b14cc
[]
no_license
FranAdduci/perseo-back
https://github.com/FranAdduci/perseo-back
788a4589b312d273f2238ef4f1a6fa7a95d92c63
eb3fa67adcb8ee5cec1c1cd0c70a938d05887429
refs/heads/master
2022-12-01T08:19:23.501000
2020-08-14T22:27:45
2020-08-14T22:27:45
287,635,061
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.perseo.backend.models.entity; public class HistoriasClinicas { }
UTF-8
Java
84
java
HistoriasClinicas.java
Java
[]
null
[]
package com.perseo.backend.models.entity; public class HistoriasClinicas { }
84
0.75
0.75
5
14.8
17.948816
41
false
false
0
0
0
0
0
0
0.2
false
false
2
f8905a44ed6130502b2f6e24e244f70de2f41254
12,429,635,395,703
328811cf2412df812911e34365a94be817f223e6
/src/main/java/pe/edu/upc/ezshipping/models/repositories/TipoClienteRepository.java
3761e5281241ba97d86f6b59a4753cdecad3fe04
[]
no_license
JoseC120900/ezshipping-TF
https://github.com/JoseC120900/ezshipping-TF
9acb93d681b1979341bd1c7c727bf29071a30acf
6c3d704ce262c25a8bcfa5ef5864b3ab953bad12
refs/heads/master
2022-12-29T16:14:19.701000
2020-10-17T21:31:34
2020-10-17T21:31:34
304,681,494
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.edu.upc.ezshipping.models.repositories; import java.util.Optional; import pe.edu.upc.ezshipping.models.entities.TipoCliente; public interface TipoClienteRepository extends JpaRepository<TipoCliente, Integer> { Optional<TipoCliente> findByNombre(String nombre) throws Exception; }
UTF-8
Java
295
java
TipoClienteRepository.java
Java
[]
null
[]
package pe.edu.upc.ezshipping.models.repositories; import java.util.Optional; import pe.edu.upc.ezshipping.models.entities.TipoCliente; public interface TipoClienteRepository extends JpaRepository<TipoCliente, Integer> { Optional<TipoCliente> findByNombre(String nombre) throws Exception; }
295
0.833898
0.833898
9
31.777779
31.653603
84
false
false
0
0
0
0
0
0
0.666667
false
false
2
54e603854257b7cbc99a74dc5be196501de31a01
29,764,123,415,981
a6507c591cbf51a62b8388c843fd9b182caf3d53
/src/main/java/de/dfki/asr/atlas/business/scratchSpace/ScratchSpace.java
bd30827f36ebbd5cf7252300b8874b791477e5d6
[ "Apache-2.0", "MIT" ]
permissive
dfki-asr/atlas-server
https://github.com/dfki-asr/atlas-server
6dbe115ee7a6092967b10567c5df23bd8245b180
20f1ab260098d753da368c0011cc0c453b2c699b
refs/heads/master
2021-01-21T04:54:08.445000
2018-10-18T15:24:48
2018-10-18T15:24:48
32,386,407
0
0
null
false
2016-03-23T13:35:30
2015-03-17T10:19:09
2015-03-17T10:25:52
2016-03-23T13:35:30
737
0
0
1
JavaScript
null
null
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ package de.dfki.asr.atlas.business.scratchSpace; import java.io.InputStream; import java.util.UUID; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; @Named @RequestScoped public class ScratchSpace { @Inject Session jcrSession; private final String relativePathToScratch = "scratch"; public String addAssetFileToScratch(InputStream in, String assetName) throws RepositoryException { Node scratchSpace = getScratchRootNode(); String nodeName = UUID.randomUUID().toString(); Node newFileNode = scratchSpace.addNode(nodeName, "nt:file"); Node contentNode = newFileNode.addNode("jcr:content", "nt:resource"); Binary binary = jcrSession.getValueFactory().createBinary(in); contentNode.setProperty("jcr:data", binary); jcrSession.save(); return nodeName; } public void removeFile(String fileNode) throws RepositoryException { jcrSession.removeItem("/" + relativePathToScratch + "/" + fileNode); } private Node getScratchRootNode() throws RepositoryException { Node root = jcrSession.getRootNode(); ensureNodeHasNodeChildren(root, relativePathToScratch); return root.getNode(relativePathToScratch); } private void ensureNodeHasNodeChildren(Node root, String path) throws RepositoryException { if (!root.hasNode(path)) { root.addNode(path); } } }
UTF-8
Java
1,742
java
ScratchSpace.java
Java
[]
null
[]
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ package de.dfki.asr.atlas.business.scratchSpace; import java.io.InputStream; import java.util.UUID; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; @Named @RequestScoped public class ScratchSpace { @Inject Session jcrSession; private final String relativePathToScratch = "scratch"; public String addAssetFileToScratch(InputStream in, String assetName) throws RepositoryException { Node scratchSpace = getScratchRootNode(); String nodeName = UUID.randomUUID().toString(); Node newFileNode = scratchSpace.addNode(nodeName, "nt:file"); Node contentNode = newFileNode.addNode("jcr:content", "nt:resource"); Binary binary = jcrSession.getValueFactory().createBinary(in); contentNode.setProperty("jcr:data", binary); jcrSession.save(); return nodeName; } public void removeFile(String fileNode) throws RepositoryException { jcrSession.removeItem("/" + relativePathToScratch + "/" + fileNode); } private Node getScratchRootNode() throws RepositoryException { Node root = jcrSession.getRootNode(); ensureNodeHasNodeChildren(root, relativePathToScratch); return root.getNode(relativePathToScratch); } private void ensureNodeHasNodeChildren(Node root, String path) throws RepositoryException { if (!root.hasNode(path)) { root.addNode(path); } } }
1,742
0.771527
0.770379
54
31.25926
27.6989
99
false
false
0
0
0
0
0
0
1.351852
false
false
2
892e70252aeddf9a250b8a12fd582450d4abb8d9
25,245,817,791,944
adca570db8c6a0d2386acfed68b55f6aa789266e
/app/src/main/java/ir/sharif/mobile/simple_task_management/repository/RewardRepository.java
709081659bd3d8c6827d9abab8561c2f3ba80005
[]
no_license
taslimisina/mobile-project
https://github.com/taslimisina/mobile-project
60974219eda817e9e3d2be7776ee1eff74c0683f
3865b3a7f959960e22d58f2d68475720a65a01a1
refs/heads/main
2023-06-21T03:31:21.394000
2021-07-23T12:16:52
2021-07-23T12:16:52
384,528,797
0
0
null
false
2021-07-17T20:50:33
2021-07-09T19:06:57
2021-07-15T03:55:52
2021-07-17T20:50:32
567
0
0
0
Java
false
false
package ir.sharif.mobile.simple_task_management.repository; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import ir.sharif.mobile.simple_task_management.model.Reward; public class RewardRepository implements BaseRepository<Reward> { private static final String TABLE_NAME = "reward"; public static final String CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "title VARCHAR(150) NOT NULL, " + " amount INTEGER, description text);"; public static final String DELETE_TASK_PATTERN = "DELETE FROM " + TABLE_NAME + " " + "WHERE id = %d;"; public static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME + ";"; private final DbHelper dbHelper; public RewardRepository(DbHelper dbHelper) { this.dbHelper = dbHelper; SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase(); // writableDatabase.execSQL(DROP_TABLE); writableDatabase.execSQL(CREATE_TABLE_QUERY); } @Override public Reward save(Reward object) { ContentValues values = new ContentValues(); if (object.getId() != null) { values.put("id", object.getId()); } values.put("title", object.getTitle()); if (object.getDescription() != null) values.put("description", object.getDescription()); values.put("amount", object.getAmount()); long insert = dbHelper.getWritableDatabase().replaceOrThrow(TABLE_NAME, null, values); return object.setId(insert); } @Override public List<Reward> findAll() { Cursor cursor = dbHelper.getReadableDatabase().rawQuery("SELECT * FROM " + TABLE_NAME, null); return parseResults(cursor); } @Override public void delete(long id) { String query = String.format(DELETE_TASK_PATTERN, id); dbHelper.getWritableDatabase().execSQL(query); } private List<Reward> parseResults(Cursor response) { List<Reward> items = new ArrayList<>(); int idIndex = response.getColumnIndex("id"); int titleIndex = response.getColumnIndex("title"); int desIndex = response.getColumnIndex("description"); int amountIndex = response.getColumnIndex("amount"); while (response.moveToNext()) { String description = null; if (!response.isNull(desIndex)) { description = response.getString(desIndex); } items.add(new Reward() .setId(response.getLong(idIndex)) .setTitle(response.getString(titleIndex)) .setDescription(description) .setAmount(response.getInt(amountIndex))); } return items; } }
UTF-8
Java
2,937
java
RewardRepository.java
Java
[]
null
[]
package ir.sharif.mobile.simple_task_management.repository; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import ir.sharif.mobile.simple_task_management.model.Reward; public class RewardRepository implements BaseRepository<Reward> { private static final String TABLE_NAME = "reward"; public static final String CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "title VARCHAR(150) NOT NULL, " + " amount INTEGER, description text);"; public static final String DELETE_TASK_PATTERN = "DELETE FROM " + TABLE_NAME + " " + "WHERE id = %d;"; public static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME + ";"; private final DbHelper dbHelper; public RewardRepository(DbHelper dbHelper) { this.dbHelper = dbHelper; SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase(); // writableDatabase.execSQL(DROP_TABLE); writableDatabase.execSQL(CREATE_TABLE_QUERY); } @Override public Reward save(Reward object) { ContentValues values = new ContentValues(); if (object.getId() != null) { values.put("id", object.getId()); } values.put("title", object.getTitle()); if (object.getDescription() != null) values.put("description", object.getDescription()); values.put("amount", object.getAmount()); long insert = dbHelper.getWritableDatabase().replaceOrThrow(TABLE_NAME, null, values); return object.setId(insert); } @Override public List<Reward> findAll() { Cursor cursor = dbHelper.getReadableDatabase().rawQuery("SELECT * FROM " + TABLE_NAME, null); return parseResults(cursor); } @Override public void delete(long id) { String query = String.format(DELETE_TASK_PATTERN, id); dbHelper.getWritableDatabase().execSQL(query); } private List<Reward> parseResults(Cursor response) { List<Reward> items = new ArrayList<>(); int idIndex = response.getColumnIndex("id"); int titleIndex = response.getColumnIndex("title"); int desIndex = response.getColumnIndex("description"); int amountIndex = response.getColumnIndex("amount"); while (response.moveToNext()) { String description = null; if (!response.isNull(desIndex)) { description = response.getString(desIndex); } items.add(new Reward() .setId(response.getLong(idIndex)) .setTitle(response.getString(titleIndex)) .setDescription(description) .setAmount(response.getInt(amountIndex))); } return items; } }
2,937
0.641471
0.640449
79
36.177216
27.688942
101
false
false
0
0
0
0
0
0
0.632911
false
false
2
778dbd6d52532b03df17047a7fa337818dc0bc61
4,690,104,316,513
b0475805679f90784fff777d6558ce1f849b5609
/app/src/main/java/com/naurah/model/Schedule.java
a36a720ff8df1f94fc4d91e254d51132be4b19e3
[]
no_license
faisalarkan21/android-absensi
https://github.com/faisalarkan21/android-absensi
c1ab0e8791b5481cc76182ded2086c9272ac11fa
a946e6b9be95eb22d2ff181c51c9605ea8cfed4f
refs/heads/master
2020-03-25T17:34:25.196000
2018-09-23T11:09:20
2018-09-23T11:09:20
143,984,078
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.naurah.model; public class Schedule { private String title, thumbnailUrl; private String year; private String dosen; private String placeAndTime; private String idMhs; private String idJadwal; private String nip; private String pertemuan; private String pertemuanDosen; private String pertemuanMhs; private String time; private Boolean isVerified; private String idLog; public Schedule() { } public Schedule(String name, String thumbnailUrl, String year, String dosen, String placeAndTime) { this.title = name; this.thumbnailUrl = thumbnailUrl; this.year = year; this.dosen = dosen; this.placeAndTime = placeAndTime; } public String getIdMhs() { return idMhs; } public void setIdMhs(String idMhs) { this.idMhs = idMhs; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getDosen() { return dosen; } public void setDosen(String dosen) { this.dosen = dosen; } public String getPlaceAndTime() { return placeAndTime; } public void setPlaceAndTime(String placeAndTime) { this.placeAndTime = placeAndTime; } public String getNip() { return nip; } public void setNip(String nip) { this.nip = nip; } public String getIdJadwal() { return idJadwal; } public void setIdJadwal(String idJadwal) { this.idJadwal = idJadwal; } public String getPertemuan() { return pertemuan; } public void setPertemuan(String pertemuan) { this.pertemuan = pertemuan; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Boolean getVerified() { return isVerified; } public void setVerified(Boolean verified) { isVerified = verified; } public String getIdLog() { return idLog; } public void setIdLog(String idLog) { this.idLog = idLog; } public String getPertemuanDosen() { return pertemuanDosen; } public void setPertemuanDosen(String pertemuanDosen) { this.pertemuanDosen = pertemuanDosen; } public String getPertemuanMhs() { return pertemuanMhs; } public void setPertemuanMhs(String pertemuanMhs) { this.pertemuanMhs = pertemuanMhs; } }
UTF-8
Java
2,881
java
Schedule.java
Java
[]
null
[]
package com.naurah.model; public class Schedule { private String title, thumbnailUrl; private String year; private String dosen; private String placeAndTime; private String idMhs; private String idJadwal; private String nip; private String pertemuan; private String pertemuanDosen; private String pertemuanMhs; private String time; private Boolean isVerified; private String idLog; public Schedule() { } public Schedule(String name, String thumbnailUrl, String year, String dosen, String placeAndTime) { this.title = name; this.thumbnailUrl = thumbnailUrl; this.year = year; this.dosen = dosen; this.placeAndTime = placeAndTime; } public String getIdMhs() { return idMhs; } public void setIdMhs(String idMhs) { this.idMhs = idMhs; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getDosen() { return dosen; } public void setDosen(String dosen) { this.dosen = dosen; } public String getPlaceAndTime() { return placeAndTime; } public void setPlaceAndTime(String placeAndTime) { this.placeAndTime = placeAndTime; } public String getNip() { return nip; } public void setNip(String nip) { this.nip = nip; } public String getIdJadwal() { return idJadwal; } public void setIdJadwal(String idJadwal) { this.idJadwal = idJadwal; } public String getPertemuan() { return pertemuan; } public void setPertemuan(String pertemuan) { this.pertemuan = pertemuan; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Boolean getVerified() { return isVerified; } public void setVerified(Boolean verified) { isVerified = verified; } public String getIdLog() { return idLog; } public void setIdLog(String idLog) { this.idLog = idLog; } public String getPertemuanDosen() { return pertemuanDosen; } public void setPertemuanDosen(String pertemuanDosen) { this.pertemuanDosen = pertemuanDosen; } public String getPertemuanMhs() { return pertemuanMhs; } public void setPertemuanMhs(String pertemuanMhs) { this.pertemuanMhs = pertemuanMhs; } }
2,881
0.610899
0.610899
144
19.013889
17.03672
80
false
false
0
0
0
0
0
0
0.361111
false
false
2
0083ac56e53a5dc63fcdcf77cff0f43ee4010e5c
21,784,074,173,240
edf6a037939a166a12849ff8e5a18483becbea2b
/src/listeners/WindowListenerSubject.java
c4d898165c162738b2d052d7f131f1e74d645153
[]
no_license
AleksicNikola00/informacioni-sistem-studentske-sluzbe
https://github.com/AleksicNikola00/informacioni-sistem-studentske-sluzbe
47cf73f01960bbd0d13761798c81e39aa630bb17
b3f855588313fda4503ea64906f03be48ce1d293
refs/heads/master
2023-02-19T16:14:31.258000
2021-01-13T19:12:07
2021-01-13T19:12:07
315,057,052
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package listeners; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import view.MainFrame; public class WindowListenerSubject implements WindowListener { @Override public void windowActivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent arg0) { // TODO Auto-generated method stub MainFrame.getInstance().azurirajPrikaz(); } @Override public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub MainFrame.getInstance().azurirajPrikaz(); } @Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub //MainFrame.getInstance().azurirajPrikaz(); } @Override public void windowDeiconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent arg0) { // TODO Auto-generated method stub } }
UTF-8
Java
1,028
java
WindowListenerSubject.java
Java
[]
null
[]
package listeners; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import view.MainFrame; public class WindowListenerSubject implements WindowListener { @Override public void windowActivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent arg0) { // TODO Auto-generated method stub MainFrame.getInstance().azurirajPrikaz(); } @Override public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub MainFrame.getInstance().azurirajPrikaz(); } @Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub //MainFrame.getInstance().azurirajPrikaz(); } @Override public void windowDeiconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent arg0) { // TODO Auto-generated method stub } }
1,028
0.753891
0.747082
55
17.690908
19.661566
62
false
false
0
0
0
0
0
0
0.872727
false
false
2
36f6670679bed4d4a1a34b2208d5fc8ab094cf1b
5,111,011,134,025
7ac8cb711987a1ff234b1ffa907b0642041e6e58
/src/main/java/bgi/ipeak/percolator/MsgfPercolator.java
e2493c2724fdb08838dde5619bd3a9bd63151df5
[ "Apache-2.0" ]
permissive
wenbostar/mzidlib
https://github.com/wenbostar/mzidlib
445843761a223b45780b7c8c345ee3110b6fc76c
41c5d9d028529f7ada5f9417d49491989f9ddba2
refs/heads/master
2021-01-20T22:40:31.325000
2016-03-01T08:23:12
2016-03-01T08:23:12
52,857,446
0
0
null
true
2016-03-01T07:33:04
2016-03-01T07:33:03
2016-02-19T16:27:04
2016-02-09T17:21:32
91,557
0
0
0
null
null
null
package bgi.ipeak.percolator; import java.io.File; import java.io.IOException; import java.util.Set; import java.util.Vector; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import bgi.ipeak.SetDecoyInfo; import bgi.ipeak.percolator.paser.MSGFParser; import bgi.ipeak.util.Properties; public class MsgfPercolator { @Option(name="-f",required=true,usage="(required) The input search result. MS-GF+ in Mzid file") private String searchResult=""; //@Option(name="-pp",required=true,usage="(required) percolator path. ") //private String percolator_path=""; @Option(name="-out_dir",required=true,usage="(required) output directory" ) private String out_dir; @Option(name="-decoyregex",required=false,usage="(optional) Decoy regular expression, default ###\\w+###") private String decoyregex="###\\w+###"; @Option(name="-ms2",required=false,usage="(optional) use the MS/MS features[use[true],not use[false](default)]") private Boolean ms2=false; private Integer searchtype; private String feature_file; private String mzidfile; private File[] result_list; private Vector<String> features_file_list=new Vector<String>(); private Vector<String> mzid_list=new Vector<String>(); private Vector<String> mzid_addScore_list=new Vector<String>(); public static void main(String[] args) throws Exception { MsgfPercolator ip=new MsgfPercolator(); CmdLineParser parser = new CmdLineParser(ip); try { parser.setUsageWidth(100); parser.parseArgument(args); System.err.println("\niPeak v1.0(2013-07)\nWritten by Guilin Li (liguilin@genomics.org.cn) in the\n" + "Proteomics Research Group, Department of Science & Technology, BGI-Shenzhen.\n"); } catch (CmdLineException e) { System.err.println("\niPeakPercolator v1.0(2013-07)\nWritten by Guilin Li (liguilin@genomics.org.cn) in the\n" + "Proteomics Research Group, Department of Science & Technology, BGI-Shenzhen.\n"); System.err.println("\nUSAGE:\n\tjava -Xmx2g -cp IPeak.jar bgi.ipeak.percolator.OmssaPercolator [options...]\n"); parser.printUsage(System.err); System.err.println("\nError:"); System.err.println(e.getMessage()); System.err.println(""); return; } ip.analyse(); } //public MsgfPercolator(String input_file,String output_file,String decoyregex, String percolator_path) { public MsgfPercolator(String input_file,String output_file,String decoyregex) { searchResult=input_file; out_dir=output_file; this.decoyregex=decoyregex; //this.percolator_path=percolator_path; //Properties.Properties_set(this.percolator_path, "mod_path"); } public MsgfPercolator() { } public void analyse() throws Exception { searchtype=check_filePath(); set_decoy_infor(); get_Features(); runPercolator(); add_scores2mzid(); System.out.println("Msgf Percolator Done!"); } private void set_decoy_infor() throws Exception { if(searchtype==0){ File result_file=new File(searchResult); String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); mzidfile=out_dir+name+".mzid"; SetDecoyInfo set_decoy=new SetDecoyInfo(result_file.getAbsolutePath(),mzidfile, decoyregex); set_decoy.SetAndPrint(); } else if(searchtype==1){ for (File result_file : result_list) { String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); String out_file=out_dir+name+".mzid"; SetDecoyInfo set_decoy=new SetDecoyInfo(result_file.getAbsolutePath(),out_file, decoyregex); set_decoy.SetAndPrint(); mzid_list.add(out_file); } } System.out.println("set decoy psm information prosperity\n\n"); } private void get_Features() throws Exception { if(searchtype==0){ File result_file=new File(searchResult); String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); feature_file=out_dir+name+".features"; MSGFParser paser=new MSGFParser(result_file.getAbsolutePath(), feature_file, decoyregex); paser.get_feature_file(); } else if(searchtype==1){ for (File result_file : result_list) { String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); String feature=out_dir+name+".features"; MSGFParser paser=new MSGFParser(result_file.getAbsolutePath(), feature,decoyregex); paser.get_feature_file(); features_file_list.add(feature); } } } private void runPercolator() throws IOException, InterruptedException { if(searchtype==0){ File result_file=new File(searchResult); String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); String tempXML=out_dir+name+".tempXML"; RunPercolator run_percolator=new RunPercolator(feature_file, out_dir+name,tempXML, true); run_percolator.execute(); IPeakPercolator.catTargetAndDecoy(out_dir+name+".target.txt", out_dir+name+".decoy.txt", out_dir+name+".per.txt"); } else if(searchtype==1){ feature_file=out_dir+"combined.features"; IPeakPercolator.combined_features(features_file_list, feature_file); String name="combined"; String tempXML=out_dir+name+".tempXML"; RunPercolator run_percolator=new RunPercolator(feature_file, out_dir+name,tempXML, true); run_percolator.execute(); IPeakPercolator.catTargetAndDecoy(out_dir+name+".target.txt", out_dir+name+".decoy.txt", out_dir+name+".per.txt"); } } private void add_scores2mzid() throws IOException{ if(searchtype==0){ String pertxtfile=feature_file.substring(0,feature_file.lastIndexOf("."))+".per.txt"; PlusPropertiesToMzid pop=new PlusPropertiesToMzid(mzidfile, pertxtfile); pop.export(); } else if(searchtype==1){ String pertxtfile=feature_file.substring(0,feature_file.lastIndexOf("."))+".per.txt"; Set<String> per_name_list=IPeakPercolator.split_percolatorResult(pertxtfile); for (String per_name : per_name_list) { String mzid_name=per_name.substring(0,per_name.indexOf(".per.txt"))+".mzid"; PlusPropertiesToMzid pop=new PlusPropertiesToMzid(mzid_name ,per_name); pop.export(); } } } private int check_filePath() { File out_file=new File(out_dir); if(out_file!= null && !out_file.exists()){ out_file.mkdir(); } out_dir=out_file.getAbsolutePath()+File.separator; File result_file=new File(searchResult); int type=-1; if(result_file.isFile()){ type=0; } else if(result_file.isDirectory()){ result_list=result_file.listFiles(); type=1; } else{ type=2; } return type; } public static void msgf_percolaotr(String input_file,String out_dir,String decoyregex) throws Exception { //MsgfPercolator run_percolator=new MsgfPercolator(input_file,out_dir,decoyregex,percolator_path); MsgfPercolator run_percolator=new MsgfPercolator(input_file,out_dir,decoyregex); run_percolator.analyse(); } }
UTF-8
Java
6,920
java
MsgfPercolator.java
Java
[ { "context": "tem.err.println(\"\\niPeak v1.0(2013-07)\\nWritten by Guilin Li (liguilin@genomics.org.cn) in the\\n\" +\n \t\t", "end": 1626, "score": 0.9998232126235962, "start": 1617, "tag": "NAME", "value": "Guilin Li" }, { "context": "tln(\"\\niPeak v1.0(2013-07)\\nWritten ...
null
[]
package bgi.ipeak.percolator; import java.io.File; import java.io.IOException; import java.util.Set; import java.util.Vector; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import bgi.ipeak.SetDecoyInfo; import bgi.ipeak.percolator.paser.MSGFParser; import bgi.ipeak.util.Properties; public class MsgfPercolator { @Option(name="-f",required=true,usage="(required) The input search result. MS-GF+ in Mzid file") private String searchResult=""; //@Option(name="-pp",required=true,usage="(required) percolator path. ") //private String percolator_path=""; @Option(name="-out_dir",required=true,usage="(required) output directory" ) private String out_dir; @Option(name="-decoyregex",required=false,usage="(optional) Decoy regular expression, default ###\\w+###") private String decoyregex="###\\w+###"; @Option(name="-ms2",required=false,usage="(optional) use the MS/MS features[use[true],not use[false](default)]") private Boolean ms2=false; private Integer searchtype; private String feature_file; private String mzidfile; private File[] result_list; private Vector<String> features_file_list=new Vector<String>(); private Vector<String> mzid_list=new Vector<String>(); private Vector<String> mzid_addScore_list=new Vector<String>(); public static void main(String[] args) throws Exception { MsgfPercolator ip=new MsgfPercolator(); CmdLineParser parser = new CmdLineParser(ip); try { parser.setUsageWidth(100); parser.parseArgument(args); System.err.println("\niPeak v1.0(2013-07)\nWritten by <NAME> (<EMAIL>) in the\n" + "Proteomics Research Group, Department of Science & Technology, BGI-Shenzhen.\n"); } catch (CmdLineException e) { System.err.println("\niPeakPercolator v1.0(2013-07)\nWritten by <NAME> (<EMAIL>) in the\n" + "Proteomics Research Group, Department of Science & Technology, BGI-Shenzhen.\n"); System.err.println("\nUSAGE:\n\tjava -Xmx2g -cp IPeak.jar bgi.ipeak.percolator.OmssaPercolator [options...]\n"); parser.printUsage(System.err); System.err.println("\nError:"); System.err.println(e.getMessage()); System.err.println(""); return; } ip.analyse(); } //public MsgfPercolator(String input_file,String output_file,String decoyregex, String percolator_path) { public MsgfPercolator(String input_file,String output_file,String decoyregex) { searchResult=input_file; out_dir=output_file; this.decoyregex=decoyregex; //this.percolator_path=percolator_path; //Properties.Properties_set(this.percolator_path, "mod_path"); } public MsgfPercolator() { } public void analyse() throws Exception { searchtype=check_filePath(); set_decoy_infor(); get_Features(); runPercolator(); add_scores2mzid(); System.out.println("Msgf Percolator Done!"); } private void set_decoy_infor() throws Exception { if(searchtype==0){ File result_file=new File(searchResult); String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); mzidfile=out_dir+name+".mzid"; SetDecoyInfo set_decoy=new SetDecoyInfo(result_file.getAbsolutePath(),mzidfile, decoyregex); set_decoy.SetAndPrint(); } else if(searchtype==1){ for (File result_file : result_list) { String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); String out_file=out_dir+name+".mzid"; SetDecoyInfo set_decoy=new SetDecoyInfo(result_file.getAbsolutePath(),out_file, decoyregex); set_decoy.SetAndPrint(); mzid_list.add(out_file); } } System.out.println("set decoy psm information prosperity\n\n"); } private void get_Features() throws Exception { if(searchtype==0){ File result_file=new File(searchResult); String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); feature_file=out_dir+name+".features"; MSGFParser paser=new MSGFParser(result_file.getAbsolutePath(), feature_file, decoyregex); paser.get_feature_file(); } else if(searchtype==1){ for (File result_file : result_list) { String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); String feature=out_dir+name+".features"; MSGFParser paser=new MSGFParser(result_file.getAbsolutePath(), feature,decoyregex); paser.get_feature_file(); features_file_list.add(feature); } } } private void runPercolator() throws IOException, InterruptedException { if(searchtype==0){ File result_file=new File(searchResult); String name=result_file.getName().substring(0,result_file.getName().lastIndexOf(".")); String tempXML=out_dir+name+".tempXML"; RunPercolator run_percolator=new RunPercolator(feature_file, out_dir+name,tempXML, true); run_percolator.execute(); IPeakPercolator.catTargetAndDecoy(out_dir+name+".target.txt", out_dir+name+".decoy.txt", out_dir+name+".per.txt"); } else if(searchtype==1){ feature_file=out_dir+"combined.features"; IPeakPercolator.combined_features(features_file_list, feature_file); String name="combined"; String tempXML=out_dir+name+".tempXML"; RunPercolator run_percolator=new RunPercolator(feature_file, out_dir+name,tempXML, true); run_percolator.execute(); IPeakPercolator.catTargetAndDecoy(out_dir+name+".target.txt", out_dir+name+".decoy.txt", out_dir+name+".per.txt"); } } private void add_scores2mzid() throws IOException{ if(searchtype==0){ String pertxtfile=feature_file.substring(0,feature_file.lastIndexOf("."))+".per.txt"; PlusPropertiesToMzid pop=new PlusPropertiesToMzid(mzidfile, pertxtfile); pop.export(); } else if(searchtype==1){ String pertxtfile=feature_file.substring(0,feature_file.lastIndexOf("."))+".per.txt"; Set<String> per_name_list=IPeakPercolator.split_percolatorResult(pertxtfile); for (String per_name : per_name_list) { String mzid_name=per_name.substring(0,per_name.indexOf(".per.txt"))+".mzid"; PlusPropertiesToMzid pop=new PlusPropertiesToMzid(mzid_name ,per_name); pop.export(); } } } private int check_filePath() { File out_file=new File(out_dir); if(out_file!= null && !out_file.exists()){ out_file.mkdir(); } out_dir=out_file.getAbsolutePath()+File.separator; File result_file=new File(searchResult); int type=-1; if(result_file.isFile()){ type=0; } else if(result_file.isDirectory()){ result_list=result_file.listFiles(); type=1; } else{ type=2; } return type; } public static void msgf_percolaotr(String input_file,String out_dir,String decoyregex) throws Exception { //MsgfPercolator run_percolator=new MsgfPercolator(input_file,out_dir,decoyregex,percolator_path); MsgfPercolator run_percolator=new MsgfPercolator(input_file,out_dir,decoyregex); run_percolator.analyse(); } }
6,880
0.716185
0.709393
175
38.542858
32.340282
118
false
false
0
0
0
0
0
0
2.925714
false
false
2
036adb3500719d1e9d15c8a93612a2e0084d2dfd
33,672,543,610,876
5aa9e456791b919be914a695e5a52d4c30ec71de
/fr.obeo.ecore.fxdiag.app/src/fr/obeo/ecore/fxdiag/app/NodeListItem.java
124e904a23ea2b925869a8adf9358a4e97ffe96a
[]
no_license
cbrun/fx-ecore-diagram
https://github.com/cbrun/fx-ecore-diagram
6cfd16f0b4553d37fff01697e137d52b5f497343
63683e1d17c5f6cf32bce5570db8a0e0f421a250
refs/heads/master
2021-01-10T19:41:17.516000
2014-01-24T13:22:07
2014-01-24T13:22:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.obeo.ecore.fxdiag.app; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.CacheHint; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.text.Font; import javafx.scene.text.Text; public class NodeListItem extends HBox { private Text label; private ImageView icon; private DiagNodeBinding binding = new DiagNodeBinding() { @Override public String label() { return "name : EString"; } @Override public Image icon() { return null; } @Override public Object getRepresentedObject() { return DiagNodeBinding.NULL; } }; public NodeListItem() { label = new Text(); icon = new ImageView(); label.setPickOnBounds(true); label.setTextOrigin(VPos.CENTER); label.setFont(Font.font(12)); setAlignment(Pos.BOTTOM_LEFT); getChildren().addAll(icon, label); updateFromModel(); setCache(true); setCacheHint(CacheHint.QUALITY); } private void updateFromModel() { label.setText(binding.label()); icon.setImage(binding.icon()); } public void bind(DiagNodeBinding binding) { this.binding = binding; updateFromModel(); } }
UTF-8
Java
1,182
java
NodeListItem.java
Java
[]
null
[]
package fr.obeo.ecore.fxdiag.app; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.CacheHint; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.text.Font; import javafx.scene.text.Text; public class NodeListItem extends HBox { private Text label; private ImageView icon; private DiagNodeBinding binding = new DiagNodeBinding() { @Override public String label() { return "name : EString"; } @Override public Image icon() { return null; } @Override public Object getRepresentedObject() { return DiagNodeBinding.NULL; } }; public NodeListItem() { label = new Text(); icon = new ImageView(); label.setPickOnBounds(true); label.setTextOrigin(VPos.CENTER); label.setFont(Font.font(12)); setAlignment(Pos.BOTTOM_LEFT); getChildren().addAll(icon, label); updateFromModel(); setCache(true); setCacheHint(CacheHint.QUALITY); } private void updateFromModel() { label.setText(binding.label()); icon.setImage(binding.icon()); } public void bind(DiagNodeBinding binding) { this.binding = binding; updateFromModel(); } }
1,182
0.72758
0.725888
57
19.736841
14.820004
58
false
false
0
0
0
0
0
0
1.666667
false
false
2
ede24235b5cb76a0fd344fcd2aa129aa6814331b
10,033,043,608,673
df12499e271f3ce39ee9ab1d085fcc25543e6ccd
/Chapter_4/SimpleClassesAndObjects/src/by/minsk/epam/jio/taskEight/Main.java
a8f00b6f31f9f9c279b14041465bda7b27c1f616
[]
no_license
D2tun/epam_introduction_to_java
https://github.com/D2tun/epam_introduction_to_java
e1cd7b9c594eaa5c75de206fdbdcfbd8b76197d4
7d30fb80c64ae71887a9dcb145b61a1c2bb5e606
refs/heads/main
2023-07-18T01:30:23.235000
2021-09-06T16:01:08
2021-09-06T16:01:08
383,377,601
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Создать класс Customer, спецификация которого приведена ниже. Определить * конструкторы, set- и get- методы и метод toString(). Создать второй класс, * агрегирующий массив типа Customer, с подходящими конструкторами и методами. * Задать критерии выбора данных и вывести эти данные на консоль. * Класс Customer: id, фамилия, имя, отчество, адрес, номер кредитной * карточки, номер банковского счёта. * Найти и вывести: * a) список покупателей в алфавитном порядке * b) список покупателей, у которых номер кредитной карточки находится в * заданном интервале */ package by.minsk.epam.jio.taskEight; import java.util.Scanner; public class Main { public static void main(String[] args) { CustomerList List = new CustomerList(); Customer customer1 = new Customer(); customer1.setAddress("Россия, г. Москва, ул. Есенина 45/1"); customer1.setBankAccountNumber("20014587479312430003"); customer1.setCreditCardNumber("4587479312430003"); customer1.setId(145); customer1.setName("Григорий"); customer1.setPatronymic("Николаевич"); customer1.setSurname("Жуковский"); List.addCustomer(customer1); Customer customer2 = new Customer(); customer2.setAddress("Беларусь, г. Минск, ул. Тимирязева 12"); customer2.setBankAccountNumber("20014587479312430012"); customer2.setCreditCardNumber("4587479312430012"); customer2.setId(148); customer2.setName("Константин"); customer2.setPatronymic("Васильевич"); customer2.setSurname("Шов"); List.addCustomer(customer2); Customer customer3 = new Customer(); customer3.setAddress("Польша, г. Варшава, площадь Замковая 1/13"); customer3.setBankAccountNumber("20014587479312430011"); customer3.setCreditCardNumber("4587479312430011"); customer3.setId(153); customer3.setName("Ян"); customer3.setPatronymic(""); customer3.setSurname("Ковальский"); List.addCustomer(customer3); Customer customer4 = new Customer(); customer4.setAddress("Литва, г. Вильнюс, Tilto g. 21-9B"); customer4.setBankAccountNumber("20014587479312430045"); customer4.setCreditCardNumber("4587479312430045"); customer4.setId(151); customer4.setName("Неринга"); customer4.setPatronymic(""); customer4.setSurname("Даукантайте"); List.addCustomer(customer4); Customer customer5 = new Customer(); customer5.setAddress("Исландия, г. Рейкьявик, Skipholt 33"); customer5.setBankAccountNumber("20014587479312430000"); customer5.setCreditCardNumber("4587479312430000"); customer5.setId(120); customer5.setName("Эрик"); customer5.setPatronymic("Бьёрнсон"); customer5.setSurname(""); List.addCustomer(customer5); List.outputSortedByName(); Scanner sc = new Scanner(System.in); String a = ""; String b = ""; System.out.println("Введите нижнюю границу номеров карт."); a = sc.nextLine(); System.out.println("Введите верхнюю границу номеров карт."); b = sc.nextLine(); List.outputCreditCardNumbersInRange(a, b); sc.close(); } }
UTF-8
Java
3,722
java
Main.java
Java
[ { "context": "ина 45/1\");\r\n\t\tcustomer1.setBankAccountNumber(\"20014587479312430003\");\r\n\t\tcustomer1.setCreditCardNumbe", "end": 927, "score": 0.5336351990699768, "start": 925, "tag": "KEY", "value": "14" }, { "context": "1\");\r\n\t\tcustomer1.setBankAccountNumber(\"20014587...
null
[]
/* * Создать класс Customer, спецификация которого приведена ниже. Определить * конструкторы, set- и get- методы и метод toString(). Создать второй класс, * агрегирующий массив типа Customer, с подходящими конструкторами и методами. * Задать критерии выбора данных и вывести эти данные на консоль. * Класс Customer: id, фамилия, имя, отчество, адрес, номер кредитной * карточки, номер банковского счёта. * Найти и вывести: * a) список покупателей в алфавитном порядке * b) список покупателей, у которых номер кредитной карточки находится в * заданном интервале */ package by.minsk.epam.jio.taskEight; import java.util.Scanner; public class Main { public static void main(String[] args) { CustomerList List = new CustomerList(); Customer customer1 = new Customer(); customer1.setAddress("Россия, г. Москва, ул. Есенина 45/1"); customer1.setBankAccountNumber("20014587479312430003"); customer1.setCreditCardNumber("4587479312430003"); customer1.setId(145); customer1.setName("Григорий"); customer1.setPatronymic("Николаевич"); customer1.setSurname("Жуковский"); List.addCustomer(customer1); Customer customer2 = new Customer(); customer2.setAddress("Беларусь, г. Минск, ул. Тимирязева 12"); customer2.setBankAccountNumber("20014587479312430012"); customer2.setCreditCardNumber("4587479312430012"); customer2.setId(148); customer2.setName("Константин"); customer2.setPatronymic("Васильевич"); customer2.setSurname("Шов"); List.addCustomer(customer2); Customer customer3 = new Customer(); customer3.setAddress("Польша, г. Варшава, площадь Замковая 1/13"); customer3.setBankAccountNumber("20014587479312430011"); customer3.setCreditCardNumber("4587479312430011"); customer3.setId(153); customer3.setName("Ян"); customer3.setPatronymic(""); customer3.setSurname("Ковальский"); List.addCustomer(customer3); Customer customer4 = new Customer(); customer4.setAddress("Литва, г. Вильнюс, Tilto g. 21-9B"); customer4.setBankAccountNumber("20014587479312430045"); customer4.setCreditCardNumber("4587479312430045"); customer4.setId(151); customer4.setName("Неринга"); customer4.setPatronymic(""); customer4.setSurname("Даукантайте"); List.addCustomer(customer4); Customer customer5 = new Customer(); customer5.setAddress("Исландия, г. Рейкьявик, Skipholt 33"); customer5.setBankAccountNumber("20014587479312430000"); customer5.setCreditCardNumber("4587479312430000"); customer5.setId(120); customer5.setName("Эрик"); customer5.setPatronymic("Бьёрнсон"); customer5.setSurname(""); List.addCustomer(customer5); List.outputSortedByName(); Scanner sc = new Scanner(System.in); String a = ""; String b = ""; System.out.println("Введите нижнюю границу номеров карт."); a = sc.nextLine(); System.out.println("Введите верхнюю границу номеров карт."); b = sc.nextLine(); List.outputCreditCardNumbersInRange(a, b); sc.close(); } }
3,722
0.722458
0.639752
88
32.761364
21.947765
79
false
false
0
0
0
0
0
0
2.477273
false
false
2
b83ba5f13534f12e3ae49b5871b647e6069aec3b
23,639,500,010,665
6212c5eceda685951ff2748df5e2b2f83ea52223
/nan/nan-model/src/main/java/com/web2h/nan/model/exception/parameter/InvalidParameterException.java
723244362130936d452949fe0f6a5648a4dd94d9
[]
no_license
web2h/need-a-nounou
https://github.com/web2h/need-a-nounou
3a456047928fca56e0aaa6fe1f8af2853520fc74
0b00edf1693e8fc48fa4b165852d4b3ed5a63540
refs/heads/master
2021-01-21T13:03:11.250000
2016-04-15T20:21:26
2016-04-15T20:21:26
54,022,056
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.web2h.nan.model.exception.parameter; /** * Invalid parameter exception. Occurs when a parameter does not match the required format. * * @author web2h */ @SuppressWarnings("serial") public class InvalidParameterException extends ParameterException { private static final String MESSAGE = "The {0} parameter is invalid"; public InvalidParameterException() { super(); } public InvalidParameterException(String invalidParameter) { super(MESSAGE.replace("{0}", invalidParameter)); } }
UTF-8
Java
530
java
InvalidParameterException.java
Java
[ { "context": "es not match the required format.\r\n * \r\n * @author web2h\r\n */\r\n@SuppressWarnings(\"serial\")\r\npublic class I", "end": 171, "score": 0.9994894862174988, "start": 166, "tag": "USERNAME", "value": "web2h" } ]
null
[]
package com.web2h.nan.model.exception.parameter; /** * Invalid parameter exception. Occurs when a parameter does not match the required format. * * @author web2h */ @SuppressWarnings("serial") public class InvalidParameterException extends ParameterException { private static final String MESSAGE = "The {0} parameter is invalid"; public InvalidParameterException() { super(); } public InvalidParameterException(String invalidParameter) { super(MESSAGE.replace("{0}", invalidParameter)); } }
530
0.730189
0.722642
20
24.6
28.690416
91
false
false
0
0
0
0
0
0
0.8
false
false
2
681c8f39ebb08cb92e8cc17ba45b04e0e7bd2966
2,791,728,767,807
d9ba1c926eb45fadf03ad4cbea475b47c3f0609b
/src/interfaceConcept/IbnSina.java
4d83e9fb13f0705832247d63f90cf6bc03d307b3
[]
no_license
MohammedTarafdar/BasicJava2020
https://github.com/MohammedTarafdar/BasicJava2020
c30c343d60b8acd2286e6e780546b5e0b782bc5b
adec22c3c6b6bb82a62c74efe7626cf87ef14ee9
refs/heads/master
2023-01-15T18:55:20.463000
2020-11-20T04:26:23
2020-11-20T04:26:23
258,062,362
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package interfaceConcept; public class IbnSina extends GlobalPatientData implements USMedical, UKMedical, IndianMedical { @Override public void physioServices() { System.out.println("IbnSina physio services"); } @Override public void oncologyServices() { System.out.println("IbnSina oncology services"); } @Override public void orthopedicServices() { System.out.println("IbnSina orthopedic services"); } @Override public void entServices() { System.out.println("IbnSina ENT services"); } @Override public void ambulanceServices() { System.out.println("IbnSina ambulance services"); } @Override public void emergencyServices() { System.out.println("IbnSina emergency services"); } @Override public void neuroServices() { System.out.println("IbnSina neuro services"); } @Override public void pediatricServices() { System.out.println("IbnSina pediatric services"); } // WHO @Override public void polioServices() { System.out.println("Polio is a worldwide problem"); } // non overridden methods public void OPTServices() { System.out.println("IbnSina OPT services"); } public void medicalInsurance() { System.out.println("IbnSina medical insurance services"); } public void pathalogyServices() { System.out.println("IbnSina pathalogy services"); } }
UTF-8
Java
1,366
java
IbnSina.java
Java
[]
null
[]
package interfaceConcept; public class IbnSina extends GlobalPatientData implements USMedical, UKMedical, IndianMedical { @Override public void physioServices() { System.out.println("IbnSina physio services"); } @Override public void oncologyServices() { System.out.println("IbnSina oncology services"); } @Override public void orthopedicServices() { System.out.println("IbnSina orthopedic services"); } @Override public void entServices() { System.out.println("IbnSina ENT services"); } @Override public void ambulanceServices() { System.out.println("IbnSina ambulance services"); } @Override public void emergencyServices() { System.out.println("IbnSina emergency services"); } @Override public void neuroServices() { System.out.println("IbnSina neuro services"); } @Override public void pediatricServices() { System.out.println("IbnSina pediatric services"); } // WHO @Override public void polioServices() { System.out.println("Polio is a worldwide problem"); } // non overridden methods public void OPTServices() { System.out.println("IbnSina OPT services"); } public void medicalInsurance() { System.out.println("IbnSina medical insurance services"); } public void pathalogyServices() { System.out.println("IbnSina pathalogy services"); } }
1,366
0.70937
0.70937
81
15.864198
20.48592
96
false
false
0
0
0
0
0
0
1.271605
false
false
2
685429f6530a95efd726389143e265a9f437d3f4
22,625,887,732,056
b27c117017d4351dd992b345fb5fa374bafbf17b
/capgemini/oops/Student_Test.java
7095106e290c205aee34157f358713714a2a0ff2
[]
no_license
pavan241197/pavan
https://github.com/pavan241197/pavan
7da60ce5bafd501aa2690d3fb2440bde7c70ff2f
a2d9d798611a9943650f27d06b31fc88621c6616
refs/heads/master
2020-06-30T11:47:19.818000
2019-08-17T12:57:59
2019-08-17T12:57:59
200,817,149
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package capgemini.oops; // fields class Student { int rollno; String name; float marks; final float OUT_OF_MARKS = 300; // constructors public Student() { rollno = 0; name = null; marks = 0.0f; System.out.println("default"); } public Student(int i, String sname, float f) { this.rollno = i; this.name = sname; this.marks = f; } public void display() { System.out.println("rollno:" + rollno); System.out.println("name:" + name); System.out.println("marks:" + marks); } public String calgrade() { double percentage = calacPer(); if (percentage > 85.0f && percentage <= 100.0f) { return "GradeA"; } else if (percentage > 75.0f && percentage <= 85.0f) { return "GradeB"; } else if (percentage > 650.f && percentage <= 65.0f) { return "GradeC"; } else { return "fail"; } } double calacPer() { double percentage = (marks / 300) * 100; return percentage; } @Override public String toString() { return "marks:" + marks + "name:" + name + "+rollno:" + rollno; } @Override public boolean equals(Object obj) { Student f = (Student) obj; if (this.OUT_OF_MARKS == f.marks) { return true; } else return false; } } public class Student_Test { public static void main(String[] args) { Student s1 = new Student(1, "pavan", 267.9f); Student s2 = new Student(2, "suresh", 256.0f); double percentage = s1.calacPer(); System.out.println("percentage:" + percentage); double percentage1 = s2.calacPer(); System.out.println("percentage:" + percentage1); System.out.println(s1.toString()); System.out.println(s2.toString()); System.out.println(s1.equals(s2)); } }
UTF-8
Java
1,730
java
Student_Test.java
Java
[ { "context": "(String[] args) {\r\n\t\tStudent s1 = new Student(1, \"pavan\", 267.9f);\r\n\t\tStudent s2 = new Student(2, \"suresh", "end": 1366, "score": 0.9996402263641357, "start": 1361, "tag": "NAME", "value": "pavan" }, { "context": "\"pavan\", 267.9f);\r\n\t\tStudent s2 = new S...
null
[]
package capgemini.oops; // fields class Student { int rollno; String name; float marks; final float OUT_OF_MARKS = 300; // constructors public Student() { rollno = 0; name = null; marks = 0.0f; System.out.println("default"); } public Student(int i, String sname, float f) { this.rollno = i; this.name = sname; this.marks = f; } public void display() { System.out.println("rollno:" + rollno); System.out.println("name:" + name); System.out.println("marks:" + marks); } public String calgrade() { double percentage = calacPer(); if (percentage > 85.0f && percentage <= 100.0f) { return "GradeA"; } else if (percentage > 75.0f && percentage <= 85.0f) { return "GradeB"; } else if (percentage > 650.f && percentage <= 65.0f) { return "GradeC"; } else { return "fail"; } } double calacPer() { double percentage = (marks / 300) * 100; return percentage; } @Override public String toString() { return "marks:" + marks + "name:" + name + "+rollno:" + rollno; } @Override public boolean equals(Object obj) { Student f = (Student) obj; if (this.OUT_OF_MARKS == f.marks) { return true; } else return false; } } public class Student_Test { public static void main(String[] args) { Student s1 = new Student(1, "pavan", 267.9f); Student s2 = new Student(2, "suresh", 256.0f); double percentage = s1.calacPer(); System.out.println("percentage:" + percentage); double percentage1 = s2.calacPer(); System.out.println("percentage:" + percentage1); System.out.println(s1.toString()); System.out.println(s2.toString()); System.out.println(s1.equals(s2)); } }
1,730
0.610405
0.580925
77
20.467533
17.359892
65
false
false
0
0
0
0
0
0
1.87013
false
false
2
d80f1abf2b9690c2541c382bb71bb0990f5b5dca
13,408,887,916,123
1252ea2bbc264be8c24db56df0c0c3b53709773a
/src/test/java/ru/mezgin/tracker/util/CalculationTimeWorkedTest.java
3ce65f42b750b0a8008d7533de093ae113a0e97c
[]
no_license
amezgin/timetracker
https://github.com/amezgin/timetracker
fc13fed7e372748e7e49a6889b77f11cdc5bc1fa
cb505d52ded394dd4b5ac664d1940c6240094521
refs/heads/master
2020-03-11T00:00:19.334000
2018-04-15T21:27:06
2018-04-15T21:27:06
129,653,025
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.mezgin.tracker.util; import org.junit.Test; import ru.mezgin.tracker.model.Status; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * The class CalculationTimeWorkedTest. * * @author Alexander Mezgin * @version 1.0 * @since 15.04.2018 */ public class CalculationTimeWorkedTest { /** * Test method calculate when list is not empty. */ @Test public void whenGetListStatusThenReturnTimeWorked() { Status startDay = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 10, 00, 00), true, false); Status out = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 10, 30, 30), true, false); Status come = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 11, 00, 00), true, false); Status worked = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 12, 00, 15), true, false); List<Status> list = new ArrayList<>(); list.add(worked); list.add(come); list.add(out); list.add(startDay); String result = CalculationTimeWorked.calculate(list); assertThat(result, is("01:30:45")); } /** * Test method calculate when list is == null. */ @Test public void whenGetListEqualsNullThenReturnEmptyString() { List<Status> list = null; String result = CalculationTimeWorked.calculate(list); assertThat(result, is("")); } }
UTF-8
Java
1,624
java
CalculationTimeWorkedTest.java
Java
[ { "context": "The class CalculationTimeWorkedTest.\n *\n * @author Alexander Mezgin\n * @version 1.0\n * @since 15.04.2018\n */\npublic c", "end": 337, "score": 0.9998779296875, "start": 321, "tag": "NAME", "value": "Alexander Mezgin" } ]
null
[]
package ru.mezgin.tracker.util; import org.junit.Test; import ru.mezgin.tracker.model.Status; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * The class CalculationTimeWorkedTest. * * @author <NAME> * @version 1.0 * @since 15.04.2018 */ public class CalculationTimeWorkedTest { /** * Test method calculate when list is not empty. */ @Test public void whenGetListStatusThenReturnTimeWorked() { Status startDay = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 10, 00, 00), true, false); Status out = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 10, 30, 30), true, false); Status come = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 11, 00, 00), true, false); Status worked = new Status(null, "Пришёл", LocalDateTime.of(2018, 04, 01, 12, 00, 15), true, false); List<Status> list = new ArrayList<>(); list.add(worked); list.add(come); list.add(out); list.add(startDay); String result = CalculationTimeWorked.calculate(list); assertThat(result, is("01:30:45")); } /** * Test method calculate when list is == null. */ @Test public void whenGetListEqualsNullThenReturnEmptyString() { List<Status> list = null; String result = CalculationTimeWorked.calculate(list); assertThat(result, is("")); } }
1,614
0.625
0.58
56
27.589285
25.823423
96
false
false
0
0
0
0
0
0
1.071429
false
false
2
bcd348ea9e56803090d7e2943f9a8fae5fa852c6
8,100,308,366,883
4e22bda99c2e74f86f417d440b142515b84e67dd
/src/test/java/org/ai/AlphabetaSearchTest.java
652fb4c11f1ba1ba4c78211622ea496fcec3e2c1
[]
no_license
nothize/suite
https://github.com/nothize/suite
ea5fe41af2457622a6aabd27dfec5ade5d4fcb0e
83753871add18b577d3d3b967b9646c7604bcb81
refs/heads/master
2021-01-16T23:02:05.972000
2012-04-01T15:11:56
2012-04-01T15:11:56
2,393,585
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ai; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.ai.AlphabetaSearch.Game; import org.junit.Test; public class AlphabetaSearchTest { private static class TicTacToe { char player = 'O'; char grid[] = new char[9]; public String toString() { return "\n" + c(grid[0]) + "|" + c(grid[1]) + "|" + c(grid[2]) // + "\n" + c(grid[3]) + "|" + c(grid[4]) + "|" + c(grid[5]) // + "\n" + c(grid[6]) + "|" + c(grid[7]) + "|" + c(grid[8]) // + "\n"; } private char c(char v) { return v != 0 ? v : ' '; } } private static Game<TicTacToe> ticTacToeGame = new Game<TicTacToe>() { private final int lines[][] = new int[][] { // { 0, 1, 2 }, // { 3, 4, 5 }, // { 6, 7, 8 }, // { 0, 3, 6 }, // { 1, 4, 7 }, // { 2, 5, 8 }, // { 0, 4, 8 }, // { 2, 4, 6 }, }; private final int scores[] = new int[] { 0, 1, 10, 10000 }; public List<TicTacToe> generate(TicTacToe state) { List<TicTacToe> states = new ArrayList<TicTacToe>(); if (!isEnd(state)) for (int i = 0; i < 9; i++) if (state.grid[i] == 0) { TicTacToe state1 = new TicTacToe(); state1.player = (char) ('O' + 'X' - state.player); state1.grid = Arrays.copyOf(state.grid, 9); state1.grid[i] = state.player; states.add(state1); } return states; } public boolean isEnd(TicTacToe state) { for (int line[] : lines) { char c0 = state.grid[line[0]]; char c1 = state.grid[line[1]]; char c2 = state.grid[line[2]]; if (c0 != 0 && c0 == c1 && c1 == c2) return true; } return false; } public int evaluate(TicTacToe state) { int score = 0; for (int line[] : lines) score += evaluateLine(state, line); return score; } private int evaluateLine(TicTacToe state, int line[]) { int no = 0, nx = 0; for (int c = 0; c < 3; c++) if (state.grid[line[c]] == 'O') no++; else if (state.grid[line[c]] == 'X') nx++; int o = (no == 0 || nx == 0) ? scores[no] - scores[nx] : 0; return state.player == 'O' ? o : -o; } }; @Test public void test() { AlphabetaSearch<TicTacToe> search = new AlphabetaSearch<TicTacToe>( ticTacToeGame); TicTacToe state = new TicTacToe(); System.out.println(search.search(state, 20)); } }
UTF-8
Java
2,317
java
AlphabetaSearchTest.java
Java
[]
null
[]
package org.ai; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.ai.AlphabetaSearch.Game; import org.junit.Test; public class AlphabetaSearchTest { private static class TicTacToe { char player = 'O'; char grid[] = new char[9]; public String toString() { return "\n" + c(grid[0]) + "|" + c(grid[1]) + "|" + c(grid[2]) // + "\n" + c(grid[3]) + "|" + c(grid[4]) + "|" + c(grid[5]) // + "\n" + c(grid[6]) + "|" + c(grid[7]) + "|" + c(grid[8]) // + "\n"; } private char c(char v) { return v != 0 ? v : ' '; } } private static Game<TicTacToe> ticTacToeGame = new Game<TicTacToe>() { private final int lines[][] = new int[][] { // { 0, 1, 2 }, // { 3, 4, 5 }, // { 6, 7, 8 }, // { 0, 3, 6 }, // { 1, 4, 7 }, // { 2, 5, 8 }, // { 0, 4, 8 }, // { 2, 4, 6 }, }; private final int scores[] = new int[] { 0, 1, 10, 10000 }; public List<TicTacToe> generate(TicTacToe state) { List<TicTacToe> states = new ArrayList<TicTacToe>(); if (!isEnd(state)) for (int i = 0; i < 9; i++) if (state.grid[i] == 0) { TicTacToe state1 = new TicTacToe(); state1.player = (char) ('O' + 'X' - state.player); state1.grid = Arrays.copyOf(state.grid, 9); state1.grid[i] = state.player; states.add(state1); } return states; } public boolean isEnd(TicTacToe state) { for (int line[] : lines) { char c0 = state.grid[line[0]]; char c1 = state.grid[line[1]]; char c2 = state.grid[line[2]]; if (c0 != 0 && c0 == c1 && c1 == c2) return true; } return false; } public int evaluate(TicTacToe state) { int score = 0; for (int line[] : lines) score += evaluateLine(state, line); return score; } private int evaluateLine(TicTacToe state, int line[]) { int no = 0, nx = 0; for (int c = 0; c < 3; c++) if (state.grid[line[c]] == 'O') no++; else if (state.grid[line[c]] == 'X') nx++; int o = (no == 0 || nx == 0) ? scores[no] - scores[nx] : 0; return state.player == 'O' ? o : -o; } }; @Test public void test() { AlphabetaSearch<TicTacToe> search = new AlphabetaSearch<TicTacToe>( ticTacToeGame); TicTacToe state = new TicTacToe(); System.out.println(search.search(state, 20)); } }
2,317
0.536901
0.504532
100
22.17
19.882181
71
false
false
0
0
0
0
0
0
3.06
false
false
2
3e651603898d52f3abbd3b24d072524c2433470f
8,100,308,364,569
1ef497fef3ca2bd5981ff2a6d3b5df32a845ce85
/jadx-decompile/org/codehaus/jackson/map/util/StdDateFormat.java
7821c62853ea3394c0f349253736e7e307d913a3
[]
no_license
gmtandi/droneapp
https://github.com/gmtandi/droneapp
624eeb8a77bbb6cbe3160d79d0c9b46e827e8f4f
bfacef0ef2cc43aded3e03c012debcee868706c5
refs/heads/master
2019-07-22T10:11:35.423000
2017-06-01T00:38:41
2017-06-01T00:38:41
92,822,587
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.codehaus.jackson.map.util; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.codehaus.jackson.io.NumberInput; import org.codehaus.jackson.org.objectweb.asm.signature.SignatureVisitor; public class StdDateFormat extends DateFormat { static final String[] ALL_FORMATS = new String[]{DATE_FORMAT_STR_ISO8601, DATE_FORMAT_STR_ISO8601_Z, "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"}; static final SimpleDateFormat DATE_FORMAT_ISO8601 = new SimpleDateFormat(DATE_FORMAT_STR_ISO8601); static final SimpleDateFormat DATE_FORMAT_ISO8601_Z = new SimpleDateFormat(DATE_FORMAT_STR_ISO8601_Z); static final SimpleDateFormat DATE_FORMAT_PLAIN = new SimpleDateFormat("yyyy-MM-dd"); static final SimpleDateFormat DATE_FORMAT_RFC1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); static final String DATE_FORMAT_STR_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; static final String DATE_FORMAT_STR_ISO8601_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; static final String DATE_FORMAT_STR_PLAIN = "yyyy-MM-dd"; static final String DATE_FORMAT_STR_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; public static final StdDateFormat instance = new StdDateFormat(); transient SimpleDateFormat _formatISO8601; transient SimpleDateFormat _formatISO8601_z; transient SimpleDateFormat _formatPlain; transient SimpleDateFormat _formatRFC1123; static { TimeZone timeZone = TimeZone.getTimeZone("GMT"); DATE_FORMAT_RFC1123.setTimeZone(timeZone); DATE_FORMAT_ISO8601.setTimeZone(timeZone); DATE_FORMAT_ISO8601_Z.setTimeZone(timeZone); DATE_FORMAT_PLAIN.setTimeZone(timeZone); } public static DateFormat getBlueprintISO8601Format() { return DATE_FORMAT_ISO8601; } public static DateFormat getBlueprintRFC1123Format() { return DATE_FORMAT_RFC1123; } public static DateFormat getISO8601Format(TimeZone timeZone) { SimpleDateFormat simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601.clone(); simpleDateFormat.setTimeZone(timeZone); return simpleDateFormat; } public static DateFormat getRFC1123Format(TimeZone timeZone) { SimpleDateFormat simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_RFC1123.clone(); simpleDateFormat.setTimeZone(timeZone); return simpleDateFormat; } private static final boolean hasTimeZone(String str) { int length = str.length(); if (length >= 6) { char charAt = str.charAt(length - 6); if (charAt == SignatureVisitor.EXTENDS || charAt == SignatureVisitor.SUPER) { return true; } charAt = str.charAt(length - 5); if (charAt == SignatureVisitor.EXTENDS || charAt == SignatureVisitor.SUPER) { return true; } char charAt2 = str.charAt(length - 3); if (charAt2 == SignatureVisitor.EXTENDS || charAt2 == SignatureVisitor.SUPER) { return true; } } return false; } public StdDateFormat clone() { return new StdDateFormat(); } public StringBuffer format(Date date, StringBuffer stringBuffer, FieldPosition fieldPosition) { if (this._formatISO8601 == null) { this._formatISO8601 = (SimpleDateFormat) DATE_FORMAT_ISO8601.clone(); } return this._formatISO8601.format(date, stringBuffer, fieldPosition); } protected boolean looksLikeISO8601(String str) { return str.length() >= 5 && Character.isDigit(str.charAt(0)) && Character.isDigit(str.charAt(3)) && str.charAt(4) == SignatureVisitor.SUPER; } public Date parse(String str) { String trim = str.trim(); ParsePosition parsePosition = new ParsePosition(0); Date parse = parse(trim, parsePosition); if (parse != null) { return parse; } StringBuilder stringBuilder = new StringBuilder(); for (String str2 : ALL_FORMATS) { if (stringBuilder.length() > 0) { stringBuilder.append("\", \""); } else { stringBuilder.append(l.e); } stringBuilder.append(str2); } stringBuilder.append(l.e); throw new ParseException(String.format("Can not parse date \"%s\": not compatible with any of standard forms (%s)", new Object[]{trim, stringBuilder.toString()}), parsePosition.getErrorIndex()); } public Date parse(String str, ParsePosition parsePosition) { if (looksLikeISO8601(str)) { return parseAsISO8601(str, parsePosition); } int length = str.length(); char charAt; do { length--; if (length < 0) { break; } charAt = str.charAt(length); if (charAt < '0') { break; } } while (charAt <= '9'); return (length >= 0 || !NumberInput.inLongRange(str, false)) ? parseAsRFC1123(str, parsePosition) : new Date(Long.parseLong(str)); } protected Date parseAsISO8601(String str, ParsePosition parsePosition) { SimpleDateFormat simpleDateFormat; int length = str.length(); char charAt = str.charAt(length - 1); if (length <= 10 && Character.isDigit(charAt)) { simpleDateFormat = this._formatPlain; if (simpleDateFormat == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_PLAIN.clone(); this._formatPlain = simpleDateFormat; } } else if (charAt == 'Z') { simpleDateFormat = this._formatISO8601_z; if (simpleDateFormat == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601_Z.clone(); this._formatISO8601_z = simpleDateFormat; } if (str.charAt(length - 4) == ':') { StringBuilder stringBuilder = new StringBuilder(str); stringBuilder.insert(length - 1, ".000"); str = stringBuilder.toString(); } } else if (hasTimeZone(str)) { charAt = str.charAt(length - 3); if (charAt == ':') { r0 = new StringBuilder(str); r0.delete(length - 3, length - 2); str = r0.toString(); } else if (charAt == SignatureVisitor.EXTENDS || charAt == SignatureVisitor.SUPER) { str = str + "00"; } int length2 = str.length(); if (Character.isDigit(str.charAt(length2 - 9))) { StringBuilder stringBuilder2 = new StringBuilder(str); stringBuilder2.insert(length2 - 5, ".000"); str = stringBuilder2.toString(); } simpleDateFormat = this._formatISO8601; if (this._formatISO8601 == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601.clone(); this._formatISO8601 = simpleDateFormat; } } else { r0 = new StringBuilder(str); if ((length - str.lastIndexOf(84)) - 1 <= 8) { r0.append(".000"); } r0.append('Z'); str = r0.toString(); simpleDateFormat = this._formatISO8601_z; if (simpleDateFormat == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601_Z.clone(); this._formatISO8601_z = simpleDateFormat; } } return simpleDateFormat.parse(str, parsePosition); } protected Date parseAsRFC1123(String str, ParsePosition parsePosition) { if (this._formatRFC1123 == null) { this._formatRFC1123 = (SimpleDateFormat) DATE_FORMAT_RFC1123.clone(); } return this._formatRFC1123.parse(str, parsePosition); } }
UTF-8
Java
8,083
java
StdDateFormat.java
Java
[]
null
[]
package org.codehaus.jackson.map.util; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.codehaus.jackson.io.NumberInput; import org.codehaus.jackson.org.objectweb.asm.signature.SignatureVisitor; public class StdDateFormat extends DateFormat { static final String[] ALL_FORMATS = new String[]{DATE_FORMAT_STR_ISO8601, DATE_FORMAT_STR_ISO8601_Z, "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"}; static final SimpleDateFormat DATE_FORMAT_ISO8601 = new SimpleDateFormat(DATE_FORMAT_STR_ISO8601); static final SimpleDateFormat DATE_FORMAT_ISO8601_Z = new SimpleDateFormat(DATE_FORMAT_STR_ISO8601_Z); static final SimpleDateFormat DATE_FORMAT_PLAIN = new SimpleDateFormat("yyyy-MM-dd"); static final SimpleDateFormat DATE_FORMAT_RFC1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); static final String DATE_FORMAT_STR_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; static final String DATE_FORMAT_STR_ISO8601_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; static final String DATE_FORMAT_STR_PLAIN = "yyyy-MM-dd"; static final String DATE_FORMAT_STR_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; public static final StdDateFormat instance = new StdDateFormat(); transient SimpleDateFormat _formatISO8601; transient SimpleDateFormat _formatISO8601_z; transient SimpleDateFormat _formatPlain; transient SimpleDateFormat _formatRFC1123; static { TimeZone timeZone = TimeZone.getTimeZone("GMT"); DATE_FORMAT_RFC1123.setTimeZone(timeZone); DATE_FORMAT_ISO8601.setTimeZone(timeZone); DATE_FORMAT_ISO8601_Z.setTimeZone(timeZone); DATE_FORMAT_PLAIN.setTimeZone(timeZone); } public static DateFormat getBlueprintISO8601Format() { return DATE_FORMAT_ISO8601; } public static DateFormat getBlueprintRFC1123Format() { return DATE_FORMAT_RFC1123; } public static DateFormat getISO8601Format(TimeZone timeZone) { SimpleDateFormat simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601.clone(); simpleDateFormat.setTimeZone(timeZone); return simpleDateFormat; } public static DateFormat getRFC1123Format(TimeZone timeZone) { SimpleDateFormat simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_RFC1123.clone(); simpleDateFormat.setTimeZone(timeZone); return simpleDateFormat; } private static final boolean hasTimeZone(String str) { int length = str.length(); if (length >= 6) { char charAt = str.charAt(length - 6); if (charAt == SignatureVisitor.EXTENDS || charAt == SignatureVisitor.SUPER) { return true; } charAt = str.charAt(length - 5); if (charAt == SignatureVisitor.EXTENDS || charAt == SignatureVisitor.SUPER) { return true; } char charAt2 = str.charAt(length - 3); if (charAt2 == SignatureVisitor.EXTENDS || charAt2 == SignatureVisitor.SUPER) { return true; } } return false; } public StdDateFormat clone() { return new StdDateFormat(); } public StringBuffer format(Date date, StringBuffer stringBuffer, FieldPosition fieldPosition) { if (this._formatISO8601 == null) { this._formatISO8601 = (SimpleDateFormat) DATE_FORMAT_ISO8601.clone(); } return this._formatISO8601.format(date, stringBuffer, fieldPosition); } protected boolean looksLikeISO8601(String str) { return str.length() >= 5 && Character.isDigit(str.charAt(0)) && Character.isDigit(str.charAt(3)) && str.charAt(4) == SignatureVisitor.SUPER; } public Date parse(String str) { String trim = str.trim(); ParsePosition parsePosition = new ParsePosition(0); Date parse = parse(trim, parsePosition); if (parse != null) { return parse; } StringBuilder stringBuilder = new StringBuilder(); for (String str2 : ALL_FORMATS) { if (stringBuilder.length() > 0) { stringBuilder.append("\", \""); } else { stringBuilder.append(l.e); } stringBuilder.append(str2); } stringBuilder.append(l.e); throw new ParseException(String.format("Can not parse date \"%s\": not compatible with any of standard forms (%s)", new Object[]{trim, stringBuilder.toString()}), parsePosition.getErrorIndex()); } public Date parse(String str, ParsePosition parsePosition) { if (looksLikeISO8601(str)) { return parseAsISO8601(str, parsePosition); } int length = str.length(); char charAt; do { length--; if (length < 0) { break; } charAt = str.charAt(length); if (charAt < '0') { break; } } while (charAt <= '9'); return (length >= 0 || !NumberInput.inLongRange(str, false)) ? parseAsRFC1123(str, parsePosition) : new Date(Long.parseLong(str)); } protected Date parseAsISO8601(String str, ParsePosition parsePosition) { SimpleDateFormat simpleDateFormat; int length = str.length(); char charAt = str.charAt(length - 1); if (length <= 10 && Character.isDigit(charAt)) { simpleDateFormat = this._formatPlain; if (simpleDateFormat == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_PLAIN.clone(); this._formatPlain = simpleDateFormat; } } else if (charAt == 'Z') { simpleDateFormat = this._formatISO8601_z; if (simpleDateFormat == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601_Z.clone(); this._formatISO8601_z = simpleDateFormat; } if (str.charAt(length - 4) == ':') { StringBuilder stringBuilder = new StringBuilder(str); stringBuilder.insert(length - 1, ".000"); str = stringBuilder.toString(); } } else if (hasTimeZone(str)) { charAt = str.charAt(length - 3); if (charAt == ':') { r0 = new StringBuilder(str); r0.delete(length - 3, length - 2); str = r0.toString(); } else if (charAt == SignatureVisitor.EXTENDS || charAt == SignatureVisitor.SUPER) { str = str + "00"; } int length2 = str.length(); if (Character.isDigit(str.charAt(length2 - 9))) { StringBuilder stringBuilder2 = new StringBuilder(str); stringBuilder2.insert(length2 - 5, ".000"); str = stringBuilder2.toString(); } simpleDateFormat = this._formatISO8601; if (this._formatISO8601 == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601.clone(); this._formatISO8601 = simpleDateFormat; } } else { r0 = new StringBuilder(str); if ((length - str.lastIndexOf(84)) - 1 <= 8) { r0.append(".000"); } r0.append('Z'); str = r0.toString(); simpleDateFormat = this._formatISO8601_z; if (simpleDateFormat == null) { simpleDateFormat = (SimpleDateFormat) DATE_FORMAT_ISO8601_Z.clone(); this._formatISO8601_z = simpleDateFormat; } } return simpleDateFormat.parse(str, parsePosition); } protected Date parseAsRFC1123(String str, ParsePosition parsePosition) { if (this._formatRFC1123 == null) { this._formatRFC1123 = (SimpleDateFormat) DATE_FORMAT_RFC1123.clone(); } return this._formatRFC1123.parse(str, parsePosition); } }
8,083
0.608932
0.578127
193
40.880829
31.689577
202
false
false
0
0
0
0
0
0
0.715026
false
false
2
bac1a41b938192a2b833b5e8a4d73611aeae737b
13,537,736,934,570
b8275941677400bfcd2311947f8322d69706c119
/src/main/java/st/extreme/klingklong/demo/JVM1.java
256fcdbd35de615e302ef9970bf235ac365a9343
[ "Apache-2.0" ]
permissive
ohumbel/klingklong
https://github.com/ohumbel/klingklong
257cc3ce327f7a294ff154d7ba2b511a679147b4
5c13f347c68fa8b3748b0dd993fc17752ffd605d
refs/heads/master
2020-05-24T20:55:55.411000
2019-07-07T11:54:43
2019-07-07T11:54:43
187,465,162
0
0
Apache-2.0
false
2019-07-07T11:54:44
2019-05-19T10:56:55
2019-06-30T11:50:22
2019-07-07T11:54:44
200
0
0
0
Java
false
false
package st.extreme.klingklong.demo; import st.extreme.klingklong.Type; public class JVM1 { /** * Main method for testing * * @param args the arguments */ public static void main(String[] args) { System.exit(work()); } /** * Do all the work and provide an appropriate exit code * * @return the exit code (0 = success) */ public static int work() { JVMWorker worker = new JVMWorker(Type.KLING); try { worker.workAndCommunicate(); return 0; } catch (Exception e) { e.printStackTrace(); return 1; } } }
UTF-8
Java
585
java
JVM1.java
Java
[]
null
[]
package st.extreme.klingklong.demo; import st.extreme.klingklong.Type; public class JVM1 { /** * Main method for testing * * @param args the arguments */ public static void main(String[] args) { System.exit(work()); } /** * Do all the work and provide an appropriate exit code * * @return the exit code (0 = success) */ public static int work() { JVMWorker worker = new JVMWorker(Type.KLING); try { worker.workAndCommunicate(); return 0; } catch (Exception e) { e.printStackTrace(); return 1; } } }
585
0.605128
0.598291
31
17.870968
16.24955
57
false
false
0
0
0
0
0
0
0.258065
false
false
2
af8d3fc27ecb1991c0e8f5c7dee4f2c4e8334af0
22,488,448,785,275
0ba0066edc525a09b25e6754d34ddb15defca720
/commonsframework-lightApp/src/main/java/cn/singno/commonsframework/weixin/msg/receive/event/R_e_reportLocationMsg.java
207db9095096c3a80e61b679ea102c5ed31cfeda
[]
no_license
zhouguangnuan/commonsframework
https://github.com/zhouguangnuan/commonsframework
bcc6fee367582f164427e00c043d747f8778f5af
c62e1283a61b6a1c1bece1aaccad70550ed3350e
refs/heads/master
2021-01-17T10:10:18.121000
2016-08-26T04:08:28
2016-08-26T04:08:28
42,493,947
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.singno.commonsframework.weixin.msg.receive.event; import cn.singno.commonsframework.weixin.msg.receive.ReceiveMsg; /** * <p>名称:R_e_subscribeMsg.java</p> * <p>描述:上报地理位置事件</p> * <pre> * 接收事件推送 * * 用户同意上报地理位置后,每次进入公众号会话时,都会在进入时上报地理位置,或在进入会话后每5秒上报一次地理位置,公众号可以在公众平台网站中修改以上设置。 * 上报地理位置时,微信会将上报地理位置事件推送到开发者填写的URL * </pre> * @author 周光暖 * @date 2015-5-25 下午5:57:56 * @version 1.0.0 */ public class R_e_reportLocationMsg extends ReceiveMsg { private String event;// 事件类型(LOCATION) private Double latitude;// 地理位置纬度 private Double longitude;// 地理位置经度 private Double Precision;// 地理位置精度 public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getPrecision() { return Precision; } public void setPrecision(Double precision) { Precision = precision; } }
UTF-8
Java
1,435
java
R_e_reportLocationMsg.java
Java
[ { "context": "位置时,微信会将上报地理位置事件推送到开发者填写的URL\n * </pre>\n * @author 周光暖\n * @date 2015-5-25 下午5:57:56\n * @version 1.0.0\n *", "end": 363, "score": 0.9998404383659363, "start": 360, "tag": "NAME", "value": "周光暖" } ]
null
[]
package cn.singno.commonsframework.weixin.msg.receive.event; import cn.singno.commonsframework.weixin.msg.receive.ReceiveMsg; /** * <p>名称:R_e_subscribeMsg.java</p> * <p>描述:上报地理位置事件</p> * <pre> * 接收事件推送 * * 用户同意上报地理位置后,每次进入公众号会话时,都会在进入时上报地理位置,或在进入会话后每5秒上报一次地理位置,公众号可以在公众平台网站中修改以上设置。 * 上报地理位置时,微信会将上报地理位置事件推送到开发者填写的URL * </pre> * @author 周光暖 * @date 2015-5-25 下午5:57:56 * @version 1.0.0 */ public class R_e_reportLocationMsg extends ReceiveMsg { private String event;// 事件类型(LOCATION) private Double latitude;// 地理位置纬度 private Double longitude;// 地理位置经度 private Double Precision;// 地理位置精度 public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getPrecision() { return Precision; } public void setPrecision(Double precision) { Precision = precision; } }
1,435
0.71618
0.702034
56
19.196428
18.919395
81
false
false
0
0
0
0
0
0
1.053571
false
false
2
3b7fa6c293e9e0e36cd1ac460cb1f453170e261f
30,099,130,882,607
a36cc163809ab6e24bfd136f557a294ab756590e
/hrportal/src/main/java/com/zenith/hrportal/entities/category/CategoryGrade.java
b425b461369b664aac323caa727bef50f7c4460b
[]
no_license
serhat26/JavaAngularCombined
https://github.com/serhat26/JavaAngularCombined
7ee364500e5e1cf7d96e77ef34a203a7950647bf
170da1838c0ee768dabf4a95518356fad6ec5b74
refs/heads/master
2023-02-11T00:42:52.873000
2021-01-14T18:13:06
2021-01-14T18:13:06
329,697,405
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zenith.hrportal.entities.category; import com.zenith.hrportal.entities.company.Company; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * The type Category grade. */ @Entity @Table(name = "PP_CATG_STATUSES") public class CategoryGrade implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private CategoryGradIdentity categoryGradIdentity; @Column(name = "DESCRIPTION") private String description; @Column(name = "UPDATE_BY") private String updatedBy; @Column(name = "UPDATE_ON") private Date updatedOn; @Column(name = "CREATE_BY") private String createdBy; @Column(name = "CREATE_ON") private Date createdOn; @ManyToOne() @JoinColumn(name = "COMP_CODE",insertable = false,updatable = false) private Company company; @Column(name = "SALARY_FROM") private Long salaryFrom; @Column(name = "SALARY_TO") private Long salaryTo; /** * Gets category grad identity. * * @return the category grad identity */ public CategoryGradIdentity getCategoryGradIdentity() { return categoryGradIdentity; } /** * Sets category grad identity. * * @param categoryGradIdentity the category grad identity */ public void setCategoryGradIdentity(CategoryGradIdentity categoryGradIdentity) { this.categoryGradIdentity = categoryGradIdentity; } /** * Gets description. * * @return the description */ public String getDescription() { return description; } /** * Sets description. * * @param description the description */ public void setDescription(String description) { this.description = description; } /** * Gets updated by. * * @return the updated by */ public String getUpdatedBy() { return updatedBy; } /** * Sets updated by. * * @param updatedBy the updated by */ public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } /** * Gets updated on. * * @return the updated on */ public Date getUpdatedOn() { return updatedOn; } /** * Sets updated on. * * @param updatedOn the updated on */ public void setUpdatedOn(Date updatedOn) { this.updatedOn = updatedOn; } /** * Gets created by. * * @return the created by */ public String getCreatedBy() { return createdBy; } /** * Sets created by. * * @param createdBy the created by */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * Gets created on. * * @return the created on */ public Date getCreatedOn() { return createdOn; } /** * Sets created on. * * @param createdOn the created on */ public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } /** * Gets company. * * @return the company */ public Company getCompany() { return company; } /** * Sets company. * * @param company the company */ public void setCompany(Company company) { this.company = company; } }
UTF-8
Java
3,582
java
CategoryGrade.java
Java
[]
null
[]
package com.zenith.hrportal.entities.category; import com.zenith.hrportal.entities.company.Company; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * The type Category grade. */ @Entity @Table(name = "PP_CATG_STATUSES") public class CategoryGrade implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private CategoryGradIdentity categoryGradIdentity; @Column(name = "DESCRIPTION") private String description; @Column(name = "UPDATE_BY") private String updatedBy; @Column(name = "UPDATE_ON") private Date updatedOn; @Column(name = "CREATE_BY") private String createdBy; @Column(name = "CREATE_ON") private Date createdOn; @ManyToOne() @JoinColumn(name = "COMP_CODE",insertable = false,updatable = false) private Company company; @Column(name = "SALARY_FROM") private Long salaryFrom; @Column(name = "SALARY_TO") private Long salaryTo; /** * Gets category grad identity. * * @return the category grad identity */ public CategoryGradIdentity getCategoryGradIdentity() { return categoryGradIdentity; } /** * Sets category grad identity. * * @param categoryGradIdentity the category grad identity */ public void setCategoryGradIdentity(CategoryGradIdentity categoryGradIdentity) { this.categoryGradIdentity = categoryGradIdentity; } /** * Gets description. * * @return the description */ public String getDescription() { return description; } /** * Sets description. * * @param description the description */ public void setDescription(String description) { this.description = description; } /** * Gets updated by. * * @return the updated by */ public String getUpdatedBy() { return updatedBy; } /** * Sets updated by. * * @param updatedBy the updated by */ public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } /** * Gets updated on. * * @return the updated on */ public Date getUpdatedOn() { return updatedOn; } /** * Sets updated on. * * @param updatedOn the updated on */ public void setUpdatedOn(Date updatedOn) { this.updatedOn = updatedOn; } /** * Gets created by. * * @return the created by */ public String getCreatedBy() { return createdBy; } /** * Sets created by. * * @param createdBy the created by */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * Gets created on. * * @return the created on */ public Date getCreatedOn() { return createdOn; } /** * Sets created on. * * @param createdOn the created on */ public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } /** * Gets company. * * @return the company */ public Company getCompany() { return company; } /** * Sets company. * * @param company the company */ public void setCompany(Company company) { this.company = company; } }
3,582
0.607482
0.607203
177
19.237288
17.287537
84
false
false
0
0
0
0
0
0
0.20339
false
false
2
2128792271bd284d75678e2d8b5433f393ec70f5
4,320,737,159,137
9fcb7ab22f6c7709193a147b0bf99902f724ee5e
/src/java/test/RecordDisplayServiceTest.java
4b94d0df63b0cdcedfd9c824ccdae544079bbcc9
[]
no_license
tarish/cyrus-code-test
https://github.com/tarish/cyrus-code-test
e3dfa52c1ce60298bbbe13b0cc3a0635a389e4b4
5098df545875929b0ad91a4244a88d82e761fa46
refs/heads/master
2020-03-27T00:25:16.137000
2018-09-20T02:02:18
2018-09-20T02:02:18
145,182,842
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by Tarish Rhees on 8/23/2018. */ public class RecordDisplayServiceTest { private Record GRACE_HALFELF; private Record LUNARIENNE_GNOME; private Record LAMIERINA_WARRIOR; //Object Under Test private RecordDisplayService displayService; @Before public void setUp() throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); GRACE_HALFELF = new Record("Halfelf", "Grace", "L", "F", "black", formatter.parse("1/23/1913")); LUNARIENNE_GNOME = new Record("Gnome", "Lunarienne", "", "F", "white", formatter.parse("5/3/2004")); LAMIERINA_WARRIOR = new Record("Warrior", "Lamierina", "S", "F", "red", formatter.parse("8/31/2005")); displayService = new RecordDisplayService(); } @Test public void getsHeaderLineForRecordReport() { assertThat(displayService.getRecordReportHeaderLine(), is("Last Name\t\t|\t\tFirst Name\t\t|\t\tGender\t\t|\t\tDate of Birth\t\t|\t\tFavorite Color") ); } @Test public void getsSetOfRecordsForDisplay() { Set<Record> records = new HashSet<>(); records.add(GRACE_HALFELF); records.add(LUNARIENNE_GNOME); assertThat(displayService.getRecordsForDisplay(records), is( "Halfelf\t\t\t|\t\tGrace\t\t|\t\tF\t\t|\t\t01/23/1913\t\t|\t\tblack\n" + "Gnome\t\t\t|\t\tLunarienne\t\t|\t\tF\t\t|\t\t05/03/2004\t\t|\t\twhite\n" )); } @Test public void displaysSetOfRecordsAsFile() throws IOException { Set<Record> records = new HashSet<>(); records.add(GRACE_HALFELF); records.add(LUNARIENNE_GNOME); File result = displayService.displayAsFile(records, "resources\\records.txt"); assertThat(result.exists(), is(true)); assertThat(result.getPath(), is("resources\\records.txt")); //TODO: Find a better way to test comparing file output! result.deleteOnExit(); } @Test public void displaySetOfRecordsSortedByLastName() throws IOException { Set<Record> records = new HashSet<>(); records.add(GRACE_HALFELF); records.add(LAMIERINA_WARRIOR); records.add(LUNARIENNE_GNOME); //TODO: Improve! Make into actual file rather than just duplicating the underlying code. RecordSet recordSet = new RecordSet(); recordSet.setRecords(records); File expected = displayService.displayAsFile(recordSet.getRecordsSortedByLastNameDescending(), "resources\\expected.txt"); File result = displayService.displayRecordsSortedByDescendingLastName(records, "resources\\records.txt"); byte[] resultArray = Files.readAllBytes(result.toPath()); byte[] expectedArray = Files.readAllBytes(expected.toPath()); assertThat(resultArray, is(expectedArray)); result.deleteOnExit(); expected.deleteOnExit(); } }
UTF-8
Java
3,279
java
RecordDisplayServiceTest.java
Java
[ { "context": "crest.MatcherAssert.assertThat;\n\n/**\n * Created by Tarish Rhees on 8/23/2018.\n */\npublic class RecordDisplayServi", "end": 371, "score": 0.9998836517333984, "start": 359, "tag": "NAME", "value": "Tarish Rhees" } ]
null
[]
import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by <NAME> on 8/23/2018. */ public class RecordDisplayServiceTest { private Record GRACE_HALFELF; private Record LUNARIENNE_GNOME; private Record LAMIERINA_WARRIOR; //Object Under Test private RecordDisplayService displayService; @Before public void setUp() throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); GRACE_HALFELF = new Record("Halfelf", "Grace", "L", "F", "black", formatter.parse("1/23/1913")); LUNARIENNE_GNOME = new Record("Gnome", "Lunarienne", "", "F", "white", formatter.parse("5/3/2004")); LAMIERINA_WARRIOR = new Record("Warrior", "Lamierina", "S", "F", "red", formatter.parse("8/31/2005")); displayService = new RecordDisplayService(); } @Test public void getsHeaderLineForRecordReport() { assertThat(displayService.getRecordReportHeaderLine(), is("Last Name\t\t|\t\tFirst Name\t\t|\t\tGender\t\t|\t\tDate of Birth\t\t|\t\tFavorite Color") ); } @Test public void getsSetOfRecordsForDisplay() { Set<Record> records = new HashSet<>(); records.add(GRACE_HALFELF); records.add(LUNARIENNE_GNOME); assertThat(displayService.getRecordsForDisplay(records), is( "Halfelf\t\t\t|\t\tGrace\t\t|\t\tF\t\t|\t\t01/23/1913\t\t|\t\tblack\n" + "Gnome\t\t\t|\t\tLunarienne\t\t|\t\tF\t\t|\t\t05/03/2004\t\t|\t\twhite\n" )); } @Test public void displaysSetOfRecordsAsFile() throws IOException { Set<Record> records = new HashSet<>(); records.add(GRACE_HALFELF); records.add(LUNARIENNE_GNOME); File result = displayService.displayAsFile(records, "resources\\records.txt"); assertThat(result.exists(), is(true)); assertThat(result.getPath(), is("resources\\records.txt")); //TODO: Find a better way to test comparing file output! result.deleteOnExit(); } @Test public void displaySetOfRecordsSortedByLastName() throws IOException { Set<Record> records = new HashSet<>(); records.add(GRACE_HALFELF); records.add(LAMIERINA_WARRIOR); records.add(LUNARIENNE_GNOME); //TODO: Improve! Make into actual file rather than just duplicating the underlying code. RecordSet recordSet = new RecordSet(); recordSet.setRecords(records); File expected = displayService.displayAsFile(recordSet.getRecordsSortedByLastNameDescending(), "resources\\expected.txt"); File result = displayService.displayRecordsSortedByDescendingLastName(records, "resources\\records.txt"); byte[] resultArray = Files.readAllBytes(result.toPath()); byte[] expectedArray = Files.readAllBytes(expected.toPath()); assertThat(resultArray, is(expectedArray)); result.deleteOnExit(); expected.deleteOnExit(); } }
3,273
0.669411
0.656298
94
33.893616
32.486813
130
false
false
0
0
0
0
0
0
0.851064
false
false
2
62ca8411016dd454e0ebf4ff2f7102c9139c21e4
22,780,506,595,329
2d555a9960d934f887ebb9da1a9b72599361a63b
/Project/Project/src/X.java
babe8b49e10c949ad4b008ccf00edd9f166241e5
[]
no_license
T1-Frank/Mathematical-Art
https://github.com/T1-Frank/Mathematical-Art
ce145627e895ab1fe6d6903fa74ecb9f7e38da8f
e0767dff09557ef2aca57607a728773c776e8059
refs/heads/main
2023-09-01T18:53:55.129000
2021-10-13T07:18:00
2021-10-13T07:18:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Random; public class X extends Expression { @Override public double evaluate(double x, double y) { return x; } public Expression variation(int maxDepth, Random random) { if (random.nextBoolean()) { return Expression.random(maxDepth, random); } else { return this; } } }
UTF-8
Java
323
java
X.java
Java
[]
null
[]
import java.util.Random; public class X extends Expression { @Override public double evaluate(double x, double y) { return x; } public Expression variation(int maxDepth, Random random) { if (random.nextBoolean()) { return Expression.random(maxDepth, random); } else { return this; } } }
323
0.665635
0.665635
18
16.944445
18.404324
59
false
false
0
0
0
0
0
0
1.222222
false
false
2
879208c4a90f7b72db70ed0172b912e95caa9c76
25,348,897,012,008
456fa0dc04f6f7388a5ecbaaf84db09cb3bf0b39
/App03/data/src/main/java/com/carrion/edward/data/repository/datasource/MovieDataStoreFactory.java
8dc77b35ae9a30910eefd98202f48bc6a84d5800
[]
no_license
edwardc29/samples
https://github.com/edwardc29/samples
9898a680b9cb945ede77bdf2bc247b13ae9b7f27
af44c210483caf6f7daf56373beed13249fa9ec0
refs/heads/master
2020-04-21T10:36:33.144000
2019-02-07T00:31:59
2019-02-07T00:31:59
169,491,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.carrion.edward.data.repository.datasource; import android.content.Context; import android.support.annotation.NonNull; import com.carrion.edward.data.entity.mapper.MovieEntityJsonMapper; import com.carrion.edward.data.net.RestApi; import com.carrion.edward.data.net.RestApiImpl; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class MovieDataStoreFactory { private final Context context; @Inject MovieDataStoreFactory(@NonNull Context context) { this.context = context.getApplicationContext(); } public MovieDataStore create(int userId) { MovieDataStore movieDataStore; //Validate if disk or cloud movieDataStore = createCloudDataStore(); return movieDataStore; } public MovieDataStore createCloudDataStore() { final MovieEntityJsonMapper movieEntityJsonMapper = new MovieEntityJsonMapper(); final RestApi restApi = new RestApiImpl(this.context, movieEntityJsonMapper); return new CloudMovieDataStore(restApi); } }
UTF-8
Java
1,061
java
MovieDataStoreFactory.java
Java
[]
null
[]
package com.carrion.edward.data.repository.datasource; import android.content.Context; import android.support.annotation.NonNull; import com.carrion.edward.data.entity.mapper.MovieEntityJsonMapper; import com.carrion.edward.data.net.RestApi; import com.carrion.edward.data.net.RestApiImpl; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class MovieDataStoreFactory { private final Context context; @Inject MovieDataStoreFactory(@NonNull Context context) { this.context = context.getApplicationContext(); } public MovieDataStore create(int userId) { MovieDataStore movieDataStore; //Validate if disk or cloud movieDataStore = createCloudDataStore(); return movieDataStore; } public MovieDataStore createCloudDataStore() { final MovieEntityJsonMapper movieEntityJsonMapper = new MovieEntityJsonMapper(); final RestApi restApi = new RestApiImpl(this.context, movieEntityJsonMapper); return new CloudMovieDataStore(restApi); } }
1,061
0.752121
0.752121
37
27.675676
25.374018
88
false
false
0
0
0
0
0
0
0.459459
false
false
2
eb61f6d83da6f60919966312fe82f47c413293e6
16,277,926,076,930
a2d2cb028465b3f6a1be3e750efcb30fcf9f5e10
/src/main/java/ru/geekbrains/justweather/HourlyWeatherRecyclerDataAdapter.java
1fc14d70effc89c226c6ff3965ed1e438f3f18d0
[]
no_license
SmallBasket42/geekbrains_android2
https://github.com/SmallBasket42/geekbrains_android2
1eb1c089e4f6ebbf37aa65e3de79c4a0e5eec896
ea38648225b49075df5e676783746b408037052b
refs/heads/master
2023-01-07T15:42:05.425000
2020-09-13T13:17:19
2020-09-13T13:17:19
295,152,522
0
0
null
false
2020-10-20T15:50:42
2020-09-13T13:03:26
2020-09-13T13:18:02
2020-10-20T15:49:55
1,354
0
0
6
Java
false
false
package ru.geekbrains.justweather; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class HourlyWeatherRecyclerDataAdapter extends RecyclerView.Adapter<HourlyWeatherRecyclerDataAdapter.ViewHolder> { private List<Integer> hourlyWeatherIcon ; private List<String> hourlyTime; private List<String> hourlyTemperature; private RVOnItemClick onItemClickCallback; public HourlyWeatherRecyclerDataAdapter(List<String> hourlyTime, List<Integer> hourlyWeatherIcon, List<String> hourlyTemperature, RVOnItemClick onItemClickCallback) { this.hourlyTime = hourlyTime; this.hourlyWeatherIcon = hourlyWeatherIcon; this.hourlyTemperature = hourlyTemperature; this.onItemClickCallback = onItemClickCallback; } @NonNull @Override public HourlyWeatherRecyclerDataAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hourly_weather_recyclerview_layout, parent, false); return new HourlyWeatherRecyclerDataAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull HourlyWeatherRecyclerDataAdapter.ViewHolder holder, int position) { String time = hourlyTime.get(position); Integer weatherIcon = hourlyWeatherIcon.get(position); String temperature = hourlyTemperature.get(position); holder.setTextToTimeTextView(time); holder.setTextToHourlyTemperatureTextView(temperature); holder.setImageToHourlyWeatherIconImageView(weatherIcon); holder.setOnClickForItem(time); } @Override public int getItemCount() { return hourlyTime == null ? 0 : hourlyTime.size(); }// class ViewHolder extends RecyclerView.ViewHolder { private TextView timeTextView; private TextView hourlyTemperatureTextView; private ImageView hourlyWeatherIconImageView; public ViewHolder(@NonNull View itemView) { super(itemView); timeTextView = itemView.findViewById(R.id.time); hourlyTemperatureTextView = itemView.findViewById(R.id.hourlyTemperature); hourlyWeatherIconImageView = itemView.findViewById(R.id.hourlyWeatherIcon); } void setTextToTimeTextView(String text) { timeTextView.setText(text); } void setTextToHourlyTemperatureTextView(String text) { hourlyTemperatureTextView.setText(text);} void setImageToHourlyWeatherIconImageView(int resourceId) { hourlyWeatherIconImageView.setImageResource(resourceId);} void setOnClickForItem(final String day) { hourlyWeatherIconImageView.setOnClickListener(view -> { if(onItemClickCallback != null) { onItemClickCallback.onItemClicked(view, day); } }); } } }
UTF-8
Java
3,131
java
HourlyWeatherRecyclerDataAdapter.java
Java
[]
null
[]
package ru.geekbrains.justweather; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class HourlyWeatherRecyclerDataAdapter extends RecyclerView.Adapter<HourlyWeatherRecyclerDataAdapter.ViewHolder> { private List<Integer> hourlyWeatherIcon ; private List<String> hourlyTime; private List<String> hourlyTemperature; private RVOnItemClick onItemClickCallback; public HourlyWeatherRecyclerDataAdapter(List<String> hourlyTime, List<Integer> hourlyWeatherIcon, List<String> hourlyTemperature, RVOnItemClick onItemClickCallback) { this.hourlyTime = hourlyTime; this.hourlyWeatherIcon = hourlyWeatherIcon; this.hourlyTemperature = hourlyTemperature; this.onItemClickCallback = onItemClickCallback; } @NonNull @Override public HourlyWeatherRecyclerDataAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hourly_weather_recyclerview_layout, parent, false); return new HourlyWeatherRecyclerDataAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull HourlyWeatherRecyclerDataAdapter.ViewHolder holder, int position) { String time = hourlyTime.get(position); Integer weatherIcon = hourlyWeatherIcon.get(position); String temperature = hourlyTemperature.get(position); holder.setTextToTimeTextView(time); holder.setTextToHourlyTemperatureTextView(temperature); holder.setImageToHourlyWeatherIconImageView(weatherIcon); holder.setOnClickForItem(time); } @Override public int getItemCount() { return hourlyTime == null ? 0 : hourlyTime.size(); }// class ViewHolder extends RecyclerView.ViewHolder { private TextView timeTextView; private TextView hourlyTemperatureTextView; private ImageView hourlyWeatherIconImageView; public ViewHolder(@NonNull View itemView) { super(itemView); timeTextView = itemView.findViewById(R.id.time); hourlyTemperatureTextView = itemView.findViewById(R.id.hourlyTemperature); hourlyWeatherIconImageView = itemView.findViewById(R.id.hourlyWeatherIcon); } void setTextToTimeTextView(String text) { timeTextView.setText(text); } void setTextToHourlyTemperatureTextView(String text) { hourlyTemperatureTextView.setText(text);} void setImageToHourlyWeatherIconImageView(int resourceId) { hourlyWeatherIconImageView.setImageResource(resourceId);} void setOnClickForItem(final String day) { hourlyWeatherIconImageView.setOnClickListener(view -> { if(onItemClickCallback != null) { onItemClickCallback.onItemClicked(view, day); } }); } } }
3,131
0.725966
0.725647
77
39.662338
35.805611
170
false
false
0
0
0
0
0
0
0.61039
false
false
2
4377b25db3b8e8483f82e09559b858060c5ffb76
18,683,107,758,395
8edd5f8745bb5073240e36906d961b9dfc026702
/SpringConfig.java
affa5c3733f427c4e1c1a6015ad9b390f4597bf9
[]
no_license
dillip37/available-parking-spaces
https://github.com/dillip37/available-parking-spaces
f0cd2ebb0163ab679040ac7b384e6659d85fe0bf
48947dfaf6b6103b21fc9b214789c18adeb4816c
refs/heads/master
2022-12-24T01:08:09.385000
2020-09-28T17:58:52
2020-09-28T17:58:52
299,387,825
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.restservice; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class SpringConfig { @Bean public DataSource postgresDataSource() { System.out.println("Creating Datasource"); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl("jdbc:postgresql://localhost:5432/devdb"); dataSource.setUsername("dbuser"); dataSource.setTestOnBorrow(true); dataSource.setTestWhileIdle(true); int intialSize = 1; dataSource.setInitialSize(1); dataSource.setMaxTotal(5); dataSource.setMinIdle(1); dataSource.setTimeBetweenEvictionRunsMillis(1000L); dataSource.setMinEvictableIdleTimeMillis(1000L); dataSource.setPassword("Temp1234"); return dataSource; } @Primary @Bean(name = "jdbcTemplate") public JdbcTemplate jdbcTemplate() { System.out.println("Creating JdbcTemplate"); JdbcTemplate jdbcTemplate = new JdbcTemplate(postgresDataSource()); return jdbcTemplate; } }
UTF-8
Java
1,349
java
SpringConfig.java
Java
[ { "context": "ost:5432/devdb\");\n dataSource.setUsername(\"dbuser\");\n dataSource.setTestOnBorrow(true);\n ", "end": 691, "score": 0.9970604181289673, "start": 685, "tag": "USERNAME", "value": "dbuser" }, { "context": "meMillis(1000L);\n\n dataSource.setPass...
null
[]
package com.example.restservice; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class SpringConfig { @Bean public DataSource postgresDataSource() { System.out.println("Creating Datasource"); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl("jdbc:postgresql://localhost:5432/devdb"); dataSource.setUsername("dbuser"); dataSource.setTestOnBorrow(true); dataSource.setTestWhileIdle(true); int intialSize = 1; dataSource.setInitialSize(1); dataSource.setMaxTotal(5); dataSource.setMinIdle(1); dataSource.setTimeBetweenEvictionRunsMillis(1000L); dataSource.setMinEvictableIdleTimeMillis(1000L); dataSource.setPassword("<PASSWORD>"); return dataSource; } @Primary @Bean(name = "jdbcTemplate") public JdbcTemplate jdbcTemplate() { System.out.println("Creating JdbcTemplate"); JdbcTemplate jdbcTemplate = new JdbcTemplate(postgresDataSource()); return jdbcTemplate; } }
1,351
0.743514
0.727947
43
30.372093
22.226135
75
false
false
0
0
0
0
0
0
0.581395
false
false
2
92472828aeaa905be92a0f6f87ba1846cf1ff269
8,521,215,146,201
7b66260d79d71519b4b4f965f011666fcdecfb84
/codes/admin/src/main/java/com/x404/busi/entity/Procedure.java
5a67d8d62e54b55ce90eaf8c93abbc287160dacf
[]
no_license
Reekdnroxx7/inventory
https://github.com/Reekdnroxx7/inventory
2647a84cbecd730bf06d5d666a1fdded27efca36
80b565131fa7abfd3786183864ff743bfa605038
refs/heads/master
2023-06-05T06:45:25.093000
2021-06-16T07:39:52
2021-06-16T07:39:52
366,370,361
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.x404.busi.entity; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; /** * Created by chaox on 1/17/2018. */ public class Procedure { private String id; private String code; private String name; /**创建时间*/ @CreatedDate private java.util.Date create_date; /**创建人*/ @CreatedBy private String create_by; /***/ @LastModifiedDate private java.util.Date update_date; /***/ @LastModifiedBy private String update_by; /**备注*/ private String remarks; }
UTF-8
Java
723
java
Procedure.java
Java
[ { "context": "ta.annotation.LastModifiedDate;\n\n/**\n * Created by chaox on 1/17/2018.\n */\npublic class Procedure\n{\n pr", "end": 285, "score": 0.9992002248764038, "start": 280, "tag": "USERNAME", "value": "chaox" } ]
null
[]
package com.x404.busi.entity; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; /** * Created by chaox on 1/17/2018. */ public class Procedure { private String id; private String code; private String name; /**创建时间*/ @CreatedDate private java.util.Date create_date; /**创建人*/ @CreatedBy private String create_by; /***/ @LastModifiedDate private java.util.Date update_date; /***/ @LastModifiedBy private String update_by; /**备注*/ private String remarks; }
723
0.704965
0.69078
30
22.5
17.304625
60
false
false
0
0
0
0
0
0
0.433333
false
false
2
8d8f7c36f634c9e273d339ae5a609d5c1bd7e4c8
18,940,805,814,947
05524acdf6e9c03134129f8b6a954d1cd2da6d43
/src/org/selenium/day2/IciciBank.java
e014e1ac4d458b8a3a533d477284526abcdc38f9
[]
no_license
AmanK1010/Selenium-
https://github.com/AmanK1010/Selenium-
de1e431ffcad8cbfdf8db0a2a9dc2bc6cae6f840
0e66ad743182fd4eeeaf4242297df62ede02bcd5
refs/heads/master
2023-02-06T23:29:04.628000
2020-12-30T07:54:53
2020-12-30T07:54:53
325,490,197
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.selenium.day2; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class IciciBank { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Selenium\\driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://infinity.icicibank.com/corp/Login.jsp"); // driver.findElement(By.name("DUMMY1")).sendKeys("qwerty"); WebElement findElement = driver.findElement(By.id("user-id-goahead")); findElement.click(); driver.findElement(By.id("AuthenticationFG.USER_PRINCIPAL")).sendKeys("qwerty"); driver.findElement(By.id("AuthenticationFG.ACCESS_CODE")).sendKeys("123456"); } }
UTF-8
Java
812
java
IciciBank.java
Java
[ { "context": "gin.jsp\");\n\t\t\n\t\t\n//\t\tdriver.findElement(By.name(\"DUMMY1\")).sendKeys(\"qwerty\");\n\t\t\n\t\tWebElement findElemen", "end": 514, "score": 0.8274812698364258, "start": 509, "tag": "USERNAME", "value": "UMMY1" }, { "context": "\t\tdriver.findElement(By.name(\"D...
null
[]
package org.selenium.day2; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class IciciBank { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Selenium\\driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://infinity.icicibank.com/corp/Login.jsp"); // driver.findElement(By.name("DUMMY1")).sendKeys("qwerty"); WebElement findElement = driver.findElement(By.id("user-id-goahead")); findElement.click(); driver.findElement(By.id("AuthenticationFG.USER_PRINCIPAL")).sendKeys("qwerty"); driver.findElement(By.id("AuthenticationFG.ACCESS_CODE")).sendKeys("123456"); } }
812
0.731527
0.721675
30
26.066668
29.614111
100
false
false
0
0
0
0
0
0
1.666667
false
false
2
03948be37d4ff03a20a7097c6e1e006476083b8c
3,556,232,940,006
4d274173ce10931ce2c819acf2ab382336816c3a
/jax-core/src/main/java/com/eoi/jax/core/spark/debug/WebsocketDebugSinker.java
13009024218d6700f2f2c02abbd02f379fb330a8
[ "Apache-2.0" ]
permissive
joely110/jax
https://github.com/joely110/jax
346aa1d66f1c6c1f0f5eb1809a3a3c20cf544d36
9f54fd84f149896112bf1e39a0b60533196ac5fb
refs/heads/master
2023-06-27T03:55:05.631000
2021-08-03T06:53:15
2021-08-03T06:53:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.eoi.jax.core.spark.debug; import com.eoi.jax.api.SparkDebugSinker; import com.eoi.jax.api.SparkDebugSinkerMeta; import com.eoi.jax.api.SparkEnvironment; import com.eoi.jax.api.annotation.Job; import com.eoi.jax.api.reflect.ParamUtil; import com.eoi.jax.common.JsonUtil; import com.eoi.jax.core.WebSocketClient; import com.eoi.jax.core.WebsocketDebugSinkerConfig; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import java.net.URI; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @Job( name = "WebsocketDebugSinker", display = "WebsocketDebugSinker", description = "用于调试spark job" ) public class WebsocketDebugSinker implements SparkDebugSinker<WebsocketDebugSinkerConfig> { private static final String F_JOB_ID = "job_id"; private static final String F_SLOT = "slot"; private static final String F_MESSAGE = "message"; @Override public boolean supportDataFrame() { return true; } @Override public boolean supportRdd() { return true; } @Override public void sinkDataFrame(SparkEnvironment context, Dataset<Row> df, WebsocketDebugSinkerConfig config, SparkDebugSinkerMeta meta) { JavaRDD<Map<String, Object>> rdd = df.toJavaRDD().map(row -> { Map<String, Object> map = new LinkedHashMap<>(); String[] names = row.schema().fieldNames(); for (int i = 0; i < names.length; i++) { String name = names[i]; map.put(name, row.get(i)); } return map; }); sinkWebsocket(rdd, config, meta); } @Override public void sinkRdd(SparkEnvironment context, RDD<Map<String, Object>> rdd, WebsocketDebugSinkerConfig config, SparkDebugSinkerMeta meta) { sinkWebsocket(rdd.toJavaRDD(), config, meta); } @Override public WebsocketDebugSinkerConfig configure(Map<String, Object> mapConfig) throws Throwable { WebsocketDebugSinkerConfig config = new WebsocketDebugSinkerConfig(); ParamUtil.configJobParams(config, mapConfig); return config; } private void sinkWebsocket(JavaRDD<Map<String, Object>> rdd, WebsocketDebugSinkerConfig config, SparkDebugSinkerMeta meta) { final String uri = config.getUri(); rdd.foreachPartition(partition -> { WebSocketClient client = new WebSocketClient(new URI(uri)); try { client.connectBlocking(10, TimeUnit.SECONDS); while (partition.hasNext()) { Map<String, Object> value = partition.next(); Map<String, Object> result = new HashMap<>(); result.put(F_JOB_ID, meta.metaConfig.getJobId()); result.put(F_SLOT, meta.slotIndex); result.put(F_MESSAGE, JsonUtil.encode(value)); client.send(JsonUtil.encode(result)); } } finally { client.close(); } }); } }
UTF-8
Java
3,741
java
WebsocketDebugSinker.java
Java
[]
null
[]
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.eoi.jax.core.spark.debug; import com.eoi.jax.api.SparkDebugSinker; import com.eoi.jax.api.SparkDebugSinkerMeta; import com.eoi.jax.api.SparkEnvironment; import com.eoi.jax.api.annotation.Job; import com.eoi.jax.api.reflect.ParamUtil; import com.eoi.jax.common.JsonUtil; import com.eoi.jax.core.WebSocketClient; import com.eoi.jax.core.WebsocketDebugSinkerConfig; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import java.net.URI; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @Job( name = "WebsocketDebugSinker", display = "WebsocketDebugSinker", description = "用于调试spark job" ) public class WebsocketDebugSinker implements SparkDebugSinker<WebsocketDebugSinkerConfig> { private static final String F_JOB_ID = "job_id"; private static final String F_SLOT = "slot"; private static final String F_MESSAGE = "message"; @Override public boolean supportDataFrame() { return true; } @Override public boolean supportRdd() { return true; } @Override public void sinkDataFrame(SparkEnvironment context, Dataset<Row> df, WebsocketDebugSinkerConfig config, SparkDebugSinkerMeta meta) { JavaRDD<Map<String, Object>> rdd = df.toJavaRDD().map(row -> { Map<String, Object> map = new LinkedHashMap<>(); String[] names = row.schema().fieldNames(); for (int i = 0; i < names.length; i++) { String name = names[i]; map.put(name, row.get(i)); } return map; }); sinkWebsocket(rdd, config, meta); } @Override public void sinkRdd(SparkEnvironment context, RDD<Map<String, Object>> rdd, WebsocketDebugSinkerConfig config, SparkDebugSinkerMeta meta) { sinkWebsocket(rdd.toJavaRDD(), config, meta); } @Override public WebsocketDebugSinkerConfig configure(Map<String, Object> mapConfig) throws Throwable { WebsocketDebugSinkerConfig config = new WebsocketDebugSinkerConfig(); ParamUtil.configJobParams(config, mapConfig); return config; } private void sinkWebsocket(JavaRDD<Map<String, Object>> rdd, WebsocketDebugSinkerConfig config, SparkDebugSinkerMeta meta) { final String uri = config.getUri(); rdd.foreachPartition(partition -> { WebSocketClient client = new WebSocketClient(new URI(uri)); try { client.connectBlocking(10, TimeUnit.SECONDS); while (partition.hasNext()) { Map<String, Object> value = partition.next(); Map<String, Object> result = new HashMap<>(); result.put(F_JOB_ID, meta.metaConfig.getJobId()); result.put(F_SLOT, meta.slotIndex); result.put(F_MESSAGE, JsonUtil.encode(value)); client.send(JsonUtil.encode(result)); } } finally { client.close(); } }); } }
3,741
0.660863
0.658987
101
35.960396
29.857059
143
false
false
0
0
0
0
0
0
0.782178
false
false
2
222cc4301da018221625ced0d03f43bb2c6d1888
10,479,720,221,824
b4ddfbb7ea8c5dc4b9dcc07e0f356254250037af
/src/main/java/hr/fer/zemris/java/hw12/jvdraw/objects/Line.java
0fb8ae160d1c9955e9af611d6e91f347c3d91dcd
[]
no_license
vilimstaroveski/JavaCourse-HW12
https://github.com/vilimstaroveski/JavaCourse-HW12
4e3a9bd9ccf0f241f2e1c2f21646cb014f891844
76edc527d2c9dd83ba9a754c1f0f53d1125a5928
refs/heads/master
2021-07-05T22:33:24.401000
2019-06-23T00:42:03
2019-06-23T00:42:03
193,291,603
0
0
null
false
2020-10-13T14:05:37
2019-06-23T00:41:03
2019-06-23T00:42:06
2020-10-13T14:05:36
746
0
0
1
HTML
false
false
package hr.fer.zemris.java.hw12.jvdraw.objects; import java.awt.Color; import java.awt.Point; /** * Object that represents a line. * @author Vilim Staroveški * */ public class Line extends GeometricalObject { /** * Creates new {@link Line} * @param color outline color */ public Line(Color color) { super(); this.outline = color; name = "LINE"; } @Override public Point getUpperLeftCorner() { int minX = startPointX <= endPointX ? startPointX : endPointX; int minY = startPointY <= endPointY ? startPointY : endPointY; return new Point(minX, minY); } @Override public Point getDownRightCorner() { int maxX = startPointX >= endPointX ? startPointX : endPointX; int maxY = startPointY >= endPointY ? startPointY : endPointY; return new Point(maxX, maxY); } }
UTF-8
Java
835
java
Line.java
Java
[ { "context": "/**\r\n * Object that represents a line.\r\n * @author Vilim Staroveški\r\n *\r\n */\r\npublic class Line extends GeometricalOb", "end": 166, "score": 0.9996703863143921, "start": 150, "tag": "NAME", "value": "Vilim Staroveški" } ]
null
[]
package hr.fer.zemris.java.hw12.jvdraw.objects; import java.awt.Color; import java.awt.Point; /** * Object that represents a line. * @author <NAME> * */ public class Line extends GeometricalObject { /** * Creates new {@link Line} * @param color outline color */ public Line(Color color) { super(); this.outline = color; name = "LINE"; } @Override public Point getUpperLeftCorner() { int minX = startPointX <= endPointX ? startPointX : endPointX; int minY = startPointY <= endPointY ? startPointY : endPointY; return new Point(minX, minY); } @Override public Point getDownRightCorner() { int maxX = startPointX >= endPointX ? startPointX : endPointX; int maxY = startPointY >= endPointY ? startPointY : endPointY; return new Point(maxX, maxY); } }
824
0.665468
0.66307
35
21.828571
20.568333
64
false
false
0
0
0
0
0
0
1.285714
false
false
2
05ec82847e343c5553b4ce8b2f38a455954f4245
5,420,248,746,428
ab35edcd3437bbf9940dd5d2d089d64f303f137f
/iBase4J-Common/src/main/java/org/ibase4j/core/listener/SessionListener.java
b882f14ce4fe307a04ac85930e027ee36f73529e
[]
no_license
Fog-computing/health
https://github.com/Fog-computing/health
d1ebe720478b78b3e890be1413683b7e4ec89753
9458fe3734c3b44aaa70c33412d7dd1fe4dfec96
refs/heads/master
2020-04-08T11:11:17.192000
2018-11-30T03:32:22
2018-11-30T03:32:22
159,296,342
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ibase4j.core.listener; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ibase4j.core.Constants; import org.ibase4j.core.util.CacheUtil; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * 会话监听器 * * @author ShenHuaJie * @version $Id: SessionListener.java, v 0.1 2014年3月28日 上午9:06:12 ShenHuaJie Exp */ public class SessionListener implements HttpSessionListener { private Logger logger = LogManager.getLogger (SessionListener.class); /* * (non-Javadoc) * * @see * javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http * .HttpSessionEvent) */ public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession (); session.setAttribute (Constants.WEBTHEME, "default"); logger.info ("创建了一个Session连接:[" + session.getId () + "]"); CacheUtil.getCache ().sadd (Constants.ALLUSER_NUMBER, session.getId ()); } /* * (non-Javadoc) * * @see * javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet * .http.HttpSessionEvent) */ public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession (); if (getAllUserNumber () > 0) { logger.info ("销毁了一个Session连接:[" + session.getId () + "]"); } session.removeAttribute (Constants.CURRENT_USER); CacheUtil.getCache ().sdel (Constants.ALLUSER_NUMBER, session.getId ()); } /** * 获取在线用户数量 */ public Integer getAllUserNumber() { return CacheUtil.getCache ().sall (Constants.ALLUSER_NUMBER).size (); } }
UTF-8
Java
1,834
java
SessionListener.java
Java
[ { "context": "p.HttpSessionListener;\n\n/**\n * 会话监听器\n *\n * @author ShenHuaJie\n * @version $Id: SessionListener.java, v 0.1 2014", "end": 364, "score": 0.9998461604118347, "start": 354, "tag": "NAME", "value": "ShenHuaJie" } ]
null
[]
package org.ibase4j.core.listener; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ibase4j.core.Constants; import org.ibase4j.core.util.CacheUtil; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * 会话监听器 * * @author ShenHuaJie * @version $Id: SessionListener.java, v 0.1 2014年3月28日 上午9:06:12 ShenHuaJie Exp */ public class SessionListener implements HttpSessionListener { private Logger logger = LogManager.getLogger (SessionListener.class); /* * (non-Javadoc) * * @see * javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http * .HttpSessionEvent) */ public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession (); session.setAttribute (Constants.WEBTHEME, "default"); logger.info ("创建了一个Session连接:[" + session.getId () + "]"); CacheUtil.getCache ().sadd (Constants.ALLUSER_NUMBER, session.getId ()); } /* * (non-Javadoc) * * @see * javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet * .http.HttpSessionEvent) */ public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession (); if (getAllUserNumber () > 0) { logger.info ("销毁了一个Session连接:[" + session.getId () + "]"); } session.removeAttribute (Constants.CURRENT_USER); CacheUtil.getCache ().sdel (Constants.ALLUSER_NUMBER, session.getId ()); } /** * 获取在线用户数量 */ public Integer getAllUserNumber() { return CacheUtil.getCache ().sall (Constants.ALLUSER_NUMBER).size (); } }
1,834
0.673446
0.662147
57
30.052631
27.091412
80
false
false
0
0
0
0
0
0
0.385965
false
false
2
375bedb771acaacf66588db8975f16986cb7b335
23,965,917,531,506
dd8b05598c3d0815664521abae8ca851870008fa
/Zac/Zacs Code/Positron_C.java
95d4c91f0989747fa15541e26a6bef4cabf6ae5f
[]
no_license
donmegamuffin/PHYS488_Project
https://github.com/donmegamuffin/PHYS488_Project
e0667d327af47672426073b5c635ecac7ef843ce
d701a9baa676e2c66319abbb94b462d4832fe65f
refs/heads/master
2021-01-19T03:27:02.938000
2017-05-05T10:09:12
2017-05-05T10:09:12
87,312,582
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Random; class Positron_C extends Positron { Random randGen = new Random(); public Positron_C(double in_momentum) { momentum = in_momentum; energy = Math.sqrt(Math.pow(momentum,2)+Math.pow(mass,2)); beta = (momentum/energy); gamma = (energy/mass); lifetime = momentum*gamma; } public double getVelocity() { return (beta*c); } }
UTF-8
Java
419
java
Positron_C.java
Java
[]
null
[]
import java.util.Random; class Positron_C extends Positron { Random randGen = new Random(); public Positron_C(double in_momentum) { momentum = in_momentum; energy = Math.sqrt(Math.pow(momentum,2)+Math.pow(mass,2)); beta = (momentum/energy); gamma = (energy/mass); lifetime = momentum*gamma; } public double getVelocity() { return (beta*c); } }
419
0.596659
0.591885
17
23.705883
17.234591
66
false
false
0
0
0
0
0
0
0.588235
false
false
2
d7b7e72fdeec120c7fc820a87b30bbb9cc0597c8
6,597,069,803,859
a707e42b2336c58d6c506f98277d2e2d705894fd
/Microgrid/src/mg/AuctionInterface.java
313eb338e505bce2b7cda3c5616c3948498ee5db
[]
no_license
tarmokorotko/microgrid
https://github.com/tarmokorotko/microgrid
f092798c02f3e22fc281c56062fb4dc41f5a5889
be95d4c191a80d30bbec482b699f463825d095a5
refs/heads/master
2020-03-24T20:56:03.715000
2018-10-23T06:47:54
2018-10-23T06:47:54
143,004,270
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mg; import jade.lang.acl.ACLMessage; public interface AuctionInterface { public ACLMessage startNewRound(); // method for initiating new auction round public void presentBid(String agentName, BidSet b); // method for setting auction participant data }
UTF-8
Java
272
java
AuctionInterface.java
Java
[]
null
[]
package mg; import jade.lang.acl.ACLMessage; public interface AuctionInterface { public ACLMessage startNewRound(); // method for initiating new auction round public void presentBid(String agentName, BidSet b); // method for setting auction participant data }
272
0.772059
0.772059
8
32
35.468296
99
false
false
0
0
0
0
0
0
0.875
false
false
2
e60433c68878cde82ab14eabd13b7088a3c3893e
5,892,695,162,826
6138e2a2278579f7e33d927603d9dad5a1099306
/DataAccessLayer-jar/src/main/java/models/Build.java
64c588b590bf8926b5e597703a67fbed8127d427
[]
no_license
gabrielfurcal/CollegeStudentManagementSystem
https://github.com/gabrielfurcal/CollegeStudentManagementSystem
00c3d7b9b9e9fa021285638c2db6a782b7ce2304
e5fd27bfb9f4f1e1cb896670bf469568046aa23f
refs/heads/master
2022-02-07T15:30:42.551000
2019-08-05T20:49:23
2019-08-05T20:49:23
175,835,652
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 models; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Gabriel_Liberato */ @Entity @Table(name = "BUILDS") @XmlRootElement @NamedQueries( { @NamedQuery(name = "Build.findAll", query = "SELECT b FROM Build b") , @NamedQuery(name = "Build.findByBuildId", query = "SELECT b FROM Build b WHERE b.buildsPK.buildId = :buildId") , @NamedQuery(name = "Build.findByCampusId", query = "SELECT b FROM Build b WHERE b.buildsPK.campusId = :campusId") , @NamedQuery(name = "Build.findByBuildName", query = "SELECT b FROM Build b WHERE b.buildName = :buildName") , @NamedQuery(name = "Build.findByBuildCreationDate", query = "SELECT b FROM Build b WHERE b.buildCreationDate = :buildCreationDate") }) public class Build implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected BuildPK buildsPK; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "BUILD_NAME") private String buildName; @Basic(optional = false) @NotNull @Column(name = "BUILD_CREATION_DATE") @Temporal(TemporalType.TIMESTAMP) private Date buildCreationDate; @OneToMany(cascade = CascadeType.ALL, mappedBy = "build") private List<Classroom> classrooms; @JoinColumn(name = "CAMPUS_ID", referencedColumnName = "CAMPUS_ID", insertable = false, updatable = false) @ManyToOne(optional = false, cascade = CascadeType.ALL) private Campus campus; public Build() { } public Build(BuildPK buildsPK) { this.buildsPK = buildsPK; } public Build(BuildPK buildsPK, String buildName, Date buildCreationDate) { this.buildsPK = buildsPK; this.buildName = buildName; this.buildCreationDate = buildCreationDate; } public Build(int buildId, int campusId) { this.buildsPK = new BuildPK(buildId, campusId); } public BuildPK getBuildsPK() { return buildsPK; } public void setBuildsPK(BuildPK buildsPK) { this.buildsPK = buildsPK; } public String getBuildName() { return buildName; } public void setBuildName(String buildName) { this.buildName = buildName; } public Date getBuildCreationDate() { return buildCreationDate; } public void setBuildCreationDate(Date buildCreationDate) { this.buildCreationDate = buildCreationDate; } @XmlTransient public List<Classroom> getClassrooms() { return classrooms; } public void setClassrooms(List<Classroom> classrooms) { this.classrooms = classrooms; } public Campus getCampus() { return campus; } public void setCampus(Campus campus) { this.campus = campus; } @Override public int hashCode() { int hash = 0; hash += (buildsPK != null ? buildsPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Build)) { return false; } Build other = (Build) object; if ((this.buildsPK == null && other.buildsPK != null) || (this.buildsPK != null && !this.buildsPK.equals(other.buildsPK))) { return false; } return true; } @Override public String toString() { return "Build{" + "buildsPK=" + buildsPK + ", buildName=" + buildName + ", buildCreationDate=" + buildCreationDate + '}'; } }
UTF-8
Java
4,553
java
Build.java
Java
[ { "context": "l.bind.annotation.XmlTransient;\n\n/**\n *\n * @author Gabriel_Liberato\n */\n@Entity\n@Table(name = \"BUILDS\")\n@XmlRootEleme", "end": 988, "score": 0.9993712306022644, "start": 972, "tag": "NAME", "value": "Gabriel_Liberato" } ]
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 models; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Gabriel_Liberato */ @Entity @Table(name = "BUILDS") @XmlRootElement @NamedQueries( { @NamedQuery(name = "Build.findAll", query = "SELECT b FROM Build b") , @NamedQuery(name = "Build.findByBuildId", query = "SELECT b FROM Build b WHERE b.buildsPK.buildId = :buildId") , @NamedQuery(name = "Build.findByCampusId", query = "SELECT b FROM Build b WHERE b.buildsPK.campusId = :campusId") , @NamedQuery(name = "Build.findByBuildName", query = "SELECT b FROM Build b WHERE b.buildName = :buildName") , @NamedQuery(name = "Build.findByBuildCreationDate", query = "SELECT b FROM Build b WHERE b.buildCreationDate = :buildCreationDate") }) public class Build implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected BuildPK buildsPK; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "BUILD_NAME") private String buildName; @Basic(optional = false) @NotNull @Column(name = "BUILD_CREATION_DATE") @Temporal(TemporalType.TIMESTAMP) private Date buildCreationDate; @OneToMany(cascade = CascadeType.ALL, mappedBy = "build") private List<Classroom> classrooms; @JoinColumn(name = "CAMPUS_ID", referencedColumnName = "CAMPUS_ID", insertable = false, updatable = false) @ManyToOne(optional = false, cascade = CascadeType.ALL) private Campus campus; public Build() { } public Build(BuildPK buildsPK) { this.buildsPK = buildsPK; } public Build(BuildPK buildsPK, String buildName, Date buildCreationDate) { this.buildsPK = buildsPK; this.buildName = buildName; this.buildCreationDate = buildCreationDate; } public Build(int buildId, int campusId) { this.buildsPK = new BuildPK(buildId, campusId); } public BuildPK getBuildsPK() { return buildsPK; } public void setBuildsPK(BuildPK buildsPK) { this.buildsPK = buildsPK; } public String getBuildName() { return buildName; } public void setBuildName(String buildName) { this.buildName = buildName; } public Date getBuildCreationDate() { return buildCreationDate; } public void setBuildCreationDate(Date buildCreationDate) { this.buildCreationDate = buildCreationDate; } @XmlTransient public List<Classroom> getClassrooms() { return classrooms; } public void setClassrooms(List<Classroom> classrooms) { this.classrooms = classrooms; } public Campus getCampus() { return campus; } public void setCampus(Campus campus) { this.campus = campus; } @Override public int hashCode() { int hash = 0; hash += (buildsPK != null ? buildsPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Build)) { return false; } Build other = (Build) object; if ((this.buildsPK == null && other.buildsPK != null) || (this.buildsPK != null && !this.buildsPK.equals(other.buildsPK))) { return false; } return true; } @Override public String toString() { return "Build{" + "buildsPK=" + buildsPK + ", buildName=" + buildName + ", buildCreationDate=" + buildCreationDate + '}'; } }
4,553
0.663738
0.662201
172
25.476744
27.561443
137
false
false
0
0
0
0
0
0
0.447674
false
false
2
558d6935810b78fd60d2a090b1cb1f0a1d2e6bc4
12,378,095,776,641
d392a08c59ce177acf48b2ec173a181de08dcc5c
/dynamic-web-project/web/src/test/java/kz/zhanbolat/web/UserValidatorTest.java
325df803e31fd480607331c27bc8df8f43303499
[]
no_license
Fousq/JWebProject
https://github.com/Fousq/JWebProject
e1c899900d5482c480993d6146c7229d390796bb
869edaa320d451570e8218c5c593e3c5bb960b87
refs/heads/master
2022-07-07T08:01:32.779000
2019-09-09T09:25:24
2019-09-09T09:25:24
197,719,486
0
0
null
false
2022-06-21T01:32:58
2019-07-19T06:58:57
2019-09-09T09:25:36
2022-06-21T01:32:57
37,022
0
0
5
Java
false
false
package kz.zhanbolat.web; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import kz.zhanbolat.web.domain.validator.UserValidator; public class UserValidatorTest { private static Logger logger = LogManager.getLogger(UserValidatorTest.class); @Test public void validePasswordShouldReturnTrue() { String password = "seeg412QWFS"; boolean valid = UserValidator.validatePassword(password); assertTrue(valid); } @Test public void validePasswordShouldReturnFalse() { String[] passwords = new String[] { "4135235414", "ferehrthgae", "FSEEVNONG", "1231fgsegf", "fgrgrgGSGSG", "3124GGGHG", "1wE" }; Stream.of(passwords).forEach(password -> assertFalse(UserValidator.validatePassword(password))); } @Test public void validateTelephoneNumberShouldReturnTrue() { String telephoneNumber = "123-123-12-12"; assertTrue(UserValidator.validateTelephoneNumber(telephoneNumber)); } @Test public void validateTelephoneNumberShouldReturnFalse() { String[] telephoneNumbers = new String[] { "702", "123-", "13", "123-1", "123-12", "1", "123-123", "123-123-1", "123-123-", "123-123-12", "123-123-123", "123-123-12-", "123-123-12-1", "123-123-12-123" }; Stream.of(telephoneNumbers).forEach(telephoneNumber -> assertFalse(UserValidator.validateTelephoneNumber(telephoneNumber))); } }
UTF-8
Java
1,516
java
UserValidatorTest.java
Java
[ { "context": "PasswordShouldReturnTrue() {\n\t\tString password = \"seeg412QWFS\";\n\t\tboolean valid = UserValidator.validatePasswor", "end": 514, "score": 0.9987568855285645, "start": 503, "tag": "PASSWORD", "value": "seeg412QWFS" }, { "context": "se() {\n\t\tString[] passwords = n...
null
[]
package kz.zhanbolat.web; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import kz.zhanbolat.web.domain.validator.UserValidator; public class UserValidatorTest { private static Logger logger = LogManager.getLogger(UserValidatorTest.class); @Test public void validePasswordShouldReturnTrue() { String password = "<PASSWORD>"; boolean valid = UserValidator.validatePassword(password); assertTrue(valid); } @Test public void validePasswordShouldReturnFalse() { String[] passwords = new String[] { "<PASSWORD>", "<PASSWORD>", "<PASSWORD>", "<PASSWORD>", "<PASSWORD>", "<PASSWORD>", "1wE" }; Stream.of(passwords).forEach(password -> assertFalse(UserValidator.validatePassword(password))); } @Test public void validateTelephoneNumberShouldReturnTrue() { String telephoneNumber = "123-123-12-12"; assertTrue(UserValidator.validateTelephoneNumber(telephoneNumber)); } @Test public void validateTelephoneNumberShouldReturnFalse() { String[] telephoneNumbers = new String[] { "702", "123-", "13", "123-1", "123-12", "1", "123-123", "123-123-1", "123-123-", "123-123-12", "123-123-123", "123-123-12-", "123-123-12-1", "123-123-12-123" }; Stream.of(telephoneNumbers).forEach(telephoneNumber -> assertFalse(UserValidator.validateTelephoneNumber(telephoneNumber))); } }
1,515
0.735488
0.658971
52
28.153847
24.363737
78
false
false
0
0
0
0
0
0
2.019231
false
false
2
c5e5226941e3f0febef77b6a6031ab3100d6ebf4
12,378,095,778,748
900246785d87eae381da6e76689cd3da24a8c749
/src/main/java/com/example/hookah/controller/mapper/ReservationMapper.java
ace973caeeb8139c58ab549d06f8432f450a986d
[]
no_license
IamCyrek/hookah
https://github.com/IamCyrek/hookah
df995e5e2c290cc23bad9ce6279efafe6734c922
0e95f17c9bd04a24d47455d47d3846c98291860b
refs/heads/master
2022-11-05T23:24:19.453000
2020-06-23T23:32:50
2020-06-23T23:32:50
262,810,837
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hookah.controller.mapper; import com.example.hookah.controller.dto.ReservationDTO; import com.example.hookah.model.Reservation; import org.mapstruct.InjectionStrategy; import org.mapstruct.Mapper; import java.util.List; @Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR, uses = { RestaurantMapper.class, UserMapper.class }) public interface ReservationMapper { ReservationDTO reservationToReservationDTO(Reservation reservation); List<ReservationDTO> reservationsToReservationDTOs(List<Reservation> reservations); Reservation reservationDTOToReservation(ReservationDTO reservationDTO); List<Reservation> reservationDTOsToReservations(List<ReservationDTO> reservationDTOs); }
UTF-8
Java
761
java
ReservationMapper.java
Java
[]
null
[]
package com.example.hookah.controller.mapper; import com.example.hookah.controller.dto.ReservationDTO; import com.example.hookah.model.Reservation; import org.mapstruct.InjectionStrategy; import org.mapstruct.Mapper; import java.util.List; @Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR, uses = { RestaurantMapper.class, UserMapper.class }) public interface ReservationMapper { ReservationDTO reservationToReservationDTO(Reservation reservation); List<ReservationDTO> reservationsToReservationDTOs(List<Reservation> reservations); Reservation reservationDTOToReservation(ReservationDTO reservationDTO); List<Reservation> reservationDTOsToReservations(List<ReservationDTO> reservationDTOs); }
761
0.822602
0.822602
21
35.238094
35.34713
118
false
false
0
0
0
0
0
0
0.619048
false
false
2
a84859c2a5cde53e877fc3615b1be7258eebb246
15,960,098,498,335
9c9f7432cc7fc23357be6267b3a5fa43e34ac3e9
/semi_sisNbro/src/common/controller/FrontController.java
9c9ceb57684eac0fda0b70705e65b58320a349bf
[]
no_license
HanGyuLee/Eclipse-test
https://github.com/HanGyuLee/Eclipse-test
4e0341b993b2f1107ceaf9d7d51ba4e7c582b25c
16fabfb44e4a75b78ce149e1ed1a416218bab217
refs/heads/master
2021-07-21T01:18:09.838000
2017-10-30T10:28:55
2017-10-30T10:28:55
108,802,960
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package common.controller; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FrontController */ @WebServlet( urlPatterns = { "*.do" }, initParams = { @WebInitParam(name = "propertyConfig", value = "C:/semi_sisNbro/WebContent/WEB-INF/Command.properties") }) public class FrontController extends HttpServlet { private static final long serialVersionUID = 1L; HashMap<String, Object> cmdMap = new HashMap<String, Object>(); //어떤 객체이던 모든지 다 hashMap에 넣어준다. /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { /* 웹브라우저 주소차엥서 *.do를 하면 FrontController 서블릿이 받는데 맨처음에 자동적으로 실행되어지는 메소드가 init(ServletConfig config) 이다 그런데 이 메소드는 WAS(==웹컨테이너, 톰캣서버)가 구동되어진 후 딱 1번만 수행되어지고, 그 이후에는 수행되지 않는다. 그러므로 FrontController서블릿을 수행할때 딱 1번만 수행해야할 업무들은 이 메소드속에 기술해 주면 된다. */ //System.out.println("==>확인용 :FrontController서블릿의 init(ServletConfig config)메소드가 작동함."); String props = config.getInitParameter("propertyConfig"); /* 초기화 파라미터 데이터 값인 "C:/myjsp/MyMVC/WebContent/WEB-INF/Command.properties"을 가져와서 문자열 변수 props에 저장시켜둔 것이다. */ //System.out.println("==>확인용 : props변수에 저장된 값 => " + props); //결과 : ==>확인용 : props변수에 저장된 값 => C:/myjsp/MyMVC/WebContent/WEB-INF/Command.properties Properties pr = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(props); pr.load(fis); /* C:/myjsp/MyMVC/WebContent/WEB-INF/Command.properties 파일의 내용을 읽어다가 Properties클래스의 객체인 pr에 로드시킨다. 그러면 pr은 읽어온 파일(Command.properties)의 내용에서 = 을 기준으로 왼쪽은 키값으로 보고, 오른쪽은 value값으로 인식한다. */ //String str_class = pr.getProperty("/test1.do"); /* pr.getProperty("/test1.do");에서 /test1.do은 key값이다. pr.getProperty("/test1.do"); 의 리턴값은 Command.properties에 기술된 key값 /test1.do 에 해당하고 value값 test.controller.Test1Controller을 리턴해준다. */ // System.out.println("확인용 str_class에 저장된 값 " + str_class); //확인용 str_class에 저장된 값 test.controller.Test1Controller Enumeration<Object> en = pr.keys(); /* pr.keys(); 은 Command.properties 파일의 내용물에서 = 을 기준으로 왼쪽에 있는 모든 key값들만 읽어오는 것이다. */ while(en.hasMoreElements()){ String key_urlname = (String)en.nextElement();//다음에 element가 있으면 읽어준다. String str_classname = pr.getProperty(key_urlname); //System.out.println("==>확인용 : key_urlname=>" + key_urlname); /* ==>확인용 : key_urlname=>/test3.do ==>확인용 : key_urlname=>/test2.do ==>확인용 : key_urlname=>/test1.do */ //System.out.println("==>확인용 :str_classname=>" + str_classname); /* ==>확인용 :str_classname=>test.controller.Test3Controller ==>확인용 :str_classname=>test.controller.Test2Controller ==>확인용 :str_classname=>test.controller.Test1Controller */ if(str_classname != null){ str_classname=str_classname.trim();//공백제거후 다시 변수에 넣기 Class cls = Class.forName(str_classname);//class일뿐 객체는 아니다. Object obj = cls.newInstance(); //문자열을 읽어 class화 해서 그 class를 객체로 만들어준다. //어떤걸 받아야 할지 모르니까 Object로 받아온다.(모든것을 다 받아줌) cmdMap.put(key_urlname, obj); } }//end of while--- } catch (Exception e) { e.printStackTrace(); } }//init(ServletConfig config) /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestProcess(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestProcess(request, response); } /* doGet메소드와 doPost메소드에서 해야할 업무처리를 requestProcess(request, response); 이 메소드로 넘겨버린다. */ private void requestProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//doGet인지 doPost인지 모르니까 걍 다 받아주는 메소드 하나 만듬 String uri = request.getRequestURI(); //System.out.println("확인용 uri : "+uri); //확인용 uri : /MyMVC/test1.do /* request.getRequestURI(); 메소드는 웹브라우저 주소창에서 요청되어진 URI 값을 반환시켜주는 메소드이다. URI라 함은 URL이 http://ip주소:9090/URI 값인데 http://ip주소:9090을 제외한 나머지를 말한다. 그런데 나머지 중에 ?(GET방식)이전까지를 말한다. */ String ctxName = request.getContextPath(); //System.out.println("==>확인용 ctxName:"+ctxName); //==>확인용 ctxName:/MyMVC int beginIndex = ctxName.length(); String mapkey = uri.substring(beginIndex); //System.out.println("=>확인용 mapKey :"+mapkey); //=>확인용 mapKey :/test2.do AbstractController action = (AbstractController)cmdMap.get(mapkey); if(action == null){ System.out.println(mapkey+" URL 패턴에 매핑된 객체가 없습니다."); }else{ try { action.execute(request, response);//메소드 호출 boolean bool = action.isRedirect(); //private으로 설정되어있기때문에 접근불가능-> 우회로 public boolean의 값인 isRedirect로 //접근해서 forward인지 redirect인지 알아봄 String viewPage = action.getViewPage();//내가 보여줄(읽어와야할) view단 페이지 if(bool){ //sendRedirect방식으로 view단 페이지 이동 response.sendRedirect(viewPage);//페이지이동 }else{ //forward방식 view단 페이지 이동 RequestDispatcher dispatcher=request.getRequestDispatcher(viewPage);//setViewPage를 가져와서 넘겨준다. dispatcher.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }//requestProcess(HttpServletRequest request, HttpServletResponse response) }
UHC
Java
7,708
java
FrontController.java
Java
[]
null
[]
package common.controller; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FrontController */ @WebServlet( urlPatterns = { "*.do" }, initParams = { @WebInitParam(name = "propertyConfig", value = "C:/semi_sisNbro/WebContent/WEB-INF/Command.properties") }) public class FrontController extends HttpServlet { private static final long serialVersionUID = 1L; HashMap<String, Object> cmdMap = new HashMap<String, Object>(); //어떤 객체이던 모든지 다 hashMap에 넣어준다. /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { /* 웹브라우저 주소차엥서 *.do를 하면 FrontController 서블릿이 받는데 맨처음에 자동적으로 실행되어지는 메소드가 init(ServletConfig config) 이다 그런데 이 메소드는 WAS(==웹컨테이너, 톰캣서버)가 구동되어진 후 딱 1번만 수행되어지고, 그 이후에는 수행되지 않는다. 그러므로 FrontController서블릿을 수행할때 딱 1번만 수행해야할 업무들은 이 메소드속에 기술해 주면 된다. */ //System.out.println("==>확인용 :FrontController서블릿의 init(ServletConfig config)메소드가 작동함."); String props = config.getInitParameter("propertyConfig"); /* 초기화 파라미터 데이터 값인 "C:/myjsp/MyMVC/WebContent/WEB-INF/Command.properties"을 가져와서 문자열 변수 props에 저장시켜둔 것이다. */ //System.out.println("==>확인용 : props변수에 저장된 값 => " + props); //결과 : ==>확인용 : props변수에 저장된 값 => C:/myjsp/MyMVC/WebContent/WEB-INF/Command.properties Properties pr = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(props); pr.load(fis); /* C:/myjsp/MyMVC/WebContent/WEB-INF/Command.properties 파일의 내용을 읽어다가 Properties클래스의 객체인 pr에 로드시킨다. 그러면 pr은 읽어온 파일(Command.properties)의 내용에서 = 을 기준으로 왼쪽은 키값으로 보고, 오른쪽은 value값으로 인식한다. */ //String str_class = pr.getProperty("/test1.do"); /* pr.getProperty("/test1.do");에서 /test1.do은 key값이다. pr.getProperty("/test1.do"); 의 리턴값은 Command.properties에 기술된 key값 /test1.do 에 해당하고 value값 test.controller.Test1Controller을 리턴해준다. */ // System.out.println("확인용 str_class에 저장된 값 " + str_class); //확인용 str_class에 저장된 값 test.controller.Test1Controller Enumeration<Object> en = pr.keys(); /* pr.keys(); 은 Command.properties 파일의 내용물에서 = 을 기준으로 왼쪽에 있는 모든 key값들만 읽어오는 것이다. */ while(en.hasMoreElements()){ String key_urlname = (String)en.nextElement();//다음에 element가 있으면 읽어준다. String str_classname = pr.getProperty(key_urlname); //System.out.println("==>확인용 : key_urlname=>" + key_urlname); /* ==>확인용 : key_urlname=>/test3.do ==>확인용 : key_urlname=>/test2.do ==>확인용 : key_urlname=>/test1.do */ //System.out.println("==>확인용 :str_classname=>" + str_classname); /* ==>확인용 :str_classname=>test.controller.Test3Controller ==>확인용 :str_classname=>test.controller.Test2Controller ==>확인용 :str_classname=>test.controller.Test1Controller */ if(str_classname != null){ str_classname=str_classname.trim();//공백제거후 다시 변수에 넣기 Class cls = Class.forName(str_classname);//class일뿐 객체는 아니다. Object obj = cls.newInstance(); //문자열을 읽어 class화 해서 그 class를 객체로 만들어준다. //어떤걸 받아야 할지 모르니까 Object로 받아온다.(모든것을 다 받아줌) cmdMap.put(key_urlname, obj); } }//end of while--- } catch (Exception e) { e.printStackTrace(); } }//init(ServletConfig config) /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestProcess(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestProcess(request, response); } /* doGet메소드와 doPost메소드에서 해야할 업무처리를 requestProcess(request, response); 이 메소드로 넘겨버린다. */ private void requestProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//doGet인지 doPost인지 모르니까 걍 다 받아주는 메소드 하나 만듬 String uri = request.getRequestURI(); //System.out.println("확인용 uri : "+uri); //확인용 uri : /MyMVC/test1.do /* request.getRequestURI(); 메소드는 웹브라우저 주소창에서 요청되어진 URI 값을 반환시켜주는 메소드이다. URI라 함은 URL이 http://ip주소:9090/URI 값인데 http://ip주소:9090을 제외한 나머지를 말한다. 그런데 나머지 중에 ?(GET방식)이전까지를 말한다. */ String ctxName = request.getContextPath(); //System.out.println("==>확인용 ctxName:"+ctxName); //==>확인용 ctxName:/MyMVC int beginIndex = ctxName.length(); String mapkey = uri.substring(beginIndex); //System.out.println("=>확인용 mapKey :"+mapkey); //=>확인용 mapKey :/test2.do AbstractController action = (AbstractController)cmdMap.get(mapkey); if(action == null){ System.out.println(mapkey+" URL 패턴에 매핑된 객체가 없습니다."); }else{ try { action.execute(request, response);//메소드 호출 boolean bool = action.isRedirect(); //private으로 설정되어있기때문에 접근불가능-> 우회로 public boolean의 값인 isRedirect로 //접근해서 forward인지 redirect인지 알아봄 String viewPage = action.getViewPage();//내가 보여줄(읽어와야할) view단 페이지 if(bool){ //sendRedirect방식으로 view단 페이지 이동 response.sendRedirect(viewPage);//페이지이동 }else{ //forward방식 view단 페이지 이동 RequestDispatcher dispatcher=request.getRequestDispatcher(viewPage);//setViewPage를 가져와서 넘겨준다. dispatcher.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }//requestProcess(HttpServletRequest request, HttpServletResponse response) }
7,708
0.660214
0.656122
198
30.09091
25.713295
107
false
false
0
0
0
0
0
0
2.671717
false
false
2
b8a40636d6820cea5fb2d5dff5ea2b4372592b37
17,042,430,262,275
8238831efe073654e856a3ce51a299dd164be11a
/src/java/dao/RatingDao.java
fde5745888596f84f472b04b1d66f0a6302e4b6c
[]
no_license
ambikasinghh/Solar-Mate_ver_1
https://github.com/ambikasinghh/Solar-Mate_ver_1
0b6fb25ddc2a6d8c468d0792ef103d089e424048
dbba1f4af756a0976ecbcc15bdff485763b037c2
refs/heads/main
2023-04-09T21:23:12.551000
2021-04-15T17:26:10
2021-04-15T17:26:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import java.util.*; import java.sql.*; import myconn.GetConnection; import dto.Rating; public class RatingDao { public int addRating(Rating obj, int rate) throws SQLException { int i=0; Connection con = GetConnection.getConnect(); String query = "select rating,no_of_rating from rating where company_name=?"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, obj.getCompany_name()); ResultSet rs = ps.executeQuery(); int r = rs.getInt(1); int nor = (rs.getInt(2))+1; rate=(rate+r)/nor; String query1 ="update rating set rating =?,no_of_rating=? where company_name=?"; PreparedStatement ps1 = con.prepareStatement(query1); ps1.setInt(1, rate); ps1.setInt(2, nor); ps1.setString(3, obj.getCompany_name()); i= ps.executeUpdate(); con.close(); return i; } }
UTF-8
Java
965
java
RatingDao.java
Java
[]
null
[]
package dao; import java.util.*; import java.sql.*; import myconn.GetConnection; import dto.Rating; public class RatingDao { public int addRating(Rating obj, int rate) throws SQLException { int i=0; Connection con = GetConnection.getConnect(); String query = "select rating,no_of_rating from rating where company_name=?"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, obj.getCompany_name()); ResultSet rs = ps.executeQuery(); int r = rs.getInt(1); int nor = (rs.getInt(2))+1; rate=(rate+r)/nor; String query1 ="update rating set rating =?,no_of_rating=? where company_name=?"; PreparedStatement ps1 = con.prepareStatement(query1); ps1.setInt(1, rate); ps1.setInt(2, nor); ps1.setString(3, obj.getCompany_name()); i= ps.executeUpdate(); con.close(); return i; } }
965
0.6
0.585492
27
33.740742
22.63657
89
false
false
0
0
0
0
0
0
1.074074
false
false
2
1476b9ed159a8451cd4be19b33bd2b4432d3132d
2,997,887,206,347
e9b030bafed6b319eed22d39acbe9e6f8aa8293e
/app/src/main/java/com/rudolphriding/giftfriend/app/home/RvHolder.java
a0002daa8c0fbbb07ff56005921d9452c14e324b
[]
no_license
nagihiko0704/GiftFriend
https://github.com/nagihiko0704/GiftFriend
44eeb52112b64b236ac1ee9cbcae4540cc755c0a
f3bf2196025823894d80476fbeae739c33cfa009
refs/heads/master
2021-01-19T15:24:43.023000
2017-12-18T07:16:00
2017-12-18T07:16:00
100,967,258
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rudolphriding.giftfriend.app.home; import android.support.constraint.ConstraintLayout; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.rudolphriding.giftfriend.R; /** * Created by 이지혜 on 2017-09-17. */ public class RvHolder extends RecyclerView.ViewHolder { ImageView image; TextView title; TextView subtitle; ConstraintLayout container; public RvHolder(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.cardview_image_title); title = (TextView) itemView.findViewById(R.id.cardview_text_title); subtitle = (TextView) itemView.findViewById(R.id.cardview_text_subtitle); container = (ConstraintLayout) itemView.findViewById(R.id.container); } }
UTF-8
Java
868
java
RvHolder.java
Java
[ { "context": "com.rudolphriding.giftfriend.R;\n\n/**\n * Created by 이지혜 on 2017-09-17.\n */\npublic class RvHolder extend", "end": 298, "score": 0.6426840424537659, "start": 297, "tag": "USERNAME", "value": "이" }, { "context": "m.rudolphriding.giftfriend.R;\n\n/**\n * Created by 이지혜 ...
null
[]
package com.rudolphriding.giftfriend.app.home; import android.support.constraint.ConstraintLayout; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.rudolphriding.giftfriend.R; /** * Created by 이지혜 on 2017-09-17. */ public class RvHolder extends RecyclerView.ViewHolder { ImageView image; TextView title; TextView subtitle; ConstraintLayout container; public RvHolder(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.cardview_image_title); title = (TextView) itemView.findViewById(R.id.cardview_text_title); subtitle = (TextView) itemView.findViewById(R.id.cardview_text_subtitle); container = (ConstraintLayout) itemView.findViewById(R.id.container); } }
868
0.737819
0.727378
30
27.733334
25.624121
81
false
false
0
0
0
0
0
0
0.533333
false
false
2
3ebb5af0dc74e659fcf49e684ecf951842b6693d
25,537,875,592,611
7e671d3247c3aa1b405e7b93985f31c9e3be45f8
/src/Poligon_Lambda/Concatenare.java
9c06345d9b4896704fb69d5580a1dd6c25cebf8c
[]
no_license
DanielaCiocoiu/Probe
https://github.com/DanielaCiocoiu/Probe
fa24d2e082cce1f70fed3c18424ad4f65c1f7bb2
4d5ce9a7f87adf39cf88d2e6230253f9438e3461
refs/heads/master
2023-06-22T05:46:45.678000
2021-07-21T11:12:45
2021-07-21T11:12:45
387,151,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Ex3Poligon_Lambda; /* Sa se creeze urmatoarele interfete functionale, care vor fi utilizate in metoda main cu ajutorul expresiilor lambda. Concatenare cu metoda String concateneaza(String s1, String s2); AfisareString cu metoda void afiseazaDeNOri(String s, int n); Inmultire cu metoda int inmultire(int[] array);*/ @FunctionalInterface public interface Concatenare { public String concateneaza(String s1, String s2); }
UTF-8
Java
463
java
Concatenare.java
Java
[]
null
[]
package Ex3Poligon_Lambda; /* Sa se creeze urmatoarele interfete functionale, care vor fi utilizate in metoda main cu ajutorul expresiilor lambda. Concatenare cu metoda String concateneaza(String s1, String s2); AfisareString cu metoda void afiseazaDeNOri(String s, int n); Inmultire cu metoda int inmultire(int[] array);*/ @FunctionalInterface public interface Concatenare { public String concateneaza(String s1, String s2); }
463
0.7473
0.736501
13
34.615383
36.122738
119
false
false
0
0
0
0
0
0
0.692308
false
false
2
3df36a677fa61f848d3e402a1b05c47ea331a03b
38,250,978,757,854
a43d76bcf8adace16c3ac29b996c7c488a5cd930
/src/Test1.java
879dfced9df39f937236ebab055ca1eb04b8e44c
[]
no_license
JyothiCyril/DevlabsSDETBatch1
https://github.com/JyothiCyril/DevlabsSDETBatch1
29ee85dea4c55f9bd02bb868a23395ac00a12421
52e915920d190e8cbedb91547d3a27d293e899a2
refs/heads/master
2023-03-19T02:35:46.919000
2021-02-13T10:07:28
2021-02-13T10:07:28
338,537,090
0
0
null
false
2021-02-13T10:07:28
2021-02-13T09:15:05
2021-02-13T10:07:18
2021-02-13T10:07:28
0
0
0
0
Java
false
false
public class Test1 extends TestBase { public static void main(String[] args) { System.out.println("I am Test case 1 class"); } }
UTF-8
Java
145
java
Test1.java
Java
[]
null
[]
public class Test1 extends TestBase { public static void main(String[] args) { System.out.println("I am Test case 1 class"); } }
145
0.648276
0.634483
10
13.4
18.650469
47
false
false
0
0
0
0
0
0
1.1
false
false
2
ce2f4c394d0d20717e5a1cac461c49d5fb22724b
38,250,978,760,598
8f49f272547ece17b67b1b81eb32d6c26d6425f4
/src/test/java/com/countme/up/service/CandidateServiceTest.java
a93f0e68c520c77382e8a04143e8650deb587259
[]
no_license
ahamouda88/countme-up
https://github.com/ahamouda88/countme-up
9407013fee40703141d8ae386522ea0882039104
c26a0d5bb5d2ed958c29fef9e53544abd24ea23b
refs/heads/master
2021-01-20T18:02:35.310000
2017-05-15T14:14:05
2017-05-15T14:14:05
90,897,577
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.countme.up.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.junit4.SpringRunner; import com.countme.up.model.entity.Candidate; import com.countme.up.spring.config.ApplicationTestConfig; @RunWith(SpringRunner.class) @DataJpaTest @SpringBootTest(classes = { ApplicationTestConfig.class }) @ComponentScan(basePackages = { "com.countme.up.dao", "com.countme.up.service" }) public class CandidateServiceTest { @Autowired private CandidateService candidateService; private long candidateId1; private long candidateId2; @Before public void testAdd() { Candidate candidate1 = new Candidate("Lionel", "Messi", "leo@hotmail.com", null); assertTrue("Failed to add first candidate!", candidateService.add(candidate1)); candidateId1 = candidate1.getId(); Candidate candidate2 = new Candidate("Andres", "Iniesta", "andres@gmail.com", null); assertTrue("Failed to add second candidate!", candidateService.add(candidate2)); candidateId2 = candidate2.getId(); } @Test public void testGetAll() { assertEquals("Invalid number of candidates!", 2, candidateService.getAll().size()); } @Test public void testGet() { Candidate candidate = candidateService.get(candidateId1); assertNotNull("Candidate object shouldn't be null!", candidate); assertEquals("Candidate firstname is incorrect!", "Lionel", candidate.getFirstname()); } @Test public void testUpdate() { String newEmail = "omaribrahim@gmail.com"; Candidate candidate = candidateService.get(candidateId2); candidate.setEmail(newEmail); assertTrue("Failed to update candidate!", candidateService.update(candidate)); assertEquals("Candidate's email isn't updated!", newEmail, candidateService.get(candidateId2).getEmail()); } @Test public void testDelete() { Candidate candidate = candidateService.delete(candidateService.get(candidateId2)); assertNotNull("Failed to delete candidate!", candidate); assertEquals("Deleted candidate is incorrect!", "Andres", candidate.getFirstname()); assertEquals("Invalid number of candidates, after deleting one candidate!", 1, candidateService.getAll().size()); } @Test public void testDeleteByKey() { Candidate candidate = candidateService.deleteByKey(candidateId1); assertNotNull("Failed to delete candidate!", candidate); assertEquals("Deleted candidate is incorrect!", "Messi", candidate.getLastname()); assertEquals("Invalid number of candidates, after deleting one candidate!", 1, candidateService.getAll().size()); } @Test(expected = NullPointerException.class) public void testInvalidAdd() { candidateService.add(null); } @Test public void testInvalidDelete() { assertNull("Delete method should return null when given invalid parameter!", candidateService.delete(null)); } @Test(expected = NullPointerException.class) public void testInvalidUpdate() { candidateService.update(null); } @Test(expected = NullPointerException.class) public void testInvalidGet() { candidateService.get(null); } @Test public void testInvalidGetKey() { assertNull("Get method should return null when given invalid Id parameter!", candidateService.get(1000L)); } }
UTF-8
Java
3,671
java
CandidateServiceTest.java
Java
[ { "context": "stAdd() {\n\t\tCandidate candidate1 = new Candidate(\"Lionel\", \"Messi\", \"leo@hotmail.com\", null);\n\t\tassertTrue", "end": 1131, "score": 0.999786376953125, "start": 1125, "tag": "NAME", "value": "Lionel" }, { "context": "\t\tCandidate candidate1 = new Candidate(\"...
null
[]
package com.countme.up.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.junit4.SpringRunner; import com.countme.up.model.entity.Candidate; import com.countme.up.spring.config.ApplicationTestConfig; @RunWith(SpringRunner.class) @DataJpaTest @SpringBootTest(classes = { ApplicationTestConfig.class }) @ComponentScan(basePackages = { "com.countme.up.dao", "com.countme.up.service" }) public class CandidateServiceTest { @Autowired private CandidateService candidateService; private long candidateId1; private long candidateId2; @Before public void testAdd() { Candidate candidate1 = new Candidate("Lionel", "Messi", "<EMAIL>", null); assertTrue("Failed to add first candidate!", candidateService.add(candidate1)); candidateId1 = candidate1.getId(); Candidate candidate2 = new Candidate("Andres", "Iniesta", "<EMAIL>", null); assertTrue("Failed to add second candidate!", candidateService.add(candidate2)); candidateId2 = candidate2.getId(); } @Test public void testGetAll() { assertEquals("Invalid number of candidates!", 2, candidateService.getAll().size()); } @Test public void testGet() { Candidate candidate = candidateService.get(candidateId1); assertNotNull("Candidate object shouldn't be null!", candidate); assertEquals("Candidate firstname is incorrect!", "Lionel", candidate.getFirstname()); } @Test public void testUpdate() { String newEmail = "<EMAIL>"; Candidate candidate = candidateService.get(candidateId2); candidate.setEmail(newEmail); assertTrue("Failed to update candidate!", candidateService.update(candidate)); assertEquals("Candidate's email isn't updated!", newEmail, candidateService.get(candidateId2).getEmail()); } @Test public void testDelete() { Candidate candidate = candidateService.delete(candidateService.get(candidateId2)); assertNotNull("Failed to delete candidate!", candidate); assertEquals("Deleted candidate is incorrect!", "Andres", candidate.getFirstname()); assertEquals("Invalid number of candidates, after deleting one candidate!", 1, candidateService.getAll().size()); } @Test public void testDeleteByKey() { Candidate candidate = candidateService.deleteByKey(candidateId1); assertNotNull("Failed to delete candidate!", candidate); assertEquals("Deleted candidate is incorrect!", "Messi", candidate.getLastname()); assertEquals("Invalid number of candidates, after deleting one candidate!", 1, candidateService.getAll().size()); } @Test(expected = NullPointerException.class) public void testInvalidAdd() { candidateService.add(null); } @Test public void testInvalidDelete() { assertNull("Delete method should return null when given invalid parameter!", candidateService.delete(null)); } @Test(expected = NullPointerException.class) public void testInvalidUpdate() { candidateService.update(null); } @Test(expected = NullPointerException.class) public void testInvalidGet() { candidateService.get(null); } @Test public void testInvalidGetKey() { assertNull("Get method should return null when given invalid Id parameter!", candidateService.get(1000L)); } }
3,640
0.770907
0.764642
111
32.072071
30.86755
110
false
false
0
0
0
0
0
0
1.603604
false
false
2
e99c1e76eb9e6bd11d76995de6307f0ecace4c5f
39,496,519,271,503
1c09b362c449164a86cdd1e44197ebacd2039539
/CarRentOrderFinal/java/home/service/HistoryService.java
50f6bbbb672c28452e70fb153f1f71c799e4f923
[]
no_license
MakcumLviv/CarFinal
https://github.com/MakcumLviv/CarFinal
7ce8eeaf2e34ea6e023000256a3a2d0c80951b57
47dd7c30bec5ed54071f8190115619c227aaa359
refs/heads/master
2016-09-08T10:09:38.201000
2015-04-27T16:23:08
2015-04-27T16:23:08
34,677,642
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package home.service; import home.model.History; public interface HistoryService { }
UTF-8
Java
93
java
HistoryService.java
Java
[]
null
[]
package home.service; import home.model.History; public interface HistoryService { }
93
0.741935
0.741935
11
7.454545
12.048113
33
false
false
0
0
0
0
0
0
0.272727
false
false
2
604c19dd75b44934cabde1c749cc453ac730f544
37,426,345,046,590
0b01d6e4d55d7aaf1fc984fb1044ea142c900009
/app/src/main/java/com/t3h/appdemo/fragment/SavedFragment.java
e506671add0b25d2bd2834c6d8449f50732e0ce9
[]
no_license
21nghin/AppDemo
https://github.com/21nghin/AppDemo
8cbec41ed22c70714fe4a4f739c1a09b48cc443d
cfe32b8a61fcf35bb4c61f5382f509a4adce2f7d
refs/heads/master
2020-07-25T05:52:16.799000
2019-11-29T14:47:03
2019-11-29T14:47:03
208,187,163
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.t3h.appdemo.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.t3h.appdemo.R; import com.t3h.appdemo.adapter.SavedAdapter; import com.t3h.appdemo.model.Saved; import java.util.ArrayList; public class SavedFragment extends Fragment { private RecyclerView rcvSave; private SavedAdapter adapter; private ArrayList<Saved> data; private DatabaseReference databaseReference; private ValueEventListener mDBListener; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.saved_fragment,container,false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); initData(); } private void initData() { databaseReference = FirebaseDatabase.getInstance().getReference("Saved"); mDBListener = databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { data.clear(); for (DataSnapshot pull : dataSnapshot.getChildren()) { Saved save = pull.getValue(Saved.class); save.setpId(pull.getKey()); data.add(save); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } //kiểm tra đã lưu chưa //phải viết trong popupmenu để khi ấn vào save nó thông báo ra private void checkSave(){ databaseReference = FirebaseDatabase.getInstance().getReference("Saves"); } private void initView() { rcvSave = getActivity().findViewById(R.id.rcv_save); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); layoutManager.setStackFromEnd(true); layoutManager.setReverseLayout(true); rcvSave.setLayoutManager(layoutManager); data = new ArrayList<>(); adapter = new SavedAdapter(data,getContext()); rcvSave.setAdapter(adapter); } @Override public void onDestroy() { super.onDestroy(); databaseReference.removeEventListener(mDBListener); } }
UTF-8
Java
3,185
java
SavedFragment.java
Java
[]
null
[]
package com.t3h.appdemo.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.t3h.appdemo.R; import com.t3h.appdemo.adapter.SavedAdapter; import com.t3h.appdemo.model.Saved; import java.util.ArrayList; public class SavedFragment extends Fragment { private RecyclerView rcvSave; private SavedAdapter adapter; private ArrayList<Saved> data; private DatabaseReference databaseReference; private ValueEventListener mDBListener; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.saved_fragment,container,false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); initData(); } private void initData() { databaseReference = FirebaseDatabase.getInstance().getReference("Saved"); mDBListener = databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { data.clear(); for (DataSnapshot pull : dataSnapshot.getChildren()) { Saved save = pull.getValue(Saved.class); save.setpId(pull.getKey()); data.add(save); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } //kiểm tra đã lưu chưa //phải viết trong popupmenu để khi ấn vào save nó thông báo ra private void checkSave(){ databaseReference = FirebaseDatabase.getInstance().getReference("Saves"); } private void initView() { rcvSave = getActivity().findViewById(R.id.rcv_save); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); layoutManager.setStackFromEnd(true); layoutManager.setReverseLayout(true); rcvSave.setLayoutManager(layoutManager); data = new ArrayList<>(); adapter = new SavedAdapter(data,getContext()); rcvSave.setAdapter(adapter); } @Override public void onDestroy() { super.onDestroy(); databaseReference.removeEventListener(mDBListener); } }
3,185
0.695831
0.694567
95
32.326317
27.052168
132
false
false
0
0
0
0
0
0
0.589474
false
false
2
2a91ab6f6e179435b41d5036eb59253a0cba9f73
37,426,345,045,578
a9335d0a500ecfca196788f804425e6c01b1e45a
/app/src/main/java/com/example/omarelaimy/iseeyou/EditSlot.java
b7b13c44ba8c73b892aab66d5ed0f2469b495dd8
[]
no_license
omarelaimy/ISeeYou
https://github.com/omarelaimy/ISeeYou
6712b33164dcf703628a4a00e974db734f57c3c8
3f236999dae9d310cb4c1c15f0202721544afd63
refs/heads/master
2021-08-29T17:41:44.484000
2017-07-20T10:50:08
2017-07-20T10:50:08
84,760,843
0
1
null
false
2017-12-14T14:04:41
2017-03-12T22:05:31
2017-08-10T13:15:36
2017-12-14T14:04:27
2,787
0
1
0
Java
false
null
package com.example.omarelaimy.iseeyou; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import java.lang.reflect.Field; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import android.app.ProgressDialog; import android.util.Log; import android.widget.TimePicker; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Omar on 3/15/2017. */ public class EditSlot extends AppCompatActivity { private static final String TAG = "EditSlotActivity"; private static final String URL_FOR_EditSlot="https://icu.000webhostapp.com/editslot.php"; private static final String URL_FOR_GetSlot ="https://icu.000webhostapp.com/getslot.php"; private String PatientID; private String SlotDay,SlotDayTime,ProductID; private int insertPillType; //ArrayLists private ArrayList<Pill> currentPills = new ArrayList<>(); private List<Integer> currentpillstoremove = new ArrayList<>(); private ArrayList<LinearLayout> Separators = new ArrayList<>(); private ProgressDialog progress; //Views for the tool bar private TextView tv_ProductID,tv_SlotName; private ImageButton closeBtn; //Views for the mainlayout private TextView tv_emptyslot; private Button btn_edit; private ImageButton btn_add; private Button setFromTime,setToTime; private LinearLayout mainLayout; //Check Variables private boolean SetFromTimeClicked = false; private boolean SetToTimeClicked = false; private int editclicked = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_slot); //Get the toolbar Views tv_ProductID = (TextView) findViewById(R.id.slot_productid); tv_SlotName = (TextView) findViewById(R.id.slot_slotname); closeBtn = (ImageButton) findViewById(R.id.slot_cancel_button); btn_edit = (Button) findViewById(R.id.slot_edit_button); //Get Views for setting the time setFromTime = (Button) findViewById(R.id.from_time); setToTime = (Button) findViewById(R.id.to_time); //Get Views for the main layout mainLayout = (LinearLayout) findViewById(R.id.mainvew_editslot); tv_emptyslot = (TextView) findViewById(R.id.empty_slot); btn_add = (ImageButton) findViewById(R.id.add_pill); //Get the strings from the intent. Bundle extras = getIntent().getExtras(); PatientID = extras.getString("patientid"); ProductID = extras.getString("productid"); SlotDay = extras.getString("SlotDay"); SlotDayTime = extras.getString("SlotDayTime"); progress = ProgressDialog.show(this, "Getting your pills", "Please wait...", true); //Call the function that retrieves the product's pills for this slot. GetSlotPills(); //Click listener on the edit in the toolbar EditToolBarClickListener(btn_edit); //Click listener on the plus at the end of the page. AddPillListener(btn_add); //Set the SlotName to the text from the intent. tv_SlotName.setText(SlotDay + " " + SlotDayTime); tv_ProductID.setText(ProductID); //Closing EditSlot Page closeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //Call the set time on both time dialogs. setTime(setFromTime,1); setTime(setToTime,2); } /*************Event Listeners*************/ //Event handler for pressing Add button in the edit_slot page public void AddPillListener(ImageView button) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Alert Dialogue to add new pill //User adds the name and the count AddPillMessage(); } }); } public void EditToolBarClickListener(Button edit) { edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editclicked++; ShowEditLabels(); } }); } public void EditPillListener(TextView tv, final int idx) { tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdatePillCountMessage(idx); } }); } public void DeletePillListener(ImageView iv,final int idx) { iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DeletePillMessage(idx); } }); } /***************Database Functions*****************/ //Function that retrieves the pills from the database for the given slot and the product. public void GetSlotPills() { // Tag used to cancel the request String cancel_req_tag = "getslotpills"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_GetSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { progress.dismiss(); Log.d(TAG, "Get Pills Slot Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { JSONArray result = jObj.getJSONArray(Config.JSON_ARRAY); //CREATE THE LINEAR LAYOUT FOR THE ARRAY RETURNED of Pills. String CurrPillname = ""; String CurrPillCount = ""; String CurrPillType = ""; String FromTime = ""; String ToTime = ""; JSONObject initialobj = result.getJSONObject(0); FromTime = initialobj.getString(Config.KEY_SlotFromtime); ToTime = initialobj.getString(Config.KEY_SlotTotime); //Loop on all pills and put them in currentpills array as well as the layout. for (int i = 0; i < result.length(); i++) { Pill currentpill = new Pill(); JSONObject PillData = result.getJSONObject(i); CurrPillname = PillData.getString(Config.KEY_Pillname); CurrPillType = PillData.getString(Config.KEY_PillType); CurrPillCount = PillData.getString(Config.KEY_PillCount); LinearLayout newpillayout = CreatePillLayout(CurrPillname, Integer.parseInt(CurrPillCount), Integer.parseInt(CurrPillType)); LinearLayout separator = CreateSeparator(); Separators.add(separator); currentpill.SetPillInfo(CurrPillname,Integer.parseInt(CurrPillType),Integer.parseInt(CurrPillCount), i, newpillayout); currentPills.add(currentpill); mainLayout.addView(newpillayout); mainLayout.addView(separator); tv_emptyslot.setVisibility(View.GONE); SetToTimeClicked = true; SetFromTimeClicked = true; setFromTime.setText(FromTime); setToTime.setText(ToTime); } //Currentpills array is ACCESSIBLE here. for (int i = 0; i < currentPills.size(); i++) { //Call the onclick listener for each close image for all the added pills. ImageView deleteimg = GetDeleteImage(i); DeletePillListener(deleteimg, i); TextView editpill = GetEditLabel(i); EditPillListener(editpill,i); } } else { Toast.makeText(getApplicationContext(), "Welcome to your new slot!", Toast.LENGTH_LONG).show(); //No pills returned, set the visibility of the text to visible to tell the user. tv_emptyslot.setVisibility(View.VISIBLE); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Get Pills slot Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("slotday", SlotDay); params.put("slotdaytime", SlotDayTime); params.put("patientid", PatientID); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Function that updates the time of the slot with no pills added. public void UpdateSlotTime() { // Tag used to cancel the request String cancel_req_tag = "updateslottime"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Update Slot Time Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { String error_msg = jObj.getString("error_msg"); //Update done Toast.makeText(getApplicationContext(), error_msg, Toast.LENGTH_LONG).show(); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); setFromTime.setText("Set From Time"); setToTime.setText("Set To Time"); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Update Slot Time Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("day", SlotDay); params.put("daytime", SlotDayTime); params.put("fromtime", setFromTime.getText().toString()); params.put("totime", setToTime.getText().toString()); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Function that updates the pill count of the selected pill. public void UpdatePillCount(final int idx, final int count) { final String PillName = currentPills.get(idx).GetPillName(); // Tag used to cancel the request String cancel_req_tag = "updatepillcount"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Update Pill count Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { currentPills.get(idx).SetCount(count); //Update done Toast.makeText(getApplicationContext(), "Pill " + PillName + " is updated successfully", Toast.LENGTH_LONG).show(); //View New count in the layout SetPillsLeftText(idx,count); SetPillIndicator(idx,count); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Update Pills slot Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("day", SlotDay); params.put("daytime", SlotDayTime); params.put("pillname", PillName); params.put("pillcount", String.valueOf(count)); params.put("patientid", PatientID); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Function that deletes the selected pill from the database. public void DeletePill(int idx) { final String PillName = currentPills.get(idx).GetPillName(); // Tag used to cancel the request String cancel_req_tag = "deleteslotpill"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Delete Pill Slot Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { Toast.makeText(getApplicationContext(), "Pill " + PillName + " is deleted successfully", Toast.LENGTH_LONG).show(); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Delete Pill slot Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("day", SlotDay); params.put("daytime", SlotDayTime); params.put("pillname", PillName); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Insert the Pill into the patient's inventory. public void InsertPill(final String insertPillName, final String insertPillCount) { // Tag used to cancel the request // Tag used to cancel the request String cancel_req_tag = "insertpills"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Insert Pill Slot Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); //Error is false, pill is inserted successfully. if (!error) { insertPillType = Integer.parseInt(jObj.getString("pilltype")); // insertPillType = Integer.parseInt(jObj.getJSONObject("result").getString("pilltype")); Pill newpill = new Pill(); int idx = currentPills.size(); //The index after adding the pill later LinearLayout newpillayout = CreatePillLayout(insertPillName,Integer.parseInt(insertPillCount),insertPillType); LinearLayout separator = CreateSeparator(); newpill.SetPillInfo(insertPillName,insertPillType,Integer.parseInt(insertPillCount),idx,newpillayout); currentPills.add(newpill); Separators.add(separator); mainLayout.addView(newpillayout); mainLayout.addView(separator); tv_emptyslot.setVisibility(View.GONE); ImageView newdeleteimage = GetDeleteImage(idx); TextView neweditpill = GetEditLabel(idx); if (editclicked % 2 != 0) { newdeleteimage.setVisibility(View.VISIBLE); neweditpill.setVisibility(View.VISIBLE); } String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); for (int i = 0; i<currentPills.size();i++) { ImageView deletepill = GetDeleteImage(i); TextView editpill = GetEditLabel(i); DeletePillListener(deletepill,i); EditPillListener(editpill,i); } } else { //Errors happened, show the error_message and you can mark the errored pills as red. String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Add Pill Inventory Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to register url Map<String, String> params = new HashMap<String, String>(); //Parameters for the patient params.put("productid",ProductID); params.put("patientid",PatientID); params.put("day",SlotDay); params.put("daytime",SlotDayTime); params.put("fromtime",setFromTime.getText().toString()); params.put("totime",setToTime.getText().toString()); params.put("pillname",insertPillName); params.put("pillcount",insertPillCount); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } /////////////////////////////Dialog Messages//////////////////////////////////////////////// //Update pill count message at pressing edit button public void UpdatePillCountMessage(final int idx) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Change Number of pills"); alertDialog.setMessage("Enter your new pills count"); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); input.setLayoutParams(lp); alertDialog.setView(input); alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String count = ""; count = input.getText().toString(); int intCount = Integer.parseInt(count); if (!count.equals("")) { if (count.equals(String.valueOf(0))) { Toast.makeText(getApplicationContext(), "You cannot update the slot pill with 0, remove it instead.", Toast.LENGTH_SHORT).show(); dialog.cancel(); } else if (intCount == currentPills.get(idx).GetPillCount()) { Toast.makeText(getApplicationContext(), "The number of the pills is the same as before.", Toast.LENGTH_SHORT).show(); dialog.cancel(); } else { //Valid new count(different than the displayed one). //Call the function to update the pillcount of the db. UpdatePillCount(idx, Integer.parseInt(count)); } } } }); alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } //Insert PillName and Count to add new pill to the slot public void AddPillMessage() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Add New Pill"); alertDialog.setMessage("Enter the new pill name and the number of pills you want to add."); LinearLayout layout = new LinearLayout(EditSlot.this); layout.setOrientation(LinearLayout.VERTICAL); final EditText et_pillname = new EditText(this); et_pillname.setInputType(InputType.TYPE_CLASS_TEXT); et_pillname.setHint("Pill Name"); final EditText et_pillcount = new EditText(this); et_pillcount.setInputType(InputType.TYPE_CLASS_NUMBER); et_pillcount.setHint("Number of Pills"); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp2.topMargin = 10; layout.setLayoutParams(lp1); et_pillname.setLayoutParams(lp2); et_pillcount.setLayoutParams(lp2); layout.addView(et_pillname); layout.addView(et_pillcount); alertDialog.setView(layout); alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String pillname = ""; String pillcount = ""; pillname = et_pillname.getText().toString(); pillcount = et_pillcount.getText().toString(); //Check if pillname is empty if (!pillname.equals("")) { if (!pillcount.equals("")) { if (pillcount.equals(String.valueOf(0))) { Toast.makeText(getApplicationContext(), "You cannot update the slot pill with 0, remove it instead.", Toast.LENGTH_SHORT).show(); dialog.cancel(); } else { //Valid new name and count //Check if time is set or not if (!SetFromTimeClicked && !SetToTimeClicked) Toast.makeText(getApplicationContext(),"Please set the From time and the To time of the slot.", Toast.LENGTH_LONG).show(); //Check if From Time is not set else if (!SetFromTimeClicked) Toast.makeText(getApplicationContext(),"Please set the From time of the slot.", Toast.LENGTH_LONG).show(); //Check if To Time is not set else if (!SetToTimeClicked) Toast.makeText(getApplicationContext(),"Please set the To time of the slot.", Toast.LENGTH_LONG).show(); else //Call the function to add the pill in the database InsertPill(pillname,pillcount); } } } } }); alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } //Slot Time Message. public void EditSlotTimeMessage() { new AlertDialog.Builder(this) .setTitle("Edit Slot Time") .setMessage("There are no new pills to be added. Do you want to edit the slot time only?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Call update query to update the current pills time. UpdateSlotTime(); } }).setNegativeButton("No", null).show(); } //Delete Pill Message. public void DeletePillMessage(final int idx) { new AlertDialog.Builder(this) .setTitle("Delete Pill") .setMessage("Are you sure you want to delete the pill completely from this slot?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Call function of database to delete from database. DeletePill(idx); //Remove from layout mainLayout.removeView(currentPills.get(idx).GetPillLayout()); mainLayout.removeView(Separators.get(idx)); currentpillstoremove.add(idx); if (currentPills.size() == currentpillstoremove.size()) tv_emptyslot.setVisibility(View.VISIBLE); } }).setNegativeButton("No", null).show(); } //////////////////////View Functions///////////////////////////////////////// public LinearLayout CreatePillLayout(String PillName, int PillCount, int PillType) { //main layout for each pill LinearLayout PillLayout = new LinearLayout(EditSlot.this); PillLayout.setOrientation(LinearLayout.HORIZONTAL); //Children of the pill layout2 LinearLayout pillIndicator = new LinearLayout(EditSlot.this); LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(46, 300); layoutParams1.setMargins(5, 10, 20, 10); //layoutParams1.weight = 1; pillIndicator.setLayoutParams(layoutParams1); pillIndicator.setBackgroundColor(getResources().getColor(R.color.colorAccent)); pillIndicator.setPadding(0, 0, 0, 0); //Layout for pill Description LinearLayout pillInfo = new LinearLayout(EditSlot.this); pillInfo.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.WRAP_CONTENT, android.app.ActionBar.LayoutParams.MATCH_PARENT); layoutParams2.setMargins(30, 10, 20, 10); layoutParams2.weight = 6; pillInfo.setLayoutParams(layoutParams2); //TextView for pillinfo TextView tv_pillname = new TextView(EditSlot.this); TextView tv_pillcount = new TextView(EditSlot.this); TextView edit_button = new TextView(EditSlot.this); //Setting the info for the pill name. tv_pillname.setText(PillName); tv_pillname.setTextColor(getResources().getColor(R.color.welcomescreen)); tv_pillname.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25); //Create a layout for the text of pills left along with edit button LinearLayout pilldescription = new LinearLayout(EditSlot.this); LinearLayout.LayoutParams pilldescription_params = new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.WRAP_CONTENT, android.app.ActionBar.LayoutParams.WRAP_CONTENT); pilldescription.setOrientation(LinearLayout.HORIZONTAL); pilldescription_params.setMargins(20, 0, 0, 70); pilldescription.setPadding(0, 0, 0, 0); pilldescription.setLayoutParams(pilldescription_params); //Text for viewing the pills left. if(PillCount == 1) tv_pillcount.setText(Integer.toString(PillCount) + " pill"); else tv_pillcount.setText(Integer.toString(PillCount) + " pills"); tv_pillcount.setTypeface(null, Typeface.ITALIC); tv_pillcount.setTextColor(getResources().getColor(R.color.greycolor)); tv_pillcount.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); //Button for edit. edit_button.setBackgroundColor(getResources().getColor(android.R.color.transparent)); edit_button.setText("edit"); edit_button.setAllCaps(false); edit_button.setPaintFlags(edit_button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); edit_button.setTextColor(getResources().getColor(R.color.welcomescreen)); edit_button.setTypeface(null, Typeface.ITALIC); edit_button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13); edit_button.setPadding(20, 0, 20, 0); edit_button.setVisibility(View.GONE); pilldescription.addView(tv_pillcount); pilldescription.addView(edit_button); pillInfo.addView(tv_pillname); pillInfo.addView(pilldescription); //ImageView for the icon ImageView iv_pilltype = CreatePillView(PillType); //Img for the X button LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams(25, 25); layoutParams4.weight = 1; layoutParams4.setMargins(20, 0, 0, 0); int src1 = R.drawable.x; ImageView deletebtn = new ImageView(EditSlot.this); deletebtn.setImageResource(src1); deletebtn.setColorFilter(getResources().getColor(R.color.welcomescreen)); deletebtn.setPadding(0, 0, 0, 0); deletebtn.setVisibility(View.GONE); PillLayout.addView(pillIndicator); PillLayout.addView(pillInfo); PillLayout.addView(iv_pilltype); PillLayout.addView(deletebtn, layoutParams4); return PillLayout; } public ImageView CreatePillView(int PillType) { ImageView iv = new ImageView(EditSlot.this); int src = 0; if (PillType == 1) { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(90, 90); src = R.drawable.circular_pill; layoutParams.weight = 1; iv.setImageResource(src); iv.setColorFilter(getResources().getColor(R.color.welcomescreen)); layoutParams.setMargins(0, 60, 0, 0); iv.setPadding(0, 0, 0, 0); iv.setLayoutParams(layoutParams); } else if (PillType == 2) { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100); src = R.drawable.capsule_pill; layoutParams.weight = 1; iv.setImageResource(src); iv.setColorFilter(getResources().getColor(R.color.welcomescreen)); layoutParams.setMargins(0, 60, 0, 0); iv.setPadding(0, 0, 0, 0); iv.setLayoutParams(layoutParams); } return iv; } public void SetPillIndicator(int idx,int count) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); LinearLayout pillindicator = (LinearLayout) pilllayout.getChildAt(0); pillindicator.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } public LinearLayout CreateSeparator() { LinearLayout separator = new LinearLayout(EditSlot.this); LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.MATCH_PARENT, 2); layoutParams1.setMargins(20, 20, 20, 20); separator.setLayoutParams(layoutParams1); separator.setBackgroundColor(getResources().getColor(R.color.SeparatorColor)); return separator; } public ImageView GetDeleteImage(int idx) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); ImageView delete = (ImageView) pilllayout.getChildAt(3); return delete; } public void SetPillsLeftText(int idx,int count) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); LinearLayout pillinfo = (LinearLayout) pilllayout.getChildAt(1); LinearLayout pillcount = (LinearLayout) pillinfo.getChildAt(1); TextView pillsleft = (TextView) pillcount.getChildAt(0); if(count == 1) pillsleft.setText(Integer.toString(count) + " pill left"); else pillsleft.setText(Integer.toString(count) + " pills left"); } ////////////////////////////////////////////////////////////////////////////// public void ShowEditLabels() { for (int i = 0; i < currentPills.size(); i++) { TextView edit = GetEditLabel(i); ImageView delete = GetDeleteImage(i); if (editclicked % 2 != 0) { edit.setVisibility(View.VISIBLE); delete.setVisibility(View.VISIBLE); } else { edit.setVisibility(View.GONE); delete.setVisibility(View.GONE); } } } public TextView GetEditLabel(int idx) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); LinearLayout pillinfo = (LinearLayout) pilllayout.getChildAt(1); LinearLayout pillcount = (LinearLayout) pillinfo.getChildAt(1); TextView edit = (TextView) pillcount.getChildAt(1); return edit; } ///////////////////////////////Time Functions//////////////////////////////////// public void setTime(Button button, final int id) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(EditSlot.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { String selectedTime = ""; if (selectedHour < 10) selectedTime = "0" + Integer.toString(selectedHour) + ":"; else selectedTime = Integer.toString(selectedHour) + ":"; if (selectedMinute < 10) selectedTime += "0" + Integer.toString(selectedMinute); else selectedTime += Integer.toString(selectedMinute); if (id == 1) { setFromTime.setText(selectedTime); SetFromTimeClicked = true; } else { setToTime.setText(selectedTime); SetToTimeClicked = true; } } }, hour, minute, true);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } }); } //Function that changes the color of the number picker. public static boolean setNumberPickerTextColor(NumberPicker numberPicker, int color) { final int count = numberPicker.getChildCount(); for (int i = 0; i < count; i++) { View child = numberPicker.getChildAt(i); if (child instanceof EditText) { try { Field selectorWheelPaintField = numberPicker.getClass() .getDeclaredField("mSelectorWheelPaint"); selectorWheelPaintField.setAccessible(true); ((Paint) selectorWheelPaintField.get(numberPicker)).setColor(color); ((EditText) child).setTextColor(color); numberPicker.invalidate(); return true; } catch (NoSuchFieldException e) { Log.d("NumberPickerTextColor", e.toString()); } catch (IllegalAccessException e) { Log.d("NumberPickerTextColor", e.toString()); } catch (IllegalArgumentException e) { Log.d("NumberPickerTextColor", e.toString()); } } } return false; } }
UTF-8
Java
43,732
java
EditSlot.java
Java
[ { "context": "package com.example.omarelaimy.iseeyou;\nimport android.app.TimePickerDialog;\nimp", "end": 30, "score": 0.845850944519043, "start": 20, "tag": "USERNAME", "value": "omarelaimy" }, { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by Omar on 3/15/2017.\n...
null
[]
package com.example.omarelaimy.iseeyou; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import java.lang.reflect.Field; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import android.app.ProgressDialog; import android.util.Log; import android.widget.TimePicker; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Omar on 3/15/2017. */ public class EditSlot extends AppCompatActivity { private static final String TAG = "EditSlotActivity"; private static final String URL_FOR_EditSlot="https://icu.000webhostapp.com/editslot.php"; private static final String URL_FOR_GetSlot ="https://icu.000webhostapp.com/getslot.php"; private String PatientID; private String SlotDay,SlotDayTime,ProductID; private int insertPillType; //ArrayLists private ArrayList<Pill> currentPills = new ArrayList<>(); private List<Integer> currentpillstoremove = new ArrayList<>(); private ArrayList<LinearLayout> Separators = new ArrayList<>(); private ProgressDialog progress; //Views for the tool bar private TextView tv_ProductID,tv_SlotName; private ImageButton closeBtn; //Views for the mainlayout private TextView tv_emptyslot; private Button btn_edit; private ImageButton btn_add; private Button setFromTime,setToTime; private LinearLayout mainLayout; //Check Variables private boolean SetFromTimeClicked = false; private boolean SetToTimeClicked = false; private int editclicked = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_slot); //Get the toolbar Views tv_ProductID = (TextView) findViewById(R.id.slot_productid); tv_SlotName = (TextView) findViewById(R.id.slot_slotname); closeBtn = (ImageButton) findViewById(R.id.slot_cancel_button); btn_edit = (Button) findViewById(R.id.slot_edit_button); //Get Views for setting the time setFromTime = (Button) findViewById(R.id.from_time); setToTime = (Button) findViewById(R.id.to_time); //Get Views for the main layout mainLayout = (LinearLayout) findViewById(R.id.mainvew_editslot); tv_emptyslot = (TextView) findViewById(R.id.empty_slot); btn_add = (ImageButton) findViewById(R.id.add_pill); //Get the strings from the intent. Bundle extras = getIntent().getExtras(); PatientID = extras.getString("patientid"); ProductID = extras.getString("productid"); SlotDay = extras.getString("SlotDay"); SlotDayTime = extras.getString("SlotDayTime"); progress = ProgressDialog.show(this, "Getting your pills", "Please wait...", true); //Call the function that retrieves the product's pills for this slot. GetSlotPills(); //Click listener on the edit in the toolbar EditToolBarClickListener(btn_edit); //Click listener on the plus at the end of the page. AddPillListener(btn_add); //Set the SlotName to the text from the intent. tv_SlotName.setText(SlotDay + " " + SlotDayTime); tv_ProductID.setText(ProductID); //Closing EditSlot Page closeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //Call the set time on both time dialogs. setTime(setFromTime,1); setTime(setToTime,2); } /*************Event Listeners*************/ //Event handler for pressing Add button in the edit_slot page public void AddPillListener(ImageView button) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Alert Dialogue to add new pill //User adds the name and the count AddPillMessage(); } }); } public void EditToolBarClickListener(Button edit) { edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editclicked++; ShowEditLabels(); } }); } public void EditPillListener(TextView tv, final int idx) { tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdatePillCountMessage(idx); } }); } public void DeletePillListener(ImageView iv,final int idx) { iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DeletePillMessage(idx); } }); } /***************Database Functions*****************/ //Function that retrieves the pills from the database for the given slot and the product. public void GetSlotPills() { // Tag used to cancel the request String cancel_req_tag = "getslotpills"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_GetSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { progress.dismiss(); Log.d(TAG, "Get Pills Slot Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { JSONArray result = jObj.getJSONArray(Config.JSON_ARRAY); //CREATE THE LINEAR LAYOUT FOR THE ARRAY RETURNED of Pills. String CurrPillname = ""; String CurrPillCount = ""; String CurrPillType = ""; String FromTime = ""; String ToTime = ""; JSONObject initialobj = result.getJSONObject(0); FromTime = initialobj.getString(Config.KEY_SlotFromtime); ToTime = initialobj.getString(Config.KEY_SlotTotime); //Loop on all pills and put them in currentpills array as well as the layout. for (int i = 0; i < result.length(); i++) { Pill currentpill = new Pill(); JSONObject PillData = result.getJSONObject(i); CurrPillname = PillData.getString(Config.KEY_Pillname); CurrPillType = PillData.getString(Config.KEY_PillType); CurrPillCount = PillData.getString(Config.KEY_PillCount); LinearLayout newpillayout = CreatePillLayout(CurrPillname, Integer.parseInt(CurrPillCount), Integer.parseInt(CurrPillType)); LinearLayout separator = CreateSeparator(); Separators.add(separator); currentpill.SetPillInfo(CurrPillname,Integer.parseInt(CurrPillType),Integer.parseInt(CurrPillCount), i, newpillayout); currentPills.add(currentpill); mainLayout.addView(newpillayout); mainLayout.addView(separator); tv_emptyslot.setVisibility(View.GONE); SetToTimeClicked = true; SetFromTimeClicked = true; setFromTime.setText(FromTime); setToTime.setText(ToTime); } //Currentpills array is ACCESSIBLE here. for (int i = 0; i < currentPills.size(); i++) { //Call the onclick listener for each close image for all the added pills. ImageView deleteimg = GetDeleteImage(i); DeletePillListener(deleteimg, i); TextView editpill = GetEditLabel(i); EditPillListener(editpill,i); } } else { Toast.makeText(getApplicationContext(), "Welcome to your new slot!", Toast.LENGTH_LONG).show(); //No pills returned, set the visibility of the text to visible to tell the user. tv_emptyslot.setVisibility(View.VISIBLE); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Get Pills slot Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("slotday", SlotDay); params.put("slotdaytime", SlotDayTime); params.put("patientid", PatientID); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Function that updates the time of the slot with no pills added. public void UpdateSlotTime() { // Tag used to cancel the request String cancel_req_tag = "updateslottime"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Update Slot Time Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { String error_msg = jObj.getString("error_msg"); //Update done Toast.makeText(getApplicationContext(), error_msg, Toast.LENGTH_LONG).show(); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); setFromTime.setText("Set From Time"); setToTime.setText("Set To Time"); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Update Slot Time Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("day", SlotDay); params.put("daytime", SlotDayTime); params.put("fromtime", setFromTime.getText().toString()); params.put("totime", setToTime.getText().toString()); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Function that updates the pill count of the selected pill. public void UpdatePillCount(final int idx, final int count) { final String PillName = currentPills.get(idx).GetPillName(); // Tag used to cancel the request String cancel_req_tag = "updatepillcount"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Update Pill count Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { currentPills.get(idx).SetCount(count); //Update done Toast.makeText(getApplicationContext(), "Pill " + PillName + " is updated successfully", Toast.LENGTH_LONG).show(); //View New count in the layout SetPillsLeftText(idx,count); SetPillIndicator(idx,count); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Update Pills slot Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("day", SlotDay); params.put("daytime", SlotDayTime); params.put("pillname", PillName); params.put("pillcount", String.valueOf(count)); params.put("patientid", PatientID); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Function that deletes the selected pill from the database. public void DeletePill(int idx) { final String PillName = currentPills.get(idx).GetPillName(); // Tag used to cancel the request String cancel_req_tag = "deleteslotpill"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Delete Pill Slot Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { Toast.makeText(getApplicationContext(), "Pill " + PillName + " is deleted successfully", Toast.LENGTH_LONG).show(); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Delete Pill slot Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to get slot url Map<String, String> params = new HashMap<String, String>(); //Parameters for the slot of a given product. params.put("productid", ProductID); params.put("day", SlotDay); params.put("daytime", SlotDayTime); params.put("pillname", PillName); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } //Insert the Pill into the patient's inventory. public void InsertPill(final String insertPillName, final String insertPillCount) { // Tag used to cancel the request // Tag used to cancel the request String cancel_req_tag = "insertpills"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_FOR_EditSlot, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Insert Pill Slot Response: " + response); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); //Error is false, pill is inserted successfully. if (!error) { insertPillType = Integer.parseInt(jObj.getString("pilltype")); // insertPillType = Integer.parseInt(jObj.getJSONObject("result").getString("pilltype")); Pill newpill = new Pill(); int idx = currentPills.size(); //The index after adding the pill later LinearLayout newpillayout = CreatePillLayout(insertPillName,Integer.parseInt(insertPillCount),insertPillType); LinearLayout separator = CreateSeparator(); newpill.SetPillInfo(insertPillName,insertPillType,Integer.parseInt(insertPillCount),idx,newpillayout); currentPills.add(newpill); Separators.add(separator); mainLayout.addView(newpillayout); mainLayout.addView(separator); tv_emptyslot.setVisibility(View.GONE); ImageView newdeleteimage = GetDeleteImage(idx); TextView neweditpill = GetEditLabel(idx); if (editclicked % 2 != 0) { newdeleteimage.setVisibility(View.VISIBLE); neweditpill.setVisibility(View.VISIBLE); } String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); for (int i = 0; i<currentPills.size();i++) { ImageView deletepill = GetDeleteImage(i); TextView editpill = GetEditLabel(i); DeletePillListener(deletepill,i); EditPillListener(editpill,i); } } else { //Errors happened, show the error_message and you can mark the errored pills as red. String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Add Pill Inventory Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Posting params to register url Map<String, String> params = new HashMap<String, String>(); //Parameters for the patient params.put("productid",ProductID); params.put("patientid",PatientID); params.put("day",SlotDay); params.put("daytime",SlotDayTime); params.put("fromtime",setFromTime.getText().toString()); params.put("totime",setToTime.getText().toString()); params.put("pillname",insertPillName); params.put("pillcount",insertPillCount); return params; } }; // Adding request to request queue AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag); } /////////////////////////////Dialog Messages//////////////////////////////////////////////// //Update pill count message at pressing edit button public void UpdatePillCountMessage(final int idx) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Change Number of pills"); alertDialog.setMessage("Enter your new pills count"); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); input.setLayoutParams(lp); alertDialog.setView(input); alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String count = ""; count = input.getText().toString(); int intCount = Integer.parseInt(count); if (!count.equals("")) { if (count.equals(String.valueOf(0))) { Toast.makeText(getApplicationContext(), "You cannot update the slot pill with 0, remove it instead.", Toast.LENGTH_SHORT).show(); dialog.cancel(); } else if (intCount == currentPills.get(idx).GetPillCount()) { Toast.makeText(getApplicationContext(), "The number of the pills is the same as before.", Toast.LENGTH_SHORT).show(); dialog.cancel(); } else { //Valid new count(different than the displayed one). //Call the function to update the pillcount of the db. UpdatePillCount(idx, Integer.parseInt(count)); } } } }); alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } //Insert PillName and Count to add new pill to the slot public void AddPillMessage() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Add New Pill"); alertDialog.setMessage("Enter the new pill name and the number of pills you want to add."); LinearLayout layout = new LinearLayout(EditSlot.this); layout.setOrientation(LinearLayout.VERTICAL); final EditText et_pillname = new EditText(this); et_pillname.setInputType(InputType.TYPE_CLASS_TEXT); et_pillname.setHint("Pill Name"); final EditText et_pillcount = new EditText(this); et_pillcount.setInputType(InputType.TYPE_CLASS_NUMBER); et_pillcount.setHint("Number of Pills"); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp2.topMargin = 10; layout.setLayoutParams(lp1); et_pillname.setLayoutParams(lp2); et_pillcount.setLayoutParams(lp2); layout.addView(et_pillname); layout.addView(et_pillcount); alertDialog.setView(layout); alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String pillname = ""; String pillcount = ""; pillname = et_pillname.getText().toString(); pillcount = et_pillcount.getText().toString(); //Check if pillname is empty if (!pillname.equals("")) { if (!pillcount.equals("")) { if (pillcount.equals(String.valueOf(0))) { Toast.makeText(getApplicationContext(), "You cannot update the slot pill with 0, remove it instead.", Toast.LENGTH_SHORT).show(); dialog.cancel(); } else { //Valid new name and count //Check if time is set or not if (!SetFromTimeClicked && !SetToTimeClicked) Toast.makeText(getApplicationContext(),"Please set the From time and the To time of the slot.", Toast.LENGTH_LONG).show(); //Check if From Time is not set else if (!SetFromTimeClicked) Toast.makeText(getApplicationContext(),"Please set the From time of the slot.", Toast.LENGTH_LONG).show(); //Check if To Time is not set else if (!SetToTimeClicked) Toast.makeText(getApplicationContext(),"Please set the To time of the slot.", Toast.LENGTH_LONG).show(); else //Call the function to add the pill in the database InsertPill(pillname,pillcount); } } } } }); alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } //Slot Time Message. public void EditSlotTimeMessage() { new AlertDialog.Builder(this) .setTitle("Edit Slot Time") .setMessage("There are no new pills to be added. Do you want to edit the slot time only?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Call update query to update the current pills time. UpdateSlotTime(); } }).setNegativeButton("No", null).show(); } //Delete Pill Message. public void DeletePillMessage(final int idx) { new AlertDialog.Builder(this) .setTitle("Delete Pill") .setMessage("Are you sure you want to delete the pill completely from this slot?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Call function of database to delete from database. DeletePill(idx); //Remove from layout mainLayout.removeView(currentPills.get(idx).GetPillLayout()); mainLayout.removeView(Separators.get(idx)); currentpillstoremove.add(idx); if (currentPills.size() == currentpillstoremove.size()) tv_emptyslot.setVisibility(View.VISIBLE); } }).setNegativeButton("No", null).show(); } //////////////////////View Functions///////////////////////////////////////// public LinearLayout CreatePillLayout(String PillName, int PillCount, int PillType) { //main layout for each pill LinearLayout PillLayout = new LinearLayout(EditSlot.this); PillLayout.setOrientation(LinearLayout.HORIZONTAL); //Children of the pill layout2 LinearLayout pillIndicator = new LinearLayout(EditSlot.this); LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(46, 300); layoutParams1.setMargins(5, 10, 20, 10); //layoutParams1.weight = 1; pillIndicator.setLayoutParams(layoutParams1); pillIndicator.setBackgroundColor(getResources().getColor(R.color.colorAccent)); pillIndicator.setPadding(0, 0, 0, 0); //Layout for pill Description LinearLayout pillInfo = new LinearLayout(EditSlot.this); pillInfo.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.WRAP_CONTENT, android.app.ActionBar.LayoutParams.MATCH_PARENT); layoutParams2.setMargins(30, 10, 20, 10); layoutParams2.weight = 6; pillInfo.setLayoutParams(layoutParams2); //TextView for pillinfo TextView tv_pillname = new TextView(EditSlot.this); TextView tv_pillcount = new TextView(EditSlot.this); TextView edit_button = new TextView(EditSlot.this); //Setting the info for the pill name. tv_pillname.setText(PillName); tv_pillname.setTextColor(getResources().getColor(R.color.welcomescreen)); tv_pillname.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25); //Create a layout for the text of pills left along with edit button LinearLayout pilldescription = new LinearLayout(EditSlot.this); LinearLayout.LayoutParams pilldescription_params = new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.WRAP_CONTENT, android.app.ActionBar.LayoutParams.WRAP_CONTENT); pilldescription.setOrientation(LinearLayout.HORIZONTAL); pilldescription_params.setMargins(20, 0, 0, 70); pilldescription.setPadding(0, 0, 0, 0); pilldescription.setLayoutParams(pilldescription_params); //Text for viewing the pills left. if(PillCount == 1) tv_pillcount.setText(Integer.toString(PillCount) + " pill"); else tv_pillcount.setText(Integer.toString(PillCount) + " pills"); tv_pillcount.setTypeface(null, Typeface.ITALIC); tv_pillcount.setTextColor(getResources().getColor(R.color.greycolor)); tv_pillcount.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); //Button for edit. edit_button.setBackgroundColor(getResources().getColor(android.R.color.transparent)); edit_button.setText("edit"); edit_button.setAllCaps(false); edit_button.setPaintFlags(edit_button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); edit_button.setTextColor(getResources().getColor(R.color.welcomescreen)); edit_button.setTypeface(null, Typeface.ITALIC); edit_button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13); edit_button.setPadding(20, 0, 20, 0); edit_button.setVisibility(View.GONE); pilldescription.addView(tv_pillcount); pilldescription.addView(edit_button); pillInfo.addView(tv_pillname); pillInfo.addView(pilldescription); //ImageView for the icon ImageView iv_pilltype = CreatePillView(PillType); //Img for the X button LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams(25, 25); layoutParams4.weight = 1; layoutParams4.setMargins(20, 0, 0, 0); int src1 = R.drawable.x; ImageView deletebtn = new ImageView(EditSlot.this); deletebtn.setImageResource(src1); deletebtn.setColorFilter(getResources().getColor(R.color.welcomescreen)); deletebtn.setPadding(0, 0, 0, 0); deletebtn.setVisibility(View.GONE); PillLayout.addView(pillIndicator); PillLayout.addView(pillInfo); PillLayout.addView(iv_pilltype); PillLayout.addView(deletebtn, layoutParams4); return PillLayout; } public ImageView CreatePillView(int PillType) { ImageView iv = new ImageView(EditSlot.this); int src = 0; if (PillType == 1) { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(90, 90); src = R.drawable.circular_pill; layoutParams.weight = 1; iv.setImageResource(src); iv.setColorFilter(getResources().getColor(R.color.welcomescreen)); layoutParams.setMargins(0, 60, 0, 0); iv.setPadding(0, 0, 0, 0); iv.setLayoutParams(layoutParams); } else if (PillType == 2) { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100); src = R.drawable.capsule_pill; layoutParams.weight = 1; iv.setImageResource(src); iv.setColorFilter(getResources().getColor(R.color.welcomescreen)); layoutParams.setMargins(0, 60, 0, 0); iv.setPadding(0, 0, 0, 0); iv.setLayoutParams(layoutParams); } return iv; } public void SetPillIndicator(int idx,int count) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); LinearLayout pillindicator = (LinearLayout) pilllayout.getChildAt(0); pillindicator.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } public LinearLayout CreateSeparator() { LinearLayout separator = new LinearLayout(EditSlot.this); LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.MATCH_PARENT, 2); layoutParams1.setMargins(20, 20, 20, 20); separator.setLayoutParams(layoutParams1); separator.setBackgroundColor(getResources().getColor(R.color.SeparatorColor)); return separator; } public ImageView GetDeleteImage(int idx) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); ImageView delete = (ImageView) pilllayout.getChildAt(3); return delete; } public void SetPillsLeftText(int idx,int count) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); LinearLayout pillinfo = (LinearLayout) pilllayout.getChildAt(1); LinearLayout pillcount = (LinearLayout) pillinfo.getChildAt(1); TextView pillsleft = (TextView) pillcount.getChildAt(0); if(count == 1) pillsleft.setText(Integer.toString(count) + " pill left"); else pillsleft.setText(Integer.toString(count) + " pills left"); } ////////////////////////////////////////////////////////////////////////////// public void ShowEditLabels() { for (int i = 0; i < currentPills.size(); i++) { TextView edit = GetEditLabel(i); ImageView delete = GetDeleteImage(i); if (editclicked % 2 != 0) { edit.setVisibility(View.VISIBLE); delete.setVisibility(View.VISIBLE); } else { edit.setVisibility(View.GONE); delete.setVisibility(View.GONE); } } } public TextView GetEditLabel(int idx) { LinearLayout pilllayout = currentPills.get(idx).GetPillLayout(); LinearLayout pillinfo = (LinearLayout) pilllayout.getChildAt(1); LinearLayout pillcount = (LinearLayout) pillinfo.getChildAt(1); TextView edit = (TextView) pillcount.getChildAt(1); return edit; } ///////////////////////////////Time Functions//////////////////////////////////// public void setTime(Button button, final int id) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(EditSlot.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { String selectedTime = ""; if (selectedHour < 10) selectedTime = "0" + Integer.toString(selectedHour) + ":"; else selectedTime = Integer.toString(selectedHour) + ":"; if (selectedMinute < 10) selectedTime += "0" + Integer.toString(selectedMinute); else selectedTime += Integer.toString(selectedMinute); if (id == 1) { setFromTime.setText(selectedTime); SetFromTimeClicked = true; } else { setToTime.setText(selectedTime); SetToTimeClicked = true; } } }, hour, minute, true);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } }); } //Function that changes the color of the number picker. public static boolean setNumberPickerTextColor(NumberPicker numberPicker, int color) { final int count = numberPicker.getChildCount(); for (int i = 0; i < count; i++) { View child = numberPicker.getChildAt(i); if (child instanceof EditText) { try { Field selectorWheelPaintField = numberPicker.getClass() .getDeclaredField("mSelectorWheelPaint"); selectorWheelPaintField.setAccessible(true); ((Paint) selectorWheelPaintField.get(numberPicker)).setColor(color); ((EditText) child).setTextColor(color); numberPicker.invalidate(); return true; } catch (NoSuchFieldException e) { Log.d("NumberPickerTextColor", e.toString()); } catch (IllegalAccessException e) { Log.d("NumberPickerTextColor", e.toString()); } catch (IllegalArgumentException e) { Log.d("NumberPickerTextColor", e.toString()); } } } return false; } }
43,732
0.528309
0.52417
909
47.110012
30.541843
195
false
false
0
0
0
0
79
0.001806
0.759076
false
false
2
6e7f55744e8dade4a3067ffc4af641e2ffa328e5
403,726,990,151
1cc037b19a154941fd1fdc7d9d1c02702794b975
/core-customize/custom/spar/sparcore/src/com/spar/hcl/jalo/promotions/SparEmployeeDiscountPromotion.java
80128db08b96cceb7c346310b9673e395531bd47
[]
no_license
demo-solution/solution
https://github.com/demo-solution/solution
b557dea73d613ec8bb722e2d9a63a338f0b9cf8d
e342fd77084703d43122a17d7184803ea72ae5c2
refs/heads/master
2022-07-16T05:41:35.541000
2020-05-19T14:51:59
2020-05-19T14:51:59
259,383,771
0
0
null
false
2020-05-19T14:54:38
2020-04-27T16:07:54
2020-05-19T14:54:19
2020-05-19T14:54:37
101,858
0
0
1
Java
false
false
package com.spar.hcl.jalo.promotions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import javax.xml.ws.WebServiceException; import org.apache.log4j.Logger; import org.springframework.remoting.soap.SoapFaultException; import com.spar.hcl.sparpricefactory.model.SparPriceRowModel; import de.hybris.platform.category.jalo.Category; import de.hybris.platform.category.jalo.CategoryManager; import de.hybris.platform.core.Registry; import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.europe1.model.PriceRowModel; import de.hybris.platform.jalo.Item; import de.hybris.platform.jalo.JaloBusinessException; import de.hybris.platform.jalo.SessionContext; import de.hybris.platform.jalo.order.AbstractOrder; import de.hybris.platform.jalo.order.AbstractOrderEntry; import de.hybris.platform.jalo.type.ComposedType; import de.hybris.platform.promotions.jalo.PromotionResult; import de.hybris.platform.promotions.jalo.PromotionsManager; import de.hybris.platform.promotions.result.PromotionEvaluationContext; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.util.Config; public class SparEmployeeDiscountPromotion extends GeneratedSparEmployeeDiscountPromotion { @SuppressWarnings("unused") private final static Logger LOG = Logger.getLogger(SparEmployeeDiscountPromotion.class.getName()); /* * @Autowired private ModelService modelService; */ boolean isemployeedsicountenabled = Config.getBoolean("enableEmployeeDiscount", false); private final ModelService modelService = (ModelService) Registry.getApplicationContext().getBean("modelService"); private static final String Invalid_Categories = "spar.employeediscount.invalid.categories"; @Override protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException { // business code placed here will be executed before the item is created // then create the item final Item item = super.createItem(ctx, type, allAttributes); // business code placed here will be executed after the item was created // and return the item return item; } @SuppressWarnings("deprecation") @Override public List<PromotionResult> evaluate(final SessionContext sessioncontext, final PromotionEvaluationContext promotionevaluationcontext) { final Logger LOG = Logger.getLogger(SparEmployeeDiscountPromotion.class); final AbstractOrder order = promotionevaluationcontext.getOrder(); final List<AbstractOrderEntry> entries = order.getAllEntries(); //for each order entry- category & promotion will be checked.Orderentry should not be in the invalid category and no promotion should be applied on it. final List<PromotionResult> promotionResults = new ArrayList<PromotionResult>(); final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(sessioncontext, this, promotionevaluationcontext.getOrder(), 1.0F); final CustomerModel customer = modelService.get(getSession().getUser()); final Double percentageDiscount = getDiscountpercentage(); Double totalPrice = Double.valueOf(0.0); Double DiscountAmount = Double.valueOf(0.0); final Double GraceAmount = getGraceamount(); LOG.info("SparEmployeeDiscountPromotion"); LOG.info("SparEmployeeDiscountPromotion"); LOG.info("SparEmployeeDiscountPromotion Started"); if (customer.getWhetherEmployee() != null && customer.getWhetherEmployee().booleanValue() && customer.getEmployeeCode() != null && customer.getCOemployeediscountamount() != null && customer.getCOemployeediscountamount() > 0) { LOG.info("SparEmployeeDiscountPromotion Conditions Satisfied"); LOG.info("Reading from Local property File"); LOG.info(isemployeedsicountenabled); if (isemployeedsicountenabled) { try { if (entries != null) { for (final AbstractOrderEntry entry : entries) { if (isValidProductCategory(entry).booleanValue() && isNOPromotionApplied(entry).booleanValue()) { totalPrice = totalPrice.doubleValue() + entry.getBasePrice().doubleValue() * entry.getQuantity().longValue(); } } if (customer.getCOemployeediscountamount().doubleValue() < 0) { return promotionResults; } if (totalPrice.doubleValue() > customer.getCOemployeediscountamount().doubleValue()) { if (totalPrice.doubleValue() > customer.getCOemployeediscountamount().doubleValue() + GraceAmount.doubleValue()) { totalPrice = customer.getCOemployeediscountamount().doubleValue() + GraceAmount.doubleValue(); } } DiscountAmount = (totalPrice.doubleValue()) * (percentageDiscount.doubleValue() / 100.00d); result.addAction( sessioncontext, PromotionsManager.getInstance().createPromotionOrderAdjustTotalAction(sessioncontext, -DiscountAmount.doubleValue())); promotionResults.add(result); LOG.info("employeedsicountenabled is fired"); } return promotionResults; } catch (final SoapFaultException s) { LOG.info("Soap Fault Exception"); return promotionResults; } catch (final WebServiceException w) { LOG.info("Exception While Accessing WebService"); return promotionResults; } } } return promotionResults; } Boolean isValidProductCategory(final AbstractOrderEntry entry) { final CategoryManager catManager = CategoryManager.getInstance(); //GIVING US THIRD LEVEL category final Collection<Category> categories = catManager.getSupercategories(entry.getProduct()); final Collection<Category> invalidCategories = getCategories(); if (invalidCategories.contains(categories.iterator().next())) { LOG.info("false"); return false; } LOG.info("true"); return true; } // Should send true in case any promotion is applied on the product Boolean isNOPromotionApplied(final AbstractOrderEntry entry) { final AbstractOrderEntryModel entryModel = modelService.get(entry); final String currentWarehouseCode = (String) getSession().getAttribute("selectedWarehouseCode"); final Collection<PriceRowModel> priceRow = entryModel.getProduct().getEurope1Prices(); LOG.info(currentWarehouseCode); for (final PriceRowModel price : priceRow) { final SparPriceRowModel sparPrice = (SparPriceRowModel) price; LOG.info(sparPrice.getWarehouse().getCode()); if (sparPrice.getWarehouse().getCode().equals(currentWarehouseCode)) { LOG.info("sparPrice"); LOG.info(sparPrice.getCheckForPromotion().booleanValue()); return !sparPrice.getCheckForPromotion().booleanValue(); } } return false; } @Override public String getResultDescription(final SessionContext sessioncontext, final PromotionResult promotionresult, final Locale locale) { // YTODO Auto-generated method stub return null; } }
UTF-8
Java
7,027
java
SparEmployeeDiscountPromotion.java
Java
[]
null
[]
package com.spar.hcl.jalo.promotions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import javax.xml.ws.WebServiceException; import org.apache.log4j.Logger; import org.springframework.remoting.soap.SoapFaultException; import com.spar.hcl.sparpricefactory.model.SparPriceRowModel; import de.hybris.platform.category.jalo.Category; import de.hybris.platform.category.jalo.CategoryManager; import de.hybris.platform.core.Registry; import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.europe1.model.PriceRowModel; import de.hybris.platform.jalo.Item; import de.hybris.platform.jalo.JaloBusinessException; import de.hybris.platform.jalo.SessionContext; import de.hybris.platform.jalo.order.AbstractOrder; import de.hybris.platform.jalo.order.AbstractOrderEntry; import de.hybris.platform.jalo.type.ComposedType; import de.hybris.platform.promotions.jalo.PromotionResult; import de.hybris.platform.promotions.jalo.PromotionsManager; import de.hybris.platform.promotions.result.PromotionEvaluationContext; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.util.Config; public class SparEmployeeDiscountPromotion extends GeneratedSparEmployeeDiscountPromotion { @SuppressWarnings("unused") private final static Logger LOG = Logger.getLogger(SparEmployeeDiscountPromotion.class.getName()); /* * @Autowired private ModelService modelService; */ boolean isemployeedsicountenabled = Config.getBoolean("enableEmployeeDiscount", false); private final ModelService modelService = (ModelService) Registry.getApplicationContext().getBean("modelService"); private static final String Invalid_Categories = "spar.employeediscount.invalid.categories"; @Override protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException { // business code placed here will be executed before the item is created // then create the item final Item item = super.createItem(ctx, type, allAttributes); // business code placed here will be executed after the item was created // and return the item return item; } @SuppressWarnings("deprecation") @Override public List<PromotionResult> evaluate(final SessionContext sessioncontext, final PromotionEvaluationContext promotionevaluationcontext) { final Logger LOG = Logger.getLogger(SparEmployeeDiscountPromotion.class); final AbstractOrder order = promotionevaluationcontext.getOrder(); final List<AbstractOrderEntry> entries = order.getAllEntries(); //for each order entry- category & promotion will be checked.Orderentry should not be in the invalid category and no promotion should be applied on it. final List<PromotionResult> promotionResults = new ArrayList<PromotionResult>(); final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(sessioncontext, this, promotionevaluationcontext.getOrder(), 1.0F); final CustomerModel customer = modelService.get(getSession().getUser()); final Double percentageDiscount = getDiscountpercentage(); Double totalPrice = Double.valueOf(0.0); Double DiscountAmount = Double.valueOf(0.0); final Double GraceAmount = getGraceamount(); LOG.info("SparEmployeeDiscountPromotion"); LOG.info("SparEmployeeDiscountPromotion"); LOG.info("SparEmployeeDiscountPromotion Started"); if (customer.getWhetherEmployee() != null && customer.getWhetherEmployee().booleanValue() && customer.getEmployeeCode() != null && customer.getCOemployeediscountamount() != null && customer.getCOemployeediscountamount() > 0) { LOG.info("SparEmployeeDiscountPromotion Conditions Satisfied"); LOG.info("Reading from Local property File"); LOG.info(isemployeedsicountenabled); if (isemployeedsicountenabled) { try { if (entries != null) { for (final AbstractOrderEntry entry : entries) { if (isValidProductCategory(entry).booleanValue() && isNOPromotionApplied(entry).booleanValue()) { totalPrice = totalPrice.doubleValue() + entry.getBasePrice().doubleValue() * entry.getQuantity().longValue(); } } if (customer.getCOemployeediscountamount().doubleValue() < 0) { return promotionResults; } if (totalPrice.doubleValue() > customer.getCOemployeediscountamount().doubleValue()) { if (totalPrice.doubleValue() > customer.getCOemployeediscountamount().doubleValue() + GraceAmount.doubleValue()) { totalPrice = customer.getCOemployeediscountamount().doubleValue() + GraceAmount.doubleValue(); } } DiscountAmount = (totalPrice.doubleValue()) * (percentageDiscount.doubleValue() / 100.00d); result.addAction( sessioncontext, PromotionsManager.getInstance().createPromotionOrderAdjustTotalAction(sessioncontext, -DiscountAmount.doubleValue())); promotionResults.add(result); LOG.info("employeedsicountenabled is fired"); } return promotionResults; } catch (final SoapFaultException s) { LOG.info("Soap Fault Exception"); return promotionResults; } catch (final WebServiceException w) { LOG.info("Exception While Accessing WebService"); return promotionResults; } } } return promotionResults; } Boolean isValidProductCategory(final AbstractOrderEntry entry) { final CategoryManager catManager = CategoryManager.getInstance(); //GIVING US THIRD LEVEL category final Collection<Category> categories = catManager.getSupercategories(entry.getProduct()); final Collection<Category> invalidCategories = getCategories(); if (invalidCategories.contains(categories.iterator().next())) { LOG.info("false"); return false; } LOG.info("true"); return true; } // Should send true in case any promotion is applied on the product Boolean isNOPromotionApplied(final AbstractOrderEntry entry) { final AbstractOrderEntryModel entryModel = modelService.get(entry); final String currentWarehouseCode = (String) getSession().getAttribute("selectedWarehouseCode"); final Collection<PriceRowModel> priceRow = entryModel.getProduct().getEurope1Prices(); LOG.info(currentWarehouseCode); for (final PriceRowModel price : priceRow) { final SparPriceRowModel sparPrice = (SparPriceRowModel) price; LOG.info(sparPrice.getWarehouse().getCode()); if (sparPrice.getWarehouse().getCode().equals(currentWarehouseCode)) { LOG.info("sparPrice"); LOG.info(sparPrice.getCheckForPromotion().booleanValue()); return !sparPrice.getCheckForPromotion().booleanValue(); } } return false; } @Override public String getResultDescription(final SessionContext sessioncontext, final PromotionResult promotionresult, final Locale locale) { // YTODO Auto-generated method stub return null; } }
7,027
0.761776
0.759499
190
35.984211
32.823368
153
false
false
0
0
0
0
0
0
2.857895
false
false
2
952831e47e73a9b44e3697ee9f0eb4a8c4f8b11f
37,830,071,971,857
6f2a821cbbbf36b323a6487adf75c235f1777e6e
/app/src/main/java/com/jacob/floatview/view/FloatBigView.java
e81fee6d1b85a4426fbb8082766c796e374ffaa9
[ "MIT" ]
permissive
wangjia55/FloatView
https://github.com/wangjia55/FloatView
60c9b8388bdd39f93fa9f120a7fd5867cbe36a81
726809a5970a53568d1e538540a114ba8fe148df
refs/heads/master
2021-01-20T08:44:04.527000
2015-04-28T12:48:06
2015-04-28T12:48:06
34,660,325
10
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jacob.floatview.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import com.jacob.floatview.MyWindowManager; import com.jacob.floatview.R; /** * Created by jacob-wj on 2015/4/28. */ public class FloatBigView extends LinearLayout implements View.OnClickListener { private MyWindowManager myWindowManager; public int width; public int height; public FloatBigView(Context context) { this(context, null); } public FloatBigView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FloatBigView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.layout_big_window, this); findViewById(R.id.button_back).setOnClickListener(this); View container = findViewById(R.id.container); width = container.getLayoutParams().width; height = container.getLayoutParams().height; } @Override public void onClick(View v) { if (myWindowManager == null) { myWindowManager = MyWindowManager.newInstance(); } myWindowManager.removeBigView(getContext()); myWindowManager.showSmallView(getContext()); } }
UTF-8
Java
1,518
java
FloatBigView.java
Java
[ { "context": ";\nimport com.jacob.floatview.R;\n\n/**\n * Created by jacob-wj on 2015/4/28.\n */\npublic class FloatBigView exten", "end": 432, "score": 0.9996446967124939, "start": 424, "tag": "USERNAME", "value": "jacob-wj" } ]
null
[]
package com.jacob.floatview.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import com.jacob.floatview.MyWindowManager; import com.jacob.floatview.R; /** * Created by jacob-wj on 2015/4/28. */ public class FloatBigView extends LinearLayout implements View.OnClickListener { private MyWindowManager myWindowManager; public int width; public int height; public FloatBigView(Context context) { this(context, null); } public FloatBigView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FloatBigView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.layout_big_window, this); findViewById(R.id.button_back).setOnClickListener(this); View container = findViewById(R.id.container); width = container.getLayoutParams().width; height = container.getLayoutParams().height; } @Override public void onClick(View v) { if (myWindowManager == null) { myWindowManager = MyWindowManager.newInstance(); } myWindowManager.removeBigView(getContext()); myWindowManager.showSmallView(getContext()); } }
1,518
0.716733
0.711462
53
27.64151
23.442499
80
false
false
0
0
0
0
0
0
0.660377
false
false
2
7be51a52ab9f3312cecfaaf31d9285f624b7bbe0
8,358,006,361,106
97889c445661cec1ec8a846b0673bb0df8ebb100
/src/manager/xsales/program/shared/domain/beallitasok/BeallitasokRendszer.java
5b9dd326a245961ec0bdac4edd334eb59ea8d558
[]
no_license
eggp/XSalesManager
https://github.com/eggp/XSalesManager
08a8e304d39f585ba952815f3e1e2a165375e332
8019f6fbd3683d36406cc9369d54e700389cb182
refs/heads/master
2015-07-10T00:28:03
2015-03-18T21:01:42
2015-03-18T21:01:42
10,280,958
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package manager.xsales.program.shared.domain.beallitasok; import hgexengine.utils.shared.HasVersion; import hgexengine.utils.shared.domain.AbstractDomainObjectWithCreateAndModifyDate; import hgexengine.utils.shared.domain.HasCreateFelhasznalo; import hgexengine.utils.shared.domain.HasDeleted; import hgexengine.utils.shared.domain.HasModifyFelhasznalo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.Version; import manager.xsales.program.shared.domain.felhasznalok.Felhasznalok; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.envers.Audited; import com.google.gwt.core.shared.GWT; @Entity @DynamicInsert @DynamicUpdate @BatchSize(size = 100) @Table(name = "beallitasok") @Audited public class BeallitasokRendszer extends AbstractDomainObjectWithCreateAndModifyDate implements HasVersion, HasCreateFelhasznalo, HasModifyFelhasznalo, HasDeleted { private static final long serialVersionUID = -5135098855188346341L; private String optionName; private String optionValue; @Transient private static BeallitasokRendszerProxyProperties properties; @Transient private static BeallitasokRendszerProxyListProperties listProperties; private Long version; private Felhasznalok createFelhasznalo; private Felhasznalok modifyFelhasznalo; private Boolean deleted = false; public BeallitasokRendszer() { super(); // TODO Auto-generated constructor stub } @Column(name = "option_name", unique = true, nullable = false) public String getOptionName() { return optionName; } public void setOptionName(String optionName) { this.optionName = optionName; } @Column(name = "option_value", nullable = false) public String getOptionValue() { return optionValue; } public void setOptionValue(String optionValue) { this.optionValue = optionValue; } @Transient public static BeallitasokRendszerProxyProperties getProperties() { if (properties == null) { properties = GWT.create(BeallitasokRendszerProxyProperties.class); } return properties; } @Transient public static BeallitasokRendszerProxyListProperties getListProperties() { if (listProperties == null) { listProperties = GWT.create(BeallitasokRendszerProxyListProperties.class); } return listProperties; } @Override public void setDeleted(Boolean bool) { deleted = bool; } @Override public Boolean getDeleted() { return deleted; } @Version @Override public Long getVersion() { return version; } @Override public void setVersion(Long version) { this.version = version; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "create_felhasznalok_id", nullable = false) public Felhasznalok getCreateFelhasznalo() { return createFelhasznalo; } public void setCreateFelhasznalo(Felhasznalok createFelhasznalo) { this.createFelhasznalo = createFelhasznalo; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "modify_felhasznalok_id", nullable = false) public Felhasznalok getModifyFelhasznalo() { return modifyFelhasznalo; } public void setModifyFelhasznalo(Felhasznalok modifyFelhasznalo) { this.modifyFelhasznalo = modifyFelhasznalo; } }
UTF-8
Java
3,625
java
BeallitasokRendszer.java
Java
[]
null
[]
package manager.xsales.program.shared.domain.beallitasok; import hgexengine.utils.shared.HasVersion; import hgexengine.utils.shared.domain.AbstractDomainObjectWithCreateAndModifyDate; import hgexengine.utils.shared.domain.HasCreateFelhasznalo; import hgexengine.utils.shared.domain.HasDeleted; import hgexengine.utils.shared.domain.HasModifyFelhasznalo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.Version; import manager.xsales.program.shared.domain.felhasznalok.Felhasznalok; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.envers.Audited; import com.google.gwt.core.shared.GWT; @Entity @DynamicInsert @DynamicUpdate @BatchSize(size = 100) @Table(name = "beallitasok") @Audited public class BeallitasokRendszer extends AbstractDomainObjectWithCreateAndModifyDate implements HasVersion, HasCreateFelhasznalo, HasModifyFelhasznalo, HasDeleted { private static final long serialVersionUID = -5135098855188346341L; private String optionName; private String optionValue; @Transient private static BeallitasokRendszerProxyProperties properties; @Transient private static BeallitasokRendszerProxyListProperties listProperties; private Long version; private Felhasznalok createFelhasznalo; private Felhasznalok modifyFelhasznalo; private Boolean deleted = false; public BeallitasokRendszer() { super(); // TODO Auto-generated constructor stub } @Column(name = "option_name", unique = true, nullable = false) public String getOptionName() { return optionName; } public void setOptionName(String optionName) { this.optionName = optionName; } @Column(name = "option_value", nullable = false) public String getOptionValue() { return optionValue; } public void setOptionValue(String optionValue) { this.optionValue = optionValue; } @Transient public static BeallitasokRendszerProxyProperties getProperties() { if (properties == null) { properties = GWT.create(BeallitasokRendszerProxyProperties.class); } return properties; } @Transient public static BeallitasokRendszerProxyListProperties getListProperties() { if (listProperties == null) { listProperties = GWT.create(BeallitasokRendszerProxyListProperties.class); } return listProperties; } @Override public void setDeleted(Boolean bool) { deleted = bool; } @Override public Boolean getDeleted() { return deleted; } @Version @Override public Long getVersion() { return version; } @Override public void setVersion(Long version) { this.version = version; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "create_felhasznalok_id", nullable = false) public Felhasznalok getCreateFelhasznalo() { return createFelhasznalo; } public void setCreateFelhasznalo(Felhasznalok createFelhasznalo) { this.createFelhasznalo = createFelhasznalo; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "modify_felhasznalok_id", nullable = false) public Felhasznalok getModifyFelhasznalo() { return modifyFelhasznalo; } public void setModifyFelhasznalo(Felhasznalok modifyFelhasznalo) { this.modifyFelhasznalo = modifyFelhasznalo; } }
3,625
0.754207
0.748138
130
25.884615
24.2955
107
false
false
0
0
0
0
0
0
1.8
false
false
2
fcb7824949b2880f72bf175992b15ea2d70cbb1c
7,103,875,978,297
d17f33afbbdf61ce5b2e86e6f970af92eacc4da1
/GroupProject/TourneyManager/app/src/main/java/edu/gatech/seclass/tourneymanager/ManagerMode.java
0e83f5ade07e7684df77826ec1e7fa41d75618ff
[]
no_license
johonea4/TourneyManagerApp
https://github.com/johonea4/TourneyManagerApp
b34a2f0c146addcb07117a6069f2f17fa125cb2e
3b8e96d9eb34a91efcf4f22a34b5793d4c645686
refs/heads/master
2020-05-05T05:22:48.613000
2017-03-11T00:10:40
2017-03-11T00:10:40
179,749,111
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.gatech.seclass.tourneymanager; import android.content.Context; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.Arrays; import java.util.SortedSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import edu.gatech.seclass.tourneymanager.Dao.TourneyManagerDao; import edu.gatech.seclass.tourneymanager.models.Match; import edu.gatech.seclass.tourneymanager.models.Player; import edu.gatech.seclass.tourneymanager.models.Prize; import edu.gatech.seclass.tourneymanager.models.Round; import edu.gatech.seclass.tourneymanager.models.Tournament; import edu.gatech.seclass.tourneymanager.models.TourneyInfo; /** * Created by johon on 2/25/2017. */ public class ManagerMode extends AppMode { ManagerMode(TourneyManagerApp app) { super(mode_t.MANAGER); m_app = app; } public boolean createTournament(ArrayList<String> players, int tourneyId, int percent, int fee, Context context) { Tournament tournament = new Tournament(); tournament.setId(tourneyId); tournament.setRunning(true); TourneyInfo tourneyInfo = new TourneyInfo(); tourneyInfo.setEntryPrice(fee); tourneyInfo.setUserNames(players); tourneyInfo.setHousePercent(percent); tourneyInfo.setNumberOfEntrants(players.size()); tourneyInfo.setCalculatedValues(); tournament.setInfo(tourneyInfo); try { TourneyManagerDao.saveTournament(tournament, context); } catch (Exception e) { return false; } return createRounds(context,tourneyId, players.size()); } private boolean createRounds(Context context, int tId, int nPlayers){ if(nPlayers%2>0) nPlayers+=1; int rounds=0,matches=0; ArrayList<Round> roundList = new ArrayList<Round>(); for(int i=nPlayers;i>1;i=(i/2)) { Round round = new Round(tId); round.setId(m_app.getLastRoundId()+1); m_app.setLastRoundId(round.getId()); roundList.add(round); round.createMatches(i/2,round.getId(),m_app.getLastMatchId()); m_app.setLastMatchId(m_app.getLastMatchId()+(i/2)); } try { TourneyManagerDao.saveRounds(roundList, context); } catch (Exception e) { return false; } return true; } public boolean EndTournament(Context context){ try { Tournament t = TourneyManagerDao.GetActiveTournament(context); HashMap<Integer, ArrayList<Match>> matchMap = TourneyManagerDao.GetMatchesByTourneyId(t.getId(), context); Set<Integer> keys = matchMap.keySet(); boolean isRunningOrNotStarted = false; for (Integer i : keys) { Round r = TourneyManagerDao.GetRound(t.getId(), i, context); isRunningOrNotStarted |= TourneyManagerDao.GetRoundState(i, context) == Round.RoundState.NOT_STARTED || TourneyManagerDao.GetRoundState(i, context) == Round.RoundState.RUNNING; } if (isRunningOrNotStarted) { t.setRunning(false); t.setEndedEarly(true); TourneyManagerDao.updateTournament(t, context); return false; //method to check if all the rounds are being completed. call refund not. } else{ int lastMatchId = m_app.getLastMatchId(); int secondLastRoundId = m_app.getLastRoundId()-1; Match lastMatch = TourneyManagerDao.GetMatchById(lastMatchId, context); String winner = lastMatch.getWinner(); String runnerUp = lastMatch.getWinner().equals(lastMatch.getPlayer1()) ? lastMatch.getPlayer2() : lastMatch.getPlayer1(); //find the third place playoff Round secondLastRound = TourneyManagerDao.GetRound(t.getId(), secondLastRoundId, context); List<String> secondLastRoundWinners = secondLastRound.getWinners(); List<String> secondLastRoundPlayers = new ArrayList<String>(); List<Match> secondLastRoundMatches = secondLastRound.getMatches(); for(int i=0; i<secondLastRound.getMatches().size(); i++){ secondLastRoundPlayers.add(secondLastRoundMatches.get(i).getPlayer1()); secondLastRoundPlayers.add(secondLastRoundMatches.get(i).getPlayer2()); } secondLastRoundPlayers.removeAll(Collections.singletonList(winner)); secondLastRoundPlayers.removeAll(Collections.singletonList(runnerUp)); String thirdPlacePlayoff = secondLastRoundPlayers.get(new Random().nextInt(secondLastRoundPlayers.size())); //update the player prizes addPlayerPrizes(winner, t.getId(), 1, t.getInfo().getFirstPlacePrize(), context); addPlayerPrizes(runnerUp, t.getId(), 2, t.getInfo().getSecondPlacePrize(), context); addPlayerPrizes(thirdPlacePlayoff, t.getId(), 3, t.getInfo().getThirdPlacePrize(), context); t.setRunning(false); t.setFinished(true); TourneyManagerDao.updateTournament(t, context); return true; } //method to find if the tournament ended early. Not all the rounds are completed. //update the tournament/ matches } catch(Exception e){ return false; } } private void addPlayerPrizes(String player, int tId, int place, int money, Context context){ Prize prize = new Prize(); prize.setUserName(player); prize.setTourneyId(tId); prize.setPlace(place); prize.setMoneyWon(money); TourneyManagerDao.addPrize(prize, context); } public int CheckRound(int rID, int tID, Context context) { Round.RoundState state = TourneyManagerDao.GetRoundState(rID,context); if(state == Round.RoundState.FINISHED) { Set<Integer> rIds = TourneyManagerDao.GetMatchesByTourneyId(tID,context).keySet(); SortedSet<Integer> sorted = new TreeSet<Integer>(rIds); Iterator<Integer> i = sorted.iterator(); while(i.hasNext()) { int tmp = i.next(); if(tmp==rID && i.hasNext()) { return SetNextRound(rID,i.next(),tID,context)==true ? 1 : 0; } } return -1; } return 1; } public boolean SetNextRound(int curRoundId, int nextRoundId, int tid, Context context) { if(curRoundId==-1) { Tournament t = TourneyManagerDao.GetActiveTournament(context); Round r = TourneyManagerDao.GetRound(tid,-1,context); Iterator<String> n = t.getInfo().getUserNames().iterator(); for(Match m : r.getMatches()) { if(n.hasNext()) { m.setPlayer1(n.next()); if(n.hasNext()) m.setPlayer2(n.next()); else return false; } else return false; TourneyManagerDao.UpdateMatch(m,context); } } else { Round r1 = TourneyManagerDao.GetRound(tid,curRoundId,context); Round r2 = TourneyManagerDao.GetRound(tid,nextRoundId,context); String [] w = r1.getWinners().toArray(new String[r1.getWinners().size()]); int nWinners = r1.getWinners().size(); int i=0; for(Match m : r2.getMatches()) { if(i<nWinners-1) { m.setPlayer1(w[i++]); m.setPlayer2(w[i++]); } else return false; TourneyManagerDao.UpdateMatch(m,context); } } return true; } public boolean createPlayer(String name, String username, String phone, String deckChoice, Context context) { Player player = new Player(); player.setName(name); player.setUserName(username); player.setPhoneNumber(phone); player.setDeckChoice(deckChoice); try { TourneyManagerDao.savePlayer(player, context); //db call } catch (Exception e) { return false; } return true; } public boolean updatePlayer(String name, String username, String phone, String deckChoice, Context context) { Player player = TourneyManagerDao.GetPlayerByUsername(username, context); if(player==null) return false; player.setName(name); player.setUserName(username); player.setPhoneNumber(phone); player.setDeckChoice(deckChoice); try { TourneyManagerDao.UpdatePlayer(player, context); //db call } catch (Exception e) { return false; } return true; } private TourneyManagerApp m_app; }
UTF-8
Java
9,345
java
ManagerMode.java
Java
[ { "context": "rneymanager.models.TourneyInfo;\n\n/**\n * Created by johon on 2/25/2017.\n */\n\npublic class ManagerMode exten", "end": 846, "score": 0.9725346565246582, "start": 841, "tag": "USERNAME", "value": "johon" }, { "context": "ze prize = new Prize();\n prize.setUserN...
null
[]
package edu.gatech.seclass.tourneymanager; import android.content.Context; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.Arrays; import java.util.SortedSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import edu.gatech.seclass.tourneymanager.Dao.TourneyManagerDao; import edu.gatech.seclass.tourneymanager.models.Match; import edu.gatech.seclass.tourneymanager.models.Player; import edu.gatech.seclass.tourneymanager.models.Prize; import edu.gatech.seclass.tourneymanager.models.Round; import edu.gatech.seclass.tourneymanager.models.Tournament; import edu.gatech.seclass.tourneymanager.models.TourneyInfo; /** * Created by johon on 2/25/2017. */ public class ManagerMode extends AppMode { ManagerMode(TourneyManagerApp app) { super(mode_t.MANAGER); m_app = app; } public boolean createTournament(ArrayList<String> players, int tourneyId, int percent, int fee, Context context) { Tournament tournament = new Tournament(); tournament.setId(tourneyId); tournament.setRunning(true); TourneyInfo tourneyInfo = new TourneyInfo(); tourneyInfo.setEntryPrice(fee); tourneyInfo.setUserNames(players); tourneyInfo.setHousePercent(percent); tourneyInfo.setNumberOfEntrants(players.size()); tourneyInfo.setCalculatedValues(); tournament.setInfo(tourneyInfo); try { TourneyManagerDao.saveTournament(tournament, context); } catch (Exception e) { return false; } return createRounds(context,tourneyId, players.size()); } private boolean createRounds(Context context, int tId, int nPlayers){ if(nPlayers%2>0) nPlayers+=1; int rounds=0,matches=0; ArrayList<Round> roundList = new ArrayList<Round>(); for(int i=nPlayers;i>1;i=(i/2)) { Round round = new Round(tId); round.setId(m_app.getLastRoundId()+1); m_app.setLastRoundId(round.getId()); roundList.add(round); round.createMatches(i/2,round.getId(),m_app.getLastMatchId()); m_app.setLastMatchId(m_app.getLastMatchId()+(i/2)); } try { TourneyManagerDao.saveRounds(roundList, context); } catch (Exception e) { return false; } return true; } public boolean EndTournament(Context context){ try { Tournament t = TourneyManagerDao.GetActiveTournament(context); HashMap<Integer, ArrayList<Match>> matchMap = TourneyManagerDao.GetMatchesByTourneyId(t.getId(), context); Set<Integer> keys = matchMap.keySet(); boolean isRunningOrNotStarted = false; for (Integer i : keys) { Round r = TourneyManagerDao.GetRound(t.getId(), i, context); isRunningOrNotStarted |= TourneyManagerDao.GetRoundState(i, context) == Round.RoundState.NOT_STARTED || TourneyManagerDao.GetRoundState(i, context) == Round.RoundState.RUNNING; } if (isRunningOrNotStarted) { t.setRunning(false); t.setEndedEarly(true); TourneyManagerDao.updateTournament(t, context); return false; //method to check if all the rounds are being completed. call refund not. } else{ int lastMatchId = m_app.getLastMatchId(); int secondLastRoundId = m_app.getLastRoundId()-1; Match lastMatch = TourneyManagerDao.GetMatchById(lastMatchId, context); String winner = lastMatch.getWinner(); String runnerUp = lastMatch.getWinner().equals(lastMatch.getPlayer1()) ? lastMatch.getPlayer2() : lastMatch.getPlayer1(); //find the third place playoff Round secondLastRound = TourneyManagerDao.GetRound(t.getId(), secondLastRoundId, context); List<String> secondLastRoundWinners = secondLastRound.getWinners(); List<String> secondLastRoundPlayers = new ArrayList<String>(); List<Match> secondLastRoundMatches = secondLastRound.getMatches(); for(int i=0; i<secondLastRound.getMatches().size(); i++){ secondLastRoundPlayers.add(secondLastRoundMatches.get(i).getPlayer1()); secondLastRoundPlayers.add(secondLastRoundMatches.get(i).getPlayer2()); } secondLastRoundPlayers.removeAll(Collections.singletonList(winner)); secondLastRoundPlayers.removeAll(Collections.singletonList(runnerUp)); String thirdPlacePlayoff = secondLastRoundPlayers.get(new Random().nextInt(secondLastRoundPlayers.size())); //update the player prizes addPlayerPrizes(winner, t.getId(), 1, t.getInfo().getFirstPlacePrize(), context); addPlayerPrizes(runnerUp, t.getId(), 2, t.getInfo().getSecondPlacePrize(), context); addPlayerPrizes(thirdPlacePlayoff, t.getId(), 3, t.getInfo().getThirdPlacePrize(), context); t.setRunning(false); t.setFinished(true); TourneyManagerDao.updateTournament(t, context); return true; } //method to find if the tournament ended early. Not all the rounds are completed. //update the tournament/ matches } catch(Exception e){ return false; } } private void addPlayerPrizes(String player, int tId, int place, int money, Context context){ Prize prize = new Prize(); prize.setUserName(player); prize.setTourneyId(tId); prize.setPlace(place); prize.setMoneyWon(money); TourneyManagerDao.addPrize(prize, context); } public int CheckRound(int rID, int tID, Context context) { Round.RoundState state = TourneyManagerDao.GetRoundState(rID,context); if(state == Round.RoundState.FINISHED) { Set<Integer> rIds = TourneyManagerDao.GetMatchesByTourneyId(tID,context).keySet(); SortedSet<Integer> sorted = new TreeSet<Integer>(rIds); Iterator<Integer> i = sorted.iterator(); while(i.hasNext()) { int tmp = i.next(); if(tmp==rID && i.hasNext()) { return SetNextRound(rID,i.next(),tID,context)==true ? 1 : 0; } } return -1; } return 1; } public boolean SetNextRound(int curRoundId, int nextRoundId, int tid, Context context) { if(curRoundId==-1) { Tournament t = TourneyManagerDao.GetActiveTournament(context); Round r = TourneyManagerDao.GetRound(tid,-1,context); Iterator<String> n = t.getInfo().getUserNames().iterator(); for(Match m : r.getMatches()) { if(n.hasNext()) { m.setPlayer1(n.next()); if(n.hasNext()) m.setPlayer2(n.next()); else return false; } else return false; TourneyManagerDao.UpdateMatch(m,context); } } else { Round r1 = TourneyManagerDao.GetRound(tid,curRoundId,context); Round r2 = TourneyManagerDao.GetRound(tid,nextRoundId,context); String [] w = r1.getWinners().toArray(new String[r1.getWinners().size()]); int nWinners = r1.getWinners().size(); int i=0; for(Match m : r2.getMatches()) { if(i<nWinners-1) { m.setPlayer1(w[i++]); m.setPlayer2(w[i++]); } else return false; TourneyManagerDao.UpdateMatch(m,context); } } return true; } public boolean createPlayer(String name, String username, String phone, String deckChoice, Context context) { Player player = new Player(); player.setName(name); player.setUserName(username); player.setPhoneNumber(phone); player.setDeckChoice(deckChoice); try { TourneyManagerDao.savePlayer(player, context); //db call } catch (Exception e) { return false; } return true; } public boolean updatePlayer(String name, String username, String phone, String deckChoice, Context context) { Player player = TourneyManagerDao.GetPlayerByUsername(username, context); if(player==null) return false; player.setName(name); player.setUserName(username); player.setPhoneNumber(phone); player.setDeckChoice(deckChoice); try { TourneyManagerDao.UpdatePlayer(player, context); //db call } catch (Exception e) { return false; } return true; } private TourneyManagerApp m_app; }
9,345
0.599893
0.595078
253
35.93676
30.525761
137
false
false
0
0
0
0
0
0
0.822134
false
false
2
7223982a46ad92c6362b30ce0d0c60d73887ae66
14,843,407,038,545
074c6d12d901863fcd57818ceefcf096e6e41566
/TP/src/test/java/com/EyVdeSW/TP/services/TestTarifarioService.java
9e96ce32bbd3c41814ed973e2e34985fea26c8c5
[]
no_license
roberGzt/TPEspecificacion
https://github.com/roberGzt/TPEspecificacion
d51c31393052589237c1d58f6ac142431d5a6374
a227cbbd2c3582b197555f24fc5c447a87d597a6
refs/heads/master
2021-01-21T07:13:55.288000
2017-06-30T16:29:46
2017-06-30T16:29:46
91,604,037
0
0
null
false
2017-06-23T15:45:22
2017-05-17T17:42:44
2017-05-17T18:01:33
2017-06-23T15:45:21
491
0
0
1
CSS
null
null
package com.EyVdeSW.TP.services; import static org.junit.Assert.*; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.easymock.*; import org.junit.Test; import org.junit.runner.RunWith; import com.EyVdeSW.TP.Daos.TarifarioDAO; import com.EyVdeSW.TP.domainModel.Tarifario; import com.EyVdeSW.TP.domainModel.Tarifario.TipoTarifario; @RunWith(EasyMockRunner.class) public class TestTarifarioService { @Mock TarifarioDAO<Tarifario<String>> tarifarioDAO; @TestSubject TarifarioService service = TarifarioService.getTarifarifarioService(); @Test public void guardarHappyPath() { Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(false); tarifarioDAO.guardar(tarifario); EasyMock.replay(tarifarioDAO); service.agregar(fecha, TipoTarifario.AccionesPublicitarias, tarifas); EasyMock.verify(tarifarioDAO); } @Test public void guardarExiste() { Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.replay(tarifarioDAO); service.agregar(fecha, TipoTarifario.AccionesPublicitarias, tarifas); EasyMock.verify(tarifarioDAO); } @Test public void borrarHappyPath() { Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.expect(tarifarioDAO.traerPorFecha(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(tarifario); tarifarioDAO.borrar(tarifario); EasyMock.replay(tarifarioDAO); service.borrar(fecha, TipoTarifario.AccionesPublicitarias); EasyMock.verify(tarifarioDAO); } @Test public void borrarNoExiste(){ Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(false); EasyMock.replay(tarifarioDAO); service.borrar(fecha, TipoTarifario.AccionesPublicitarias); EasyMock.verify(tarifarioDAO); } @Test public void modificarHappyPath() { Date fechaOriginal = new Date(20170206); Map<String, BigDecimal>tarifasOriginal= new HashMap<>(); Date fechaModificacion = new Date(20170206); Tarifario<String>original= new Tarifario<>(tarifasOriginal, fechaOriginal, TipoTarifario.AccionesPublicitarias); Tarifario<String>modificacion= new Tarifario<>(tarifasOriginal, fechaModificacion, TipoTarifario.Tag); original.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.expect(tarifarioDAO.existe(fechaModificacion, TipoTarifario.Tag)).andReturn(false); EasyMock.expect(tarifarioDAO.traerPorFecha(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(original); EasyMock.expect(tarifarioDAO.traerPorFecha(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(original); tarifarioDAO.modificar(original, modificacion); EasyMock.replay(tarifarioDAO); assertEquals(true, service.modificar(fechaOriginal, TipoTarifario.AccionesPublicitarias, tarifasOriginal, fechaModificacion, TipoTarifario.Tag)); EasyMock.verify(tarifarioDAO); } @SuppressWarnings("unused") @Test public void modificarExisteModificacion() { Date fechaOriginal = new Date(20170206); Map<String, BigDecimal>tarifasOriginal= new HashMap<>(); Date fechaModificacion = new Date(20170206); Tarifario<String>original= new Tarifario<>(tarifasOriginal, fechaOriginal, TipoTarifario.AccionesPublicitarias); Tarifario<String>modificacion= new Tarifario<>(tarifasOriginal, fechaModificacion, TipoTarifario.Tag); original.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.expect(tarifarioDAO.existe(fechaModificacion, TipoTarifario.Tag)).andReturn(true); EasyMock.replay(tarifarioDAO); assertEquals(false, service.modificar(fechaOriginal, TipoTarifario.AccionesPublicitarias, tarifasOriginal, fechaModificacion, TipoTarifario.Tag)); EasyMock.verify(tarifarioDAO); } @Test public void modificarNoExisteOriginal() { Date fechaOriginal = new Date(20170206); Map<String, BigDecimal>tarifasOriginal= new HashMap<>(); Date fechaModificacion = new Date(20170206); Tarifario<String>original= new Tarifario<>(tarifasOriginal, fechaOriginal, TipoTarifario.AccionesPublicitarias); original.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(false); EasyMock.replay(tarifarioDAO); assertEquals(false, service.modificar(fechaOriginal, TipoTarifario.AccionesPublicitarias, tarifasOriginal, fechaModificacion, TipoTarifario.Tag)); EasyMock.verify(tarifarioDAO); } }
UTF-8
Java
5,933
java
TestTarifarioService.java
Java
[]
null
[]
package com.EyVdeSW.TP.services; import static org.junit.Assert.*; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.easymock.*; import org.junit.Test; import org.junit.runner.RunWith; import com.EyVdeSW.TP.Daos.TarifarioDAO; import com.EyVdeSW.TP.domainModel.Tarifario; import com.EyVdeSW.TP.domainModel.Tarifario.TipoTarifario; @RunWith(EasyMockRunner.class) public class TestTarifarioService { @Mock TarifarioDAO<Tarifario<String>> tarifarioDAO; @TestSubject TarifarioService service = TarifarioService.getTarifarifarioService(); @Test public void guardarHappyPath() { Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(false); tarifarioDAO.guardar(tarifario); EasyMock.replay(tarifarioDAO); service.agregar(fecha, TipoTarifario.AccionesPublicitarias, tarifas); EasyMock.verify(tarifarioDAO); } @Test public void guardarExiste() { Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.replay(tarifarioDAO); service.agregar(fecha, TipoTarifario.AccionesPublicitarias, tarifas); EasyMock.verify(tarifarioDAO); } @Test public void borrarHappyPath() { Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.expect(tarifarioDAO.traerPorFecha(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(tarifario); tarifarioDAO.borrar(tarifario); EasyMock.replay(tarifarioDAO); service.borrar(fecha, TipoTarifario.AccionesPublicitarias); EasyMock.verify(tarifarioDAO); } @Test public void borrarNoExiste(){ Date fecha = new Date(20170206); Map<String, BigDecimal>tarifas= new HashMap<>(); Tarifario<String>tarifario= new Tarifario<>(tarifas, fecha, TipoTarifario.AccionesPublicitarias); tarifario.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fecha, TipoTarifario.AccionesPublicitarias)).andReturn(false); EasyMock.replay(tarifarioDAO); service.borrar(fecha, TipoTarifario.AccionesPublicitarias); EasyMock.verify(tarifarioDAO); } @Test public void modificarHappyPath() { Date fechaOriginal = new Date(20170206); Map<String, BigDecimal>tarifasOriginal= new HashMap<>(); Date fechaModificacion = new Date(20170206); Tarifario<String>original= new Tarifario<>(tarifasOriginal, fechaOriginal, TipoTarifario.AccionesPublicitarias); Tarifario<String>modificacion= new Tarifario<>(tarifasOriginal, fechaModificacion, TipoTarifario.Tag); original.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.expect(tarifarioDAO.existe(fechaModificacion, TipoTarifario.Tag)).andReturn(false); EasyMock.expect(tarifarioDAO.traerPorFecha(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(original); EasyMock.expect(tarifarioDAO.traerPorFecha(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(original); tarifarioDAO.modificar(original, modificacion); EasyMock.replay(tarifarioDAO); assertEquals(true, service.modificar(fechaOriginal, TipoTarifario.AccionesPublicitarias, tarifasOriginal, fechaModificacion, TipoTarifario.Tag)); EasyMock.verify(tarifarioDAO); } @SuppressWarnings("unused") @Test public void modificarExisteModificacion() { Date fechaOriginal = new Date(20170206); Map<String, BigDecimal>tarifasOriginal= new HashMap<>(); Date fechaModificacion = new Date(20170206); Tarifario<String>original= new Tarifario<>(tarifasOriginal, fechaOriginal, TipoTarifario.AccionesPublicitarias); Tarifario<String>modificacion= new Tarifario<>(tarifasOriginal, fechaModificacion, TipoTarifario.Tag); original.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(true); EasyMock.expect(tarifarioDAO.existe(fechaModificacion, TipoTarifario.Tag)).andReturn(true); EasyMock.replay(tarifarioDAO); assertEquals(false, service.modificar(fechaOriginal, TipoTarifario.AccionesPublicitarias, tarifasOriginal, fechaModificacion, TipoTarifario.Tag)); EasyMock.verify(tarifarioDAO); } @Test public void modificarNoExisteOriginal() { Date fechaOriginal = new Date(20170206); Map<String, BigDecimal>tarifasOriginal= new HashMap<>(); Date fechaModificacion = new Date(20170206); Tarifario<String>original= new Tarifario<>(tarifasOriginal, fechaOriginal, TipoTarifario.AccionesPublicitarias); original.agregarTarifa("Mail", new BigDecimal("20.00")); EasyMock.expect(tarifarioDAO.existe(fechaOriginal, TipoTarifario.AccionesPublicitarias)).andReturn(false); EasyMock.replay(tarifarioDAO); assertEquals(false, service.modificar(fechaOriginal, TipoTarifario.AccionesPublicitarias, tarifasOriginal, fechaModificacion, TipoTarifario.Tag)); EasyMock.verify(tarifarioDAO); } }
5,933
0.766391
0.748188
149
37.81879
36.549873
127
false
false
0
0
0
0
0
0
2.583893
false
false
2
dd86b1188953693ede0683430fcff8bf6a8de6a2
3,530,463,123,618
63152c4f60c3be964e9f4e315ae50cb35a75c555
/mllib/target/java/org/apache/spark/mllib/classification/StreamingLogisticRegressionWithSGD.java
17a357bb9ebf04596ff401cf33a041f00eeb24b2
[ "EPL-1.0", "Classpath-exception-2.0", "LicenseRef-scancode-unicode", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown", "GCC-exception-3.1", "LGPL-2.0-or-later", "CDDL-1.0", "MIT", "CC-BY-SA-3.0", "NAIST-2003", "LGPL-2.1-only", "LicenseRef-scancode-other...
permissive
PowersYang/spark-cn
https://github.com/PowersYang/spark-cn
76c407d774e35d18feb52297c68c65889a75a002
06a0459999131ee14864a69a15746c900e815a14
refs/heads/master
2022-12-11T20:18:37.376000
2020-03-30T09:48:22
2020-03-30T09:48:22
219,248,341
0
0
Apache-2.0
false
2022-12-05T23:46:17
2019-11-03T03:55:17
2020-03-30T09:51:51
2022-12-05T23:46:17
122,973
0
0
13
HTML
false
false
package org.apache.spark.mllib.classification; /** * Train or predict a logistic regression model on streaming data. Training uses * Stochastic Gradient Descent to update the model based on each new batch of * incoming data from a DStream (see <code>LogisticRegressionWithSGD</code> for model equation) * <p> * Each batch of data is assumed to be an RDD of LabeledPoints. * The number of data points per batch can vary, but the number * of features must be constant. An initial weight * vector must be provided. * <p> * Use a builder pattern to construct a streaming logistic regression * analysis in an application, like: * <p> * <pre><code> * val model = new StreamingLogisticRegressionWithSGD() * .setStepSize(0.5) * .setNumIterations(10) * .setInitialWeights(Vectors.dense(...)) * .trainOn(DStream) * </code></pre> */ public class StreamingLogisticRegressionWithSGD extends org.apache.spark.mllib.regression.StreamingLinearAlgorithm<org.apache.spark.mllib.classification.LogisticRegressionModel, org.apache.spark.mllib.classification.LogisticRegressionWithSGD> implements scala.Serializable { // not preceding StreamingLogisticRegressionWithSGD (double stepSize, int numIterations, double miniBatchFraction, double regParam) { throw new RuntimeException(); } /** * Construct a StreamingLogisticRegression object with default parameters: * {stepSize: 0.1, numIterations: 50, miniBatchFraction: 1.0, regParam: 0.0}. * Initial weights must be set before using trainOn or predictOn * (see <code>StreamingLinearAlgorithm</code>) */ public StreamingLogisticRegressionWithSGD () { throw new RuntimeException(); } protected org.apache.spark.mllib.classification.LogisticRegressionWithSGD algorithm () { throw new RuntimeException(); } protected scala.Option<org.apache.spark.mllib.classification.LogisticRegressionModel> model () { throw new RuntimeException(); } /** Set the initial weights. Default: [0.0, 0.0]. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setInitialWeights (org.apache.spark.mllib.linalg.Vector initialWeights) { throw new RuntimeException(); } /** Set the fraction of each batch to use for updates. Default: 1.0. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setMiniBatchFraction (double miniBatchFraction) { throw new RuntimeException(); } /** Set the number of iterations of gradient descent to run per update. Default: 50. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setNumIterations (int numIterations) { throw new RuntimeException(); } /** Set the regularization parameter. Default: 0.0. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setRegParam (double regParam) { throw new RuntimeException(); } /** Set the step size for gradient descent. Default: 0.1. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setStepSize (double stepSize) { throw new RuntimeException(); } }
UTF-8
Java
3,080
java
StreamingLogisticRegressionWithSGD.java
Java
[]
null
[]
package org.apache.spark.mllib.classification; /** * Train or predict a logistic regression model on streaming data. Training uses * Stochastic Gradient Descent to update the model based on each new batch of * incoming data from a DStream (see <code>LogisticRegressionWithSGD</code> for model equation) * <p> * Each batch of data is assumed to be an RDD of LabeledPoints. * The number of data points per batch can vary, but the number * of features must be constant. An initial weight * vector must be provided. * <p> * Use a builder pattern to construct a streaming logistic regression * analysis in an application, like: * <p> * <pre><code> * val model = new StreamingLogisticRegressionWithSGD() * .setStepSize(0.5) * .setNumIterations(10) * .setInitialWeights(Vectors.dense(...)) * .trainOn(DStream) * </code></pre> */ public class StreamingLogisticRegressionWithSGD extends org.apache.spark.mllib.regression.StreamingLinearAlgorithm<org.apache.spark.mllib.classification.LogisticRegressionModel, org.apache.spark.mllib.classification.LogisticRegressionWithSGD> implements scala.Serializable { // not preceding StreamingLogisticRegressionWithSGD (double stepSize, int numIterations, double miniBatchFraction, double regParam) { throw new RuntimeException(); } /** * Construct a StreamingLogisticRegression object with default parameters: * {stepSize: 0.1, numIterations: 50, miniBatchFraction: 1.0, regParam: 0.0}. * Initial weights must be set before using trainOn or predictOn * (see <code>StreamingLinearAlgorithm</code>) */ public StreamingLogisticRegressionWithSGD () { throw new RuntimeException(); } protected org.apache.spark.mllib.classification.LogisticRegressionWithSGD algorithm () { throw new RuntimeException(); } protected scala.Option<org.apache.spark.mllib.classification.LogisticRegressionModel> model () { throw new RuntimeException(); } /** Set the initial weights. Default: [0.0, 0.0]. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setInitialWeights (org.apache.spark.mllib.linalg.Vector initialWeights) { throw new RuntimeException(); } /** Set the fraction of each batch to use for updates. Default: 1.0. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setMiniBatchFraction (double miniBatchFraction) { throw new RuntimeException(); } /** Set the number of iterations of gradient descent to run per update. Default: 50. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setNumIterations (int numIterations) { throw new RuntimeException(); } /** Set the regularization parameter. Default: 0.0. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setRegParam (double regParam) { throw new RuntimeException(); } /** Set the step size for gradient descent. Default: 0.1. */ public org.apache.spark.mllib.classification.StreamingLogisticRegressionWithSGD setStepSize (double stepSize) { throw new RuntimeException(); } }
3,080
0.769481
0.761688
45
67.444443
58.603207
275
false
false
0
0
0
0
0
0
0.444444
false
false
2
c544eb42935bab08dc9f01681a807186a344a45e
23,914,377,964,001
71b4d4f61b0351e8a4406960d2a8cca5b278995e
/src/test/java/br/com/dextra/dextranet/unidade/UnidadeTest.java
95079616b325ee840556bdcf6cac3b69904dcbbf
[]
no_license
dextra/dextranet
https://github.com/dextra/dextranet
0b54495b8121e023a863ac3bb213d4506d107e78
bc54575883fa5e8a49a106ea3065e96b261d653c
refs/heads/master
2021-01-21T12:52:56.880000
2016-03-24T12:10:53
2016-03-24T12:10:53
7,016,884
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.dextra.dextranet.unidade; import org.junit.Assert; import org.junit.Test; import br.com.dextra.teste.TesteIntegracaoBase; import com.google.appengine.api.datastore.Entity; //a heranca eh para poder testar os objetos envolvendo entity public class UnidadeTest extends TesteIntegracaoBase { @Test public void testeConstrutor() { Entity unidadeEntity = new Unidade("campinas").toEntity(); Unidade unidade = new Unidade(unidadeEntity); Assert.assertEquals(unidadeEntity.getProperty(UnidadeFields.id.name()), unidade.getId()); Assert.assertEquals(unidadeEntity.getProperty(UnidadeFields.nome.name()), unidade.getNome()); } @Test public void testeToEntity() { Unidade unidade = new Unidade("campinas"); Entity unidadeEntity = unidade.toEntity(); Assert.assertEquals(unidade.getId(), unidadeEntity.getProperty(UnidadeFields.id.name())); Assert.assertEquals(unidade.getNome(), unidadeEntity.getProperty(UnidadeFields.nome.name())); } }
UTF-8
Java
1,007
java
UnidadeTest.java
Java
[]
null
[]
package br.com.dextra.dextranet.unidade; import org.junit.Assert; import org.junit.Test; import br.com.dextra.teste.TesteIntegracaoBase; import com.google.appengine.api.datastore.Entity; //a heranca eh para poder testar os objetos envolvendo entity public class UnidadeTest extends TesteIntegracaoBase { @Test public void testeConstrutor() { Entity unidadeEntity = new Unidade("campinas").toEntity(); Unidade unidade = new Unidade(unidadeEntity); Assert.assertEquals(unidadeEntity.getProperty(UnidadeFields.id.name()), unidade.getId()); Assert.assertEquals(unidadeEntity.getProperty(UnidadeFields.nome.name()), unidade.getNome()); } @Test public void testeToEntity() { Unidade unidade = new Unidade("campinas"); Entity unidadeEntity = unidade.toEntity(); Assert.assertEquals(unidade.getId(), unidadeEntity.getProperty(UnidadeFields.id.name())); Assert.assertEquals(unidade.getNome(), unidadeEntity.getProperty(UnidadeFields.nome.name())); } }
1,007
0.751738
0.751738
32
29.46875
31.827646
95
false
false
0
0
0
0
0
0
1.21875
false
false
2
c3f4c49acf817feeec2536fb448b9e5499fe825d
23,914,377,963,969
c8b6e7531db33ccbb547194668ad0b6d2cffbb65
/java-se-base-parent/model-io-stream/src/main/java/com/io/stream/IoParam.java
4e375663378fd54038bdac6d7781aacda8e45fed
[ "Apache-2.0" ]
permissive
cicadasmile/java-base-parent
https://github.com/cicadasmile/java-base-parent
fe7bcd568700fbe11561d0e0584283c870e25905
3b3e7f9e0543780a83f37c1ed8b95ff62f529b6e
refs/heads/master
2022-06-25T06:09:30.435000
2022-02-22T14:54:25
2022-02-22T14:54:25
226,533,015
39
24
Apache-2.0
false
2022-06-21T02:29:58
2019-12-07T15:12:27
2022-06-06T07:26:15
2022-06-21T02:29:55
197
35
25
8
Java
false
false
package com.io.stream; public class IoParam { public static final String BASE_PATH = "基础路径" ; }
UTF-8
Java
111
java
IoParam.java
Java
[]
null
[]
package com.io.stream; public class IoParam { public static final String BASE_PATH = "基础路径" ; }
111
0.68932
0.68932
7
13.714286
17.942083
51
false
false
0
0
0
0
0
0
0.285714
false
false
2
e48cbbf70d98dcca6e0af68d8fdee52b9e8560d6
28,948,079,635,749
fa0cddbb3d04f7ff14ab2c1b6a04daafc4cabef6
/src/main/java/com/zspace/spring/cache/service/CacheKeyGenerator.java
6432bcfb9f420281dbe56778cb8398808f0699da
[]
no_license
jack-wqing/common-spring-cache
https://github.com/jack-wqing/common-spring-cache
7c2c5fa16fdae9ddc73b6576796ca27478bdd47f
132350b5300d5394c8853dfa55e8186378881307
refs/heads/master
2022-11-23T17:42:07.910000
2019-12-24T12:53:51
2019-12-24T12:53:51
229,940,888
0
0
null
false
2022-11-16T12:14:35
2019-12-24T12:48:28
2019-12-24T12:53:54
2022-11-16T12:14:33
17
0
0
3
null
false
false
package com.zspace.spring.cache.service; import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import com.alibaba.fastjson.JSON; public class CacheKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder key = new StringBuilder(); key.append(target.getClass().getName()).append(".").append(method.getName()).append(":"); if (params.length == 0) { return key.append(0).toString(); } key.append(JSON.toJSONString(params)); return MD5Util.GetMD5Code(key.toString()); } }
UTF-8
Java
606
java
CacheKeyGenerator.java
Java
[]
null
[]
package com.zspace.spring.cache.service; import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import com.alibaba.fastjson.JSON; public class CacheKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder key = new StringBuilder(); key.append(target.getClass().getName()).append(".").append(method.getName()).append(":"); if (params.length == 0) { return key.append(0).toString(); } key.append(JSON.toJSONString(params)); return MD5Util.GetMD5Code(key.toString()); } }
606
0.745875
0.739274
20
29.35
26.422102
91
true
false
0
0
0
0
0
0
1.45
false
false
2
7015d1edc530cf29e480d804cbef07d944040c37
22,660,247,456,728
adcdd5d02646a77c411f342bc693e1bef6793a39
/2020 Senior Year/Programming Concepts/PLC Interpreter Project/src/test/java/plc.interpreter/LexerTests.java
bfbf4708339fe86c10d754d1477d7dc78f91aeeb
[]
no_license
Koby1997/UF-Classes
https://github.com/Koby1997/UF-Classes
15dc5714584e56b23bdfc3f187ca44c7a10d2381
c50e461fcd5249106398c33a65b3248edece9198
refs/heads/master
2023-03-12T16:42:20.706000
2021-03-02T21:12:35
2021-03-02T21:12:35
343,909,056
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package plc.interpreter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * Standard JUnit5 parameterized tests. See the RegexTests file from part 1 for * more information. */ final class LexerTests { @ParameterizedTest @MethodSource void testIdentifier(String input, boolean success) { test(input, Token.Type.IDENTIFIER, success); } private static Stream<Arguments> testIdentifier() { return Stream.of( Arguments.of("getName", true), Arguments.of("is-empty?", true), Arguments.of("<=>", true), Arguments.of("42=life", false), Arguments.of("why,are,there,commas,", false), Arguments.of("a", true) ); } @ParameterizedTest @MethodSource void testNumber(String input, boolean success) { test(input, Token.Type.NUMBER, success); } private static Stream<Arguments> testNumber() { return Stream.of( Arguments.of("1", true), Arguments.of("-1.0", true), Arguments.of("007.000", true), Arguments.of("1.", false), Arguments.of(".5", false) ); } @ParameterizedTest @MethodSource void testString(String input, boolean success) { test(input, Token.Type.STRING, success); } private static Stream<Arguments> testString() { return Stream.of( Arguments.of("\"\"", true), Arguments.of("\"abc\"", true), Arguments.of("\"Hello,\\nWorld\"", true), Arguments.of("\"unterminated", false), Arguments.of("\"invalid\\escape\"", false) ); } @ParameterizedTest @MethodSource void testOperator(String input, boolean success) { test(input, Token.Type.OPERATOR, success); } private static Stream<Arguments> testOperator() { return Stream.of( Arguments.of("(", true), Arguments.of("#", true), Arguments.of(" ", false), Arguments.of("\t", false) ); } @Test void testExample1() { String input = "(+ 1 -2.0)"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "(", 0), new Token(Token.Type.IDENTIFIER, "+", 1), new Token(Token.Type.NUMBER, "1", 3), new Token(Token.Type.NUMBER, "-2.0", 5), new Token(Token.Type.OPERATOR, ")", 9) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample2() { String input = "(print \"Hello, World!\")"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "(", 0), new Token(Token.Type.IDENTIFIER, "print", 1), new Token(Token.Type.STRING, "\"Hello, World!\"", 7), new Token(Token.Type.OPERATOR, ")", 22) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample3() { String input = "(let [x 10] (assert-equals? x 10))"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "(", 0), new Token(Token.Type.IDENTIFIER, "let", 1), new Token(Token.Type.OPERATOR, "[", 5), new Token(Token.Type.IDENTIFIER, "x", 6), new Token(Token.Type.NUMBER, "10", 8), new Token(Token.Type.OPERATOR, "]", 10), new Token(Token.Type.OPERATOR, "(", 12), new Token(Token.Type.IDENTIFIER, "assert-equals?", 13), new Token(Token.Type.IDENTIFIER, "x", 28), new Token(Token.Type.NUMBER, "10", 30), new Token(Token.Type.OPERATOR, ")", 32), new Token(Token.Type.OPERATOR, ")", 33) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample4() { String input = "abc123"; List<Token> expected = Arrays.asList( new Token(Token.Type.IDENTIFIER, "abc123", 0) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample5() { String input = "@.#"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "@", 0), new Token(Token.Type.OPERATOR, ".", 1), new Token(Token.Type.OPERATOR, "#", 2) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample6() { String input = "1.2.3"; List<Token> expected = Arrays.asList( new Token(Token.Type.NUMBER, "1.2", 0), new Token(Token.Type.IDENTIFIER, ".3", 3) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample7() { String input = "#sql { SELECT * FROM ${table} }"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "#", 0), new Token(Token.Type.IDENTIFIER, "sql", 1), new Token(Token.Type.OPERATOR, "{", 5), new Token(Token.Type.IDENTIFIER, "SELECT", 7), new Token(Token.Type.IDENTIFIER, "*", 14), new Token(Token.Type.IDENTIFIER, "FROM", 16), new Token(Token.Type.OPERATOR, "$", 21), new Token(Token.Type.OPERATOR, "{", 22), new Token(Token.Type.IDENTIFIER, "table", 23), new Token(Token.Type.OPERATOR, "}", 28), new Token(Token.Type.OPERATOR, "}", 30) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample8() { String input = "."; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, ".", 0) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @ParameterizedTest @MethodSource("plc.interpreter.LexerTests#testPeekAndMatch") void testPeek(String test, String input, String[] patterns, boolean matches) { Lexer lexer = new Lexer(input); Assertions.assertEquals(matches, lexer.peek(patterns)); Assertions.assertEquals(0, lexer.chars.index); } @ParameterizedTest @MethodSource("plc.interpreter.LexerTests#testPeekAndMatch") void testMatch(String test, String input, String[] patterns, boolean matches) { Lexer lexer = new Lexer(input); Assertions.assertEquals(matches, lexer.match(patterns)); Assertions.assertEquals(matches ? patterns.length : 0, lexer.chars.index); } private static Stream<Arguments> testPeekAndMatch() { return Stream.of( Arguments.of("Single Char Input, Single Char Pattern", "a", new String[] {"a"}, true), Arguments.of("Multiple Char Input, Single Char Pattern", "abc", new String[] {"a"}, true), Arguments.of("Single Char Input, Multiple Char Pattern", "a", new String[] {"a", "b", "c"}, false), Arguments.of("Multiple Char Input, Multiple Char Pattern", "abc", new String[] {"a"}, true), Arguments.of("Single Char Input, Char Class Pattern Success", "a", new String[] {"[a-z]"}, true), Arguments.of("Single Char Input, Char Class Pattern Failure", "@", new String[] {"[a-z]"}, false), Arguments.of("Multiple Char Input, Mixed Pattern Success", "cat", new String[] {"c", "[aeiou]", "t"}, true), Arguments.of("Multiple Char Input, Mixed Pattern Failure 1", "cyt", new String[] {"c", "[aeiou]", "t"}, false), Arguments.of("Multiple Char Input, Mixed Pattern Failure 2", "cow", new String[] {"c", "[aeiou]", "t"}, false), Arguments.of("End of Input", "eo", new String[] {"e", "o", "[fi]"}, false) ); } @Test void testCharStream() { Lexer lexer = new Lexer("abc 123"); lexer.chars.advance(); lexer.chars.advance(); lexer.chars.advance(); Assertions.assertEquals(new Token(Token.Type.IDENTIFIER, "abc", 0), lexer.chars.emit(Token.Type.IDENTIFIER)); lexer.chars.advance(); lexer.chars.reset(); Assertions.assertEquals(0, lexer.chars.length); lexer.chars.advance(); lexer.chars.advance(); lexer.chars.advance(); Assertions.assertEquals(new Token(Token.Type.NUMBER, "123", 4), lexer.chars.emit(Token.Type.NUMBER)); Assertions.assertFalse(lexer.chars.has(0)); } /** * Tests that the input lexes to the (single) expected token if successful, * else throws a {@link ParseException} otherwise. */ private static void test(String input, Token.Type expected, boolean success) { try { if (success) { Assertions.assertEquals(Arrays.asList(new Token(expected, input, 0)), Lexer.lex(input)); } else { Assertions.assertNotEquals(Arrays.asList(new Token(expected, input, 0)), Lexer.lex(input)); } } catch (ParseException e) { Assertions.assertFalse(success, e.getMessage()); } } }
UTF-8
Java
9,556
java
LexerTests.java
Java
[]
null
[]
package plc.interpreter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * Standard JUnit5 parameterized tests. See the RegexTests file from part 1 for * more information. */ final class LexerTests { @ParameterizedTest @MethodSource void testIdentifier(String input, boolean success) { test(input, Token.Type.IDENTIFIER, success); } private static Stream<Arguments> testIdentifier() { return Stream.of( Arguments.of("getName", true), Arguments.of("is-empty?", true), Arguments.of("<=>", true), Arguments.of("42=life", false), Arguments.of("why,are,there,commas,", false), Arguments.of("a", true) ); } @ParameterizedTest @MethodSource void testNumber(String input, boolean success) { test(input, Token.Type.NUMBER, success); } private static Stream<Arguments> testNumber() { return Stream.of( Arguments.of("1", true), Arguments.of("-1.0", true), Arguments.of("007.000", true), Arguments.of("1.", false), Arguments.of(".5", false) ); } @ParameterizedTest @MethodSource void testString(String input, boolean success) { test(input, Token.Type.STRING, success); } private static Stream<Arguments> testString() { return Stream.of( Arguments.of("\"\"", true), Arguments.of("\"abc\"", true), Arguments.of("\"Hello,\\nWorld\"", true), Arguments.of("\"unterminated", false), Arguments.of("\"invalid\\escape\"", false) ); } @ParameterizedTest @MethodSource void testOperator(String input, boolean success) { test(input, Token.Type.OPERATOR, success); } private static Stream<Arguments> testOperator() { return Stream.of( Arguments.of("(", true), Arguments.of("#", true), Arguments.of(" ", false), Arguments.of("\t", false) ); } @Test void testExample1() { String input = "(+ 1 -2.0)"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "(", 0), new Token(Token.Type.IDENTIFIER, "+", 1), new Token(Token.Type.NUMBER, "1", 3), new Token(Token.Type.NUMBER, "-2.0", 5), new Token(Token.Type.OPERATOR, ")", 9) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample2() { String input = "(print \"Hello, World!\")"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "(", 0), new Token(Token.Type.IDENTIFIER, "print", 1), new Token(Token.Type.STRING, "\"Hello, World!\"", 7), new Token(Token.Type.OPERATOR, ")", 22) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample3() { String input = "(let [x 10] (assert-equals? x 10))"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "(", 0), new Token(Token.Type.IDENTIFIER, "let", 1), new Token(Token.Type.OPERATOR, "[", 5), new Token(Token.Type.IDENTIFIER, "x", 6), new Token(Token.Type.NUMBER, "10", 8), new Token(Token.Type.OPERATOR, "]", 10), new Token(Token.Type.OPERATOR, "(", 12), new Token(Token.Type.IDENTIFIER, "assert-equals?", 13), new Token(Token.Type.IDENTIFIER, "x", 28), new Token(Token.Type.NUMBER, "10", 30), new Token(Token.Type.OPERATOR, ")", 32), new Token(Token.Type.OPERATOR, ")", 33) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample4() { String input = "abc123"; List<Token> expected = Arrays.asList( new Token(Token.Type.IDENTIFIER, "abc123", 0) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample5() { String input = "@.#"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "@", 0), new Token(Token.Type.OPERATOR, ".", 1), new Token(Token.Type.OPERATOR, "#", 2) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample6() { String input = "1.2.3"; List<Token> expected = Arrays.asList( new Token(Token.Type.NUMBER, "1.2", 0), new Token(Token.Type.IDENTIFIER, ".3", 3) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample7() { String input = "#sql { SELECT * FROM ${table} }"; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, "#", 0), new Token(Token.Type.IDENTIFIER, "sql", 1), new Token(Token.Type.OPERATOR, "{", 5), new Token(Token.Type.IDENTIFIER, "SELECT", 7), new Token(Token.Type.IDENTIFIER, "*", 14), new Token(Token.Type.IDENTIFIER, "FROM", 16), new Token(Token.Type.OPERATOR, "$", 21), new Token(Token.Type.OPERATOR, "{", 22), new Token(Token.Type.IDENTIFIER, "table", 23), new Token(Token.Type.OPERATOR, "}", 28), new Token(Token.Type.OPERATOR, "}", 30) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @Test void testExample8() { String input = "."; List<Token> expected = Arrays.asList( new Token(Token.Type.OPERATOR, ".", 0) ); Assertions.assertEquals(expected, Lexer.lex(input)); } @ParameterizedTest @MethodSource("plc.interpreter.LexerTests#testPeekAndMatch") void testPeek(String test, String input, String[] patterns, boolean matches) { Lexer lexer = new Lexer(input); Assertions.assertEquals(matches, lexer.peek(patterns)); Assertions.assertEquals(0, lexer.chars.index); } @ParameterizedTest @MethodSource("plc.interpreter.LexerTests#testPeekAndMatch") void testMatch(String test, String input, String[] patterns, boolean matches) { Lexer lexer = new Lexer(input); Assertions.assertEquals(matches, lexer.match(patterns)); Assertions.assertEquals(matches ? patterns.length : 0, lexer.chars.index); } private static Stream<Arguments> testPeekAndMatch() { return Stream.of( Arguments.of("Single Char Input, Single Char Pattern", "a", new String[] {"a"}, true), Arguments.of("Multiple Char Input, Single Char Pattern", "abc", new String[] {"a"}, true), Arguments.of("Single Char Input, Multiple Char Pattern", "a", new String[] {"a", "b", "c"}, false), Arguments.of("Multiple Char Input, Multiple Char Pattern", "abc", new String[] {"a"}, true), Arguments.of("Single Char Input, Char Class Pattern Success", "a", new String[] {"[a-z]"}, true), Arguments.of("Single Char Input, Char Class Pattern Failure", "@", new String[] {"[a-z]"}, false), Arguments.of("Multiple Char Input, Mixed Pattern Success", "cat", new String[] {"c", "[aeiou]", "t"}, true), Arguments.of("Multiple Char Input, Mixed Pattern Failure 1", "cyt", new String[] {"c", "[aeiou]", "t"}, false), Arguments.of("Multiple Char Input, Mixed Pattern Failure 2", "cow", new String[] {"c", "[aeiou]", "t"}, false), Arguments.of("End of Input", "eo", new String[] {"e", "o", "[fi]"}, false) ); } @Test void testCharStream() { Lexer lexer = new Lexer("abc 123"); lexer.chars.advance(); lexer.chars.advance(); lexer.chars.advance(); Assertions.assertEquals(new Token(Token.Type.IDENTIFIER, "abc", 0), lexer.chars.emit(Token.Type.IDENTIFIER)); lexer.chars.advance(); lexer.chars.reset(); Assertions.assertEquals(0, lexer.chars.length); lexer.chars.advance(); lexer.chars.advance(); lexer.chars.advance(); Assertions.assertEquals(new Token(Token.Type.NUMBER, "123", 4), lexer.chars.emit(Token.Type.NUMBER)); Assertions.assertFalse(lexer.chars.has(0)); } /** * Tests that the input lexes to the (single) expected token if successful, * else throws a {@link ParseException} otherwise. */ private static void test(String input, Token.Type expected, boolean success) { try { if (success) { Assertions.assertEquals(Arrays.asList(new Token(expected, input, 0)), Lexer.lex(input)); } else { Assertions.assertNotEquals(Arrays.asList(new Token(expected, input, 0)), Lexer.lex(input)); } } catch (ParseException e) { Assertions.assertFalse(success, e.getMessage()); } } }
9,556
0.562892
0.55044
253
36.770752
29.13365
127
false
false
0
0
0
0
0
0
1.268775
false
false
2
ff24fb537cb80c6dd68b5d7c48335438b859888b
26,663,157,030,025
b2759bbf00326177d75d67f803c30132e07e6fbe
/Step4/output/MicroParserLexer.java
687d0346717af11828481c57be8880cd699c55a8
[]
no_license
vineethh91/ECE468-Compiler
https://github.com/vineethh91/ECE468-Compiler
8cee1f82867495cbed72ceb840af383f1081249c
d4acae66419bcd9b18c96221f28733d42ff79c5d
refs/heads/master
2021-01-19T05:46:48.190000
2013-03-21T23:25:19
2013-03-21T23:25:19
8,940,872
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// $ANTLR 3.4 MicroParser.g 2012-10-14 00:46:37 import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked"}) public class MicroParserLexer extends Lexer { public static final int EOF=-1; public static final int T__17=17; public static final int T__18=18; public static final int T__19=19; public static final int T__20=20; public static final int T__21=21; public static final int T__22=22; public static final int T__23=23; public static final int T__24=24; public static final int T__25=25; public static final int T__26=26; public static final int T__27=27; public static final int T__28=28; public static final int T__29=29; public static final int T__30=30; public static final int T__31=31; public static final int T__32=32; public static final int T__33=33; public static final int T__34=34; public static final int T__35=35; public static final int T__36=36; public static final int T__37=37; public static final int T__38=38; public static final int T__39=39; public static final int T__40=40; public static final int T__41=41; public static final int T__42=42; public static final int T__43=43; public static final int T__44=44; public static final int T__45=45; public static final int T__46=46; public static final int COMMENT=4; public static final int ESC_SEQ=5; public static final int EXPONENT=6; public static final int FLOATLITERAL=7; public static final int HEX_DIGIT=8; public static final int IDENTIFIER=9; public static final int INTLITERAL=10; public static final int KEYWORD=11; public static final int OCTAL_ESC=12; public static final int OPERATORS=13; public static final int STRINGLIETRAL=14; public static final int UNICODE_ESC=15; public static final int WHITESPACE=16; // delegates // delegators public Lexer[] getDelegates() { return new Lexer[] {}; } public MicroParserLexer() {} public MicroParserLexer(CharStream input) { this(input, new RecognizerSharedState()); } public MicroParserLexer(CharStream input, RecognizerSharedState state) { super(input,state); } public String getGrammarFileName() { return "MicroParser.g"; } // $ANTLR start "T__17" public final void mT__17() throws RecognitionException { try { int _type = T__17; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:7:7: ( '!=' ) // MicroParser.g:7:9: '!=' { match("!="); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__17" // $ANTLR start "T__18" public final void mT__18() throws RecognitionException { try { int _type = T__18; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:8:7: ( '(' ) // MicroParser.g:8:9: '(' { match('('); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__18" // $ANTLR start "T__19" public final void mT__19() throws RecognitionException { try { int _type = T__19; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:9:7: ( ')' ) // MicroParser.g:9:9: ')' { match(')'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__19" // $ANTLR start "T__20" public final void mT__20() throws RecognitionException { try { int _type = T__20; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:10:7: ( '*' ) // MicroParser.g:10:9: '*' { match('*'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__20" // $ANTLR start "T__21" public final void mT__21() throws RecognitionException { try { int _type = T__21; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:11:7: ( '+' ) // MicroParser.g:11:9: '+' { match('+'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__21" // $ANTLR start "T__22" public final void mT__22() throws RecognitionException { try { int _type = T__22; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:12:7: ( ',' ) // MicroParser.g:12:9: ',' { match(','); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__22" // $ANTLR start "T__23" public final void mT__23() throws RecognitionException { try { int _type = T__23; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:13:7: ( '-' ) // MicroParser.g:13:9: '-' { match('-'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__23" // $ANTLR start "T__24" public final void mT__24() throws RecognitionException { try { int _type = T__24; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:14:7: ( '/' ) // MicroParser.g:14:9: '/' { match('/'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__24" // $ANTLR start "T__25" public final void mT__25() throws RecognitionException { try { int _type = T__25; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:15:7: ( ':=' ) // MicroParser.g:15:9: ':=' { match(":="); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__25" // $ANTLR start "T__26" public final void mT__26() throws RecognitionException { try { int _type = T__26; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:16:7: ( ';' ) // MicroParser.g:16:9: ';' { match(';'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__26" // $ANTLR start "T__27" public final void mT__27() throws RecognitionException { try { int _type = T__27; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:17:7: ( '<' ) // MicroParser.g:17:9: '<' { match('<'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__27" // $ANTLR start "T__28" public final void mT__28() throws RecognitionException { try { int _type = T__28; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:18:7: ( '=' ) // MicroParser.g:18:9: '=' { match('='); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__28" // $ANTLR start "T__29" public final void mT__29() throws RecognitionException { try { int _type = T__29; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:19:7: ( '>' ) // MicroParser.g:19:9: '>' { match('>'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__29" // $ANTLR start "T__30" public final void mT__30() throws RecognitionException { try { int _type = T__30; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:20:7: ( 'BEGIN' ) // MicroParser.g:20:9: 'BEGIN' { match("BEGIN"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__30" // $ANTLR start "T__31" public final void mT__31() throws RecognitionException { try { int _type = T__31; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:21:7: ( 'ELSE' ) // MicroParser.g:21:9: 'ELSE' { match("ELSE"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__31" // $ANTLR start "T__32" public final void mT__32() throws RecognitionException { try { int _type = T__32; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:22:7: ( 'END' ) // MicroParser.g:22:9: 'END' { match("END"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__32" // $ANTLR start "T__33" public final void mT__33() throws RecognitionException { try { int _type = T__33; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:23:7: ( 'ENDIF' ) // MicroParser.g:23:9: 'ENDIF' { match("ENDIF"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__33" // $ANTLR start "T__34" public final void mT__34() throws RecognitionException { try { int _type = T__34; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:24:7: ( 'FLOAT' ) // MicroParser.g:24:9: 'FLOAT' { match("FLOAT"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__34" // $ANTLR start "T__35" public final void mT__35() throws RecognitionException { try { int _type = T__35; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:25:7: ( 'FUNCTION' ) // MicroParser.g:25:9: 'FUNCTION' { match("FUNCTION"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__35" // $ANTLR start "T__36" public final void mT__36() throws RecognitionException { try { int _type = T__36; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:26:7: ( 'IF' ) // MicroParser.g:26:9: 'IF' { match("IF"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__36" // $ANTLR start "T__37" public final void mT__37() throws RecognitionException { try { int _type = T__37; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:27:7: ( 'INT' ) // MicroParser.g:27:9: 'INT' { match("INT"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__37" // $ANTLR start "T__38" public final void mT__38() throws RecognitionException { try { int _type = T__38; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:28:7: ( 'PROGRAM' ) // MicroParser.g:28:9: 'PROGRAM' { match("PROGRAM"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__38" // $ANTLR start "T__39" public final void mT__39() throws RecognitionException { try { int _type = T__39; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:29:7: ( 'READ' ) // MicroParser.g:29:9: 'READ' { match("READ"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__39" // $ANTLR start "T__40" public final void mT__40() throws RecognitionException { try { int _type = T__40; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:30:7: ( 'REPEAT' ) // MicroParser.g:30:9: 'REPEAT' { match("REPEAT"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__40" // $ANTLR start "T__41" public final void mT__41() throws RecognitionException { try { int _type = T__41; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:31:7: ( 'RETURN' ) // MicroParser.g:31:9: 'RETURN' { match("RETURN"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__41" // $ANTLR start "T__42" public final void mT__42() throws RecognitionException { try { int _type = T__42; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:32:7: ( 'STRING' ) // MicroParser.g:32:9: 'STRING' { match("STRING"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__42" // $ANTLR start "T__43" public final void mT__43() throws RecognitionException { try { int _type = T__43; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:33:7: ( 'THEN' ) // MicroParser.g:33:9: 'THEN' { match("THEN"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__43" // $ANTLR start "T__44" public final void mT__44() throws RecognitionException { try { int _type = T__44; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:34:7: ( 'UNTIL' ) // MicroParser.g:34:9: 'UNTIL' { match("UNTIL"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__44" // $ANTLR start "T__45" public final void mT__45() throws RecognitionException { try { int _type = T__45; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:35:7: ( 'VOID' ) // MicroParser.g:35:9: 'VOID' { match("VOID"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__45" // $ANTLR start "T__46" public final void mT__46() throws RecognitionException { try { int _type = T__46; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:36:7: ( 'WRITE' ) // MicroParser.g:36:9: 'WRITE' { match("WRITE"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__46" // $ANTLR start "KEYWORD" public final void mKEYWORD() throws RecognitionException { try { int _type = KEYWORD; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:192:9: ( ( 'PROGRAM' ) | ( 'BEGIN' ) | ( 'FUNCTION' ) | ( 'END' ) | ( 'READ' ) | ( 'WRITE' ) | ( 'IF' ) | ( 'THEN' ) | ( 'ELSE' ) | ( 'ENDIF' ) | ( 'REPEAT' ) | ( 'UNTIL' ) | ( 'CONTINUE' ) | ( 'BREAK' ) | ( 'RETURN' ) | ( 'INT' ) | ( 'VOID' ) | ( 'STRING' ) | ( 'FLOAT' ) ) int alt1=19; switch ( input.LA(1) ) { case 'P': { alt1=1; } break; case 'B': { int LA1_2 = input.LA(2); if ( (LA1_2=='E') ) { alt1=2; } else if ( (LA1_2=='R') ) { alt1=14; } else { NoViableAltException nvae = new NoViableAltException("", 1, 2, input); throw nvae; } } break; case 'F': { int LA1_3 = input.LA(2); if ( (LA1_3=='U') ) { alt1=3; } else if ( (LA1_3=='L') ) { alt1=19; } else { NoViableAltException nvae = new NoViableAltException("", 1, 3, input); throw nvae; } } break; case 'E': { int LA1_4 = input.LA(2); if ( (LA1_4=='N') ) { int LA1_17 = input.LA(3); if ( (LA1_17=='D') ) { int LA1_22 = input.LA(4); if ( (LA1_22=='I') ) { alt1=10; } else { alt1=4; } } else { NoViableAltException nvae = new NoViableAltException("", 1, 17, input); throw nvae; } } else if ( (LA1_4=='L') ) { alt1=9; } else { NoViableAltException nvae = new NoViableAltException("", 1, 4, input); throw nvae; } } break; case 'R': { int LA1_5 = input.LA(2); if ( (LA1_5=='E') ) { switch ( input.LA(3) ) { case 'A': { alt1=5; } break; case 'P': { alt1=11; } break; case 'T': { alt1=15; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 19, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 1, 5, input); throw nvae; } } break; case 'W': { alt1=6; } break; case 'I': { int LA1_7 = input.LA(2); if ( (LA1_7=='F') ) { alt1=7; } else if ( (LA1_7=='N') ) { alt1=16; } else { NoViableAltException nvae = new NoViableAltException("", 1, 7, input); throw nvae; } } break; case 'T': { alt1=8; } break; case 'U': { alt1=12; } break; case 'C': { alt1=13; } break; case 'V': { alt1=17; } break; case 'S': { alt1=18; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 0, input); throw nvae; } switch (alt1) { case 1 : // MicroParser.g:192:11: ( 'PROGRAM' ) { // MicroParser.g:192:11: ( 'PROGRAM' ) // MicroParser.g:192:12: 'PROGRAM' { match("PROGRAM"); } } break; case 2 : // MicroParser.g:192:25: ( 'BEGIN' ) { // MicroParser.g:192:25: ( 'BEGIN' ) // MicroParser.g:192:26: 'BEGIN' { match("BEGIN"); } } break; case 3 : // MicroParser.g:192:37: ( 'FUNCTION' ) { // MicroParser.g:192:37: ( 'FUNCTION' ) // MicroParser.g:192:38: 'FUNCTION' { match("FUNCTION"); } } break; case 4 : // MicroParser.g:192:52: ( 'END' ) { // MicroParser.g:192:52: ( 'END' ) // MicroParser.g:192:53: 'END' { match("END"); } } break; case 5 : // MicroParser.g:192:62: ( 'READ' ) { // MicroParser.g:192:62: ( 'READ' ) // MicroParser.g:192:63: 'READ' { match("READ"); } } break; case 6 : // MicroParser.g:192:73: ( 'WRITE' ) { // MicroParser.g:192:73: ( 'WRITE' ) // MicroParser.g:192:74: 'WRITE' { match("WRITE"); } } break; case 7 : // MicroParser.g:193:4: ( 'IF' ) { // MicroParser.g:193:4: ( 'IF' ) // MicroParser.g:193:5: 'IF' { match("IF"); } } break; case 8 : // MicroParser.g:193:13: ( 'THEN' ) { // MicroParser.g:193:13: ( 'THEN' ) // MicroParser.g:193:14: 'THEN' { match("THEN"); } } break; case 9 : // MicroParser.g:193:24: ( 'ELSE' ) { // MicroParser.g:193:24: ( 'ELSE' ) // MicroParser.g:193:25: 'ELSE' { match("ELSE"); } } break; case 10 : // MicroParser.g:193:35: ( 'ENDIF' ) { // MicroParser.g:193:35: ( 'ENDIF' ) // MicroParser.g:193:36: 'ENDIF' { match("ENDIF"); } } break; case 11 : // MicroParser.g:193:47: ( 'REPEAT' ) { // MicroParser.g:193:47: ( 'REPEAT' ) // MicroParser.g:193:48: 'REPEAT' { match("REPEAT"); } } break; case 12 : // MicroParser.g:193:60: ( 'UNTIL' ) { // MicroParser.g:193:60: ( 'UNTIL' ) // MicroParser.g:193:61: 'UNTIL' { match("UNTIL"); } } break; case 13 : // MicroParser.g:194:4: ( 'CONTINUE' ) { // MicroParser.g:194:4: ( 'CONTINUE' ) // MicroParser.g:194:5: 'CONTINUE' { match("CONTINUE"); } } break; case 14 : // MicroParser.g:194:19: ( 'BREAK' ) { // MicroParser.g:194:19: ( 'BREAK' ) // MicroParser.g:194:20: 'BREAK' { match("BREAK"); } } break; case 15 : // MicroParser.g:194:31: ( 'RETURN' ) { // MicroParser.g:194:31: ( 'RETURN' ) // MicroParser.g:194:32: 'RETURN' { match("RETURN"); } } break; case 16 : // MicroParser.g:194:44: ( 'INT' ) { // MicroParser.g:194:44: ( 'INT' ) // MicroParser.g:194:45: 'INT' { match("INT"); } } break; case 17 : // MicroParser.g:194:54: ( 'VOID' ) { // MicroParser.g:194:54: ( 'VOID' ) // MicroParser.g:194:55: 'VOID' { match("VOID"); } } break; case 18 : // MicroParser.g:194:65: ( 'STRING' ) { // MicroParser.g:194:65: ( 'STRING' ) // MicroParser.g:194:66: 'STRING' { match("STRING"); } } break; case 19 : // MicroParser.g:194:78: ( 'FLOAT' ) { // MicroParser.g:194:78: ( 'FLOAT' ) // MicroParser.g:194:79: 'FLOAT' { match("FLOAT"); } } break; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "KEYWORD" // $ANTLR start "IDENTIFIER" public final void mIDENTIFIER() throws RecognitionException { try { int _type = IDENTIFIER; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:197:13: ( ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* ) // MicroParser.g:197:15: ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* { if ( (input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } // MicroParser.g:197:39: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* loop2: do { int alt2=2; int LA2_0 = input.LA(1); if ( ((LA2_0 >= '0' && LA2_0 <= '9')||(LA2_0 >= 'A' && LA2_0 <= 'Z')||LA2_0=='_'||(LA2_0 >= 'a' && LA2_0 <= 'z')) ) { alt2=1; } switch (alt2) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop2; } } while (true); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "IDENTIFIER" // $ANTLR start "INTLITERAL" public final void mINTLITERAL() throws RecognitionException { try { int _type = INTLITERAL; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:200:12: ( ( '0' .. '9' )+ ) // MicroParser.g:200:14: ( '0' .. '9' )+ { // MicroParser.g:200:14: ( '0' .. '9' )+ int cnt3=0; loop3: do { int alt3=2; int LA3_0 = input.LA(1); if ( ((LA3_0 >= '0' && LA3_0 <= '9')) ) { alt3=1; } switch (alt3) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt3 >= 1 ) break loop3; EarlyExitException eee = new EarlyExitException(3, input); throw eee; } cnt3++; } while (true); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "INTLITERAL" // $ANTLR start "FLOATLITERAL" public final void mFLOATLITERAL() throws RecognitionException { try { int _type = FLOATLITERAL; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:204:5: ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( EXPONENT )? | '.' ( '0' .. '9' )+ ( EXPONENT )? | ( '0' .. '9' )+ EXPONENT ) int alt10=3; alt10 = dfa10.predict(input); switch (alt10) { case 1 : // MicroParser.g:204:9: ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( EXPONENT )? { // MicroParser.g:204:9: ( '0' .. '9' )+ int cnt4=0; loop4: do { int alt4=2; int LA4_0 = input.LA(1); if ( ((LA4_0 >= '0' && LA4_0 <= '9')) ) { alt4=1; } switch (alt4) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt4 >= 1 ) break loop4; EarlyExitException eee = new EarlyExitException(4, input); throw eee; } cnt4++; } while (true); match('.'); // MicroParser.g:204:25: ( '0' .. '9' )* loop5: do { int alt5=2; int LA5_0 = input.LA(1); if ( ((LA5_0 >= '0' && LA5_0 <= '9')) ) { alt5=1; } switch (alt5) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop5; } } while (true); // MicroParser.g:204:37: ( EXPONENT )? int alt6=2; int LA6_0 = input.LA(1); if ( (LA6_0=='E'||LA6_0=='e') ) { alt6=1; } switch (alt6) { case 1 : // MicroParser.g:204:37: EXPONENT { mEXPONENT(); } break; } } break; case 2 : // MicroParser.g:205:9: '.' ( '0' .. '9' )+ ( EXPONENT )? { match('.'); // MicroParser.g:205:13: ( '0' .. '9' )+ int cnt7=0; loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( ((LA7_0 >= '0' && LA7_0 <= '9')) ) { alt7=1; } switch (alt7) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt7 >= 1 ) break loop7; EarlyExitException eee = new EarlyExitException(7, input); throw eee; } cnt7++; } while (true); // MicroParser.g:205:25: ( EXPONENT )? int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0=='E'||LA8_0=='e') ) { alt8=1; } switch (alt8) { case 1 : // MicroParser.g:205:25: EXPONENT { mEXPONENT(); } break; } } break; case 3 : // MicroParser.g:206:9: ( '0' .. '9' )+ EXPONENT { // MicroParser.g:206:9: ( '0' .. '9' )+ int cnt9=0; loop9: do { int alt9=2; int LA9_0 = input.LA(1); if ( ((LA9_0 >= '0' && LA9_0 <= '9')) ) { alt9=1; } switch (alt9) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt9 >= 1 ) break loop9; EarlyExitException eee = new EarlyExitException(9, input); throw eee; } cnt9++; } while (true); mEXPONENT(); } break; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "FLOATLITERAL" // $ANTLR start "COMMENT" public final void mCOMMENT() throws RecognitionException { try { int _type = COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:210:5: ( '--' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' | '/*' ( options {greedy=false; } : . )* '*/' ) int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='-') ) { alt14=1; } else if ( (LA14_0=='/') ) { alt14=2; } else { NoViableAltException nvae = new NoViableAltException("", 14, 0, input); throw nvae; } switch (alt14) { case 1 : // MicroParser.g:210:9: '--' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' { match("--"); // MicroParser.g:210:15: (~ ( '\\n' | '\\r' ) )* loop11: do { int alt11=2; int LA11_0 = input.LA(1); if ( ((LA11_0 >= '\u0000' && LA11_0 <= '\t')||(LA11_0 >= '\u000B' && LA11_0 <= '\f')||(LA11_0 >= '\u000E' && LA11_0 <= '\uFFFF')) ) { alt11=1; } switch (alt11) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '\t')||(input.LA(1) >= '\u000B' && input.LA(1) <= '\f')||(input.LA(1) >= '\u000E' && input.LA(1) <= '\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop11; } } while (true); // MicroParser.g:210:29: ( '\\r' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\r') ) { alt12=1; } switch (alt12) { case 1 : // MicroParser.g:210:29: '\\r' { match('\r'); } break; } match('\n'); _channel=HIDDEN; } break; case 2 : // MicroParser.g:211:9: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // MicroParser.g:211:14: ( options {greedy=false; } : . )* loop13: do { int alt13=2; int LA13_0 = input.LA(1); if ( (LA13_0=='*') ) { int LA13_1 = input.LA(2); if ( (LA13_1=='/') ) { alt13=2; } else if ( ((LA13_1 >= '\u0000' && LA13_1 <= '.')||(LA13_1 >= '0' && LA13_1 <= '\uFFFF')) ) { alt13=1; } } else if ( ((LA13_0 >= '\u0000' && LA13_0 <= ')')||(LA13_0 >= '+' && LA13_0 <= '\uFFFF')) ) { alt13=1; } switch (alt13) { case 1 : // MicroParser.g:211:42: . { matchAny(); } break; default : break loop13; } } while (true); match("*/"); _channel=HIDDEN; } break; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "COMMENT" // $ANTLR start "STRINGLIETRAL" public final void mSTRINGLIETRAL() throws RecognitionException { try { int _type = STRINGLIETRAL; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:215:5: ( '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' ) // MicroParser.g:215:8: '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' { match('\"'); // MicroParser.g:215:12: ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* loop15: do { int alt15=3; int LA15_0 = input.LA(1); if ( (LA15_0=='\\') ) { alt15=1; } else if ( ((LA15_0 >= '\u0000' && LA15_0 <= '!')||(LA15_0 >= '#' && LA15_0 <= '[')||(LA15_0 >= ']' && LA15_0 <= '\uFFFF')) ) { alt15=2; } switch (alt15) { case 1 : // MicroParser.g:215:14: ESC_SEQ { mESC_SEQ(); } break; case 2 : // MicroParser.g:215:24: ~ ( '\\\\' | '\"' ) { if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '!')||(input.LA(1) >= '#' && input.LA(1) <= '[')||(input.LA(1) >= ']' && input.LA(1) <= '\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop15; } } while (true); match('\"'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "STRINGLIETRAL" // $ANTLR start "OPERATORS" public final void mOPERATORS() throws RecognitionException { try { // MicroParser.g:219:11: ( ( ':=' ) | ( '+' ) | ( '-' ) | ( '*' ) | ( '/' ) | ( '=' ) | ( '!=' ) | ( '<' ) | ( '>' ) | ( '(' ) | ( ')' ) | ( ';' ) | ( ',' ) ) int alt16=13; switch ( input.LA(1) ) { case ':': { alt16=1; } break; case '+': { alt16=2; } break; case '-': { alt16=3; } break; case '*': { alt16=4; } break; case '/': { alt16=5; } break; case '=': { alt16=6; } break; case '!': { alt16=7; } break; case '<': { alt16=8; } break; case '>': { alt16=9; } break; case '(': { alt16=10; } break; case ')': { alt16=11; } break; case ';': { alt16=12; } break; case ',': { alt16=13; } break; default: NoViableAltException nvae = new NoViableAltException("", 16, 0, input); throw nvae; } switch (alt16) { case 1 : // MicroParser.g:219:13: ( ':=' ) { // MicroParser.g:219:13: ( ':=' ) // MicroParser.g:219:14: ':=' { match(":="); } } break; case 2 : // MicroParser.g:219:22: ( '+' ) { // MicroParser.g:219:22: ( '+' ) // MicroParser.g:219:23: '+' { match('+'); } } break; case 3 : // MicroParser.g:219:30: ( '-' ) { // MicroParser.g:219:30: ( '-' ) // MicroParser.g:219:31: '-' { match('-'); } } break; case 4 : // MicroParser.g:219:38: ( '*' ) { // MicroParser.g:219:38: ( '*' ) // MicroParser.g:219:39: '*' { match('*'); } } break; case 5 : // MicroParser.g:219:46: ( '/' ) { // MicroParser.g:219:46: ( '/' ) // MicroParser.g:219:47: '/' { match('/'); } } break; case 6 : // MicroParser.g:219:54: ( '=' ) { // MicroParser.g:219:54: ( '=' ) // MicroParser.g:219:55: '=' { match('='); } } break; case 7 : // MicroParser.g:219:62: ( '!=' ) { // MicroParser.g:219:62: ( '!=' ) // MicroParser.g:219:63: '!=' { match("!="); } } break; case 8 : // MicroParser.g:219:71: ( '<' ) { // MicroParser.g:219:71: ( '<' ) // MicroParser.g:219:72: '<' { match('<'); } } break; case 9 : // MicroParser.g:219:79: ( '>' ) { // MicroParser.g:219:79: ( '>' ) // MicroParser.g:219:80: '>' { match('>'); } } break; case 10 : // MicroParser.g:219:87: ( '(' ) { // MicroParser.g:219:87: ( '(' ) // MicroParser.g:219:88: '(' { match('('); } } break; case 11 : // MicroParser.g:219:95: ( ')' ) { // MicroParser.g:219:95: ( ')' ) // MicroParser.g:219:96: ')' { match(')'); } } break; case 12 : // MicroParser.g:219:103: ( ';' ) { // MicroParser.g:219:103: ( ';' ) // MicroParser.g:219:104: ';' { match(';'); } } break; case 13 : // MicroParser.g:219:111: ( ',' ) { // MicroParser.g:219:111: ( ',' ) // MicroParser.g:219:112: ',' { match(','); } } break; } } finally { // do for sure before leaving } } // $ANTLR end "OPERATORS" // $ANTLR start "WHITESPACE" public final void mWHITESPACE() throws RecognitionException { try { int _type = WHITESPACE; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:221:12: ( ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ ) // MicroParser.g:221:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ { // MicroParser.g:221:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ int cnt17=0; loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( ((LA17_0 >= '\t' && LA17_0 <= '\n')||(LA17_0 >= '\f' && LA17_0 <= '\r')||LA17_0==' ') ) { alt17=1; } switch (alt17) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '\t' && input.LA(1) <= '\n')||(input.LA(1) >= '\f' && input.LA(1) <= '\r')||input.LA(1)==' ' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt17 >= 1 ) break loop17; EarlyExitException eee = new EarlyExitException(17, input); throw eee; } cnt17++; } while (true); _channel = HIDDEN; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "WHITESPACE" // $ANTLR start "EXPONENT" public final void mEXPONENT() throws RecognitionException { try { // MicroParser.g:225:10: ( ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ ) // MicroParser.g:225:12: ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ { if ( input.LA(1)=='E'||input.LA(1)=='e' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } // MicroParser.g:225:22: ( '+' | '-' )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0=='+'||LA18_0=='-') ) { alt18=1; } switch (alt18) { case 1 : // MicroParser.g: { if ( input.LA(1)=='+'||input.LA(1)=='-' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; } // MicroParser.g:225:33: ( '0' .. '9' )+ int cnt19=0; loop19: do { int alt19=2; int LA19_0 = input.LA(1); if ( ((LA19_0 >= '0' && LA19_0 <= '9')) ) { alt19=1; } switch (alt19) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt19 >= 1 ) break loop19; EarlyExitException eee = new EarlyExitException(19, input); throw eee; } cnt19++; } while (true); } } finally { // do for sure before leaving } } // $ANTLR end "EXPONENT" // $ANTLR start "HEX_DIGIT" public final void mHEX_DIGIT() throws RecognitionException { try { // MicroParser.g:228:11: ( ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) ) // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'F')||(input.LA(1) >= 'a' && input.LA(1) <= 'f') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } } finally { // do for sure before leaving } } // $ANTLR end "HEX_DIGIT" // $ANTLR start "ESC_SEQ" public final void mESC_SEQ() throws RecognitionException { try { // MicroParser.g:232:5: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC ) int alt20=3; int LA20_0 = input.LA(1); if ( (LA20_0=='\\') ) { switch ( input.LA(2) ) { case '\"': case '\'': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': { alt20=1; } break; case 'u': { alt20=2; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { alt20=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 20, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 20, 0, input); throw nvae; } switch (alt20) { case 1 : // MicroParser.g:232:9: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) { match('\\'); if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 2 : // MicroParser.g:233:9: UNICODE_ESC { mUNICODE_ESC(); } break; case 3 : // MicroParser.g:234:9: OCTAL_ESC { mOCTAL_ESC(); } break; } } finally { // do for sure before leaving } } // $ANTLR end "ESC_SEQ" // $ANTLR start "OCTAL_ESC" public final void mOCTAL_ESC() throws RecognitionException { try { // MicroParser.g:239:5: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ) int alt21=3; int LA21_0 = input.LA(1); if ( (LA21_0=='\\') ) { int LA21_1 = input.LA(2); if ( ((LA21_1 >= '0' && LA21_1 <= '3')) ) { int LA21_2 = input.LA(3); if ( ((LA21_2 >= '0' && LA21_2 <= '7')) ) { int LA21_4 = input.LA(4); if ( ((LA21_4 >= '0' && LA21_4 <= '7')) ) { alt21=1; } else { alt21=2; } } else { alt21=3; } } else if ( ((LA21_1 >= '4' && LA21_1 <= '7')) ) { int LA21_3 = input.LA(3); if ( ((LA21_3 >= '0' && LA21_3 <= '7')) ) { alt21=2; } else { alt21=3; } } else { NoViableAltException nvae = new NoViableAltException("", 21, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 21, 0, input); throw nvae; } switch (alt21) { case 1 : // MicroParser.g:239:9: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) { match('\\'); if ( (input.LA(1) >= '0' && input.LA(1) <= '3') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 2 : // MicroParser.g:240:9: '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) { match('\\'); if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 3 : // MicroParser.g:241:9: '\\\\' ( '0' .. '7' ) { match('\\'); if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; } } finally { // do for sure before leaving } } // $ANTLR end "OCTAL_ESC" // $ANTLR start "UNICODE_ESC" public final void mUNICODE_ESC() throws RecognitionException { try { // MicroParser.g:246:5: ( '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ) // MicroParser.g:246:9: '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT { match('\\'); match('u'); mHEX_DIGIT(); mHEX_DIGIT(); mHEX_DIGIT(); mHEX_DIGIT(); } } finally { // do for sure before leaving } } // $ANTLR end "UNICODE_ESC" public void mTokens() throws RecognitionException { // MicroParser.g:1:8: ( T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | KEYWORD | IDENTIFIER | INTLITERAL | FLOATLITERAL | COMMENT | STRINGLIETRAL | WHITESPACE ) int alt22=37; alt22 = dfa22.predict(input); switch (alt22) { case 1 : // MicroParser.g:1:10: T__17 { mT__17(); } break; case 2 : // MicroParser.g:1:16: T__18 { mT__18(); } break; case 3 : // MicroParser.g:1:22: T__19 { mT__19(); } break; case 4 : // MicroParser.g:1:28: T__20 { mT__20(); } break; case 5 : // MicroParser.g:1:34: T__21 { mT__21(); } break; case 6 : // MicroParser.g:1:40: T__22 { mT__22(); } break; case 7 : // MicroParser.g:1:46: T__23 { mT__23(); } break; case 8 : // MicroParser.g:1:52: T__24 { mT__24(); } break; case 9 : // MicroParser.g:1:58: T__25 { mT__25(); } break; case 10 : // MicroParser.g:1:64: T__26 { mT__26(); } break; case 11 : // MicroParser.g:1:70: T__27 { mT__27(); } break; case 12 : // MicroParser.g:1:76: T__28 { mT__28(); } break; case 13 : // MicroParser.g:1:82: T__29 { mT__29(); } break; case 14 : // MicroParser.g:1:88: T__30 { mT__30(); } break; case 15 : // MicroParser.g:1:94: T__31 { mT__31(); } break; case 16 : // MicroParser.g:1:100: T__32 { mT__32(); } break; case 17 : // MicroParser.g:1:106: T__33 { mT__33(); } break; case 18 : // MicroParser.g:1:112: T__34 { mT__34(); } break; case 19 : // MicroParser.g:1:118: T__35 { mT__35(); } break; case 20 : // MicroParser.g:1:124: T__36 { mT__36(); } break; case 21 : // MicroParser.g:1:130: T__37 { mT__37(); } break; case 22 : // MicroParser.g:1:136: T__38 { mT__38(); } break; case 23 : // MicroParser.g:1:142: T__39 { mT__39(); } break; case 24 : // MicroParser.g:1:148: T__40 { mT__40(); } break; case 25 : // MicroParser.g:1:154: T__41 { mT__41(); } break; case 26 : // MicroParser.g:1:160: T__42 { mT__42(); } break; case 27 : // MicroParser.g:1:166: T__43 { mT__43(); } break; case 28 : // MicroParser.g:1:172: T__44 { mT__44(); } break; case 29 : // MicroParser.g:1:178: T__45 { mT__45(); } break; case 30 : // MicroParser.g:1:184: T__46 { mT__46(); } break; case 31 : // MicroParser.g:1:190: KEYWORD { mKEYWORD(); } break; case 32 : // MicroParser.g:1:198: IDENTIFIER { mIDENTIFIER(); } break; case 33 : // MicroParser.g:1:209: INTLITERAL { mINTLITERAL(); } break; case 34 : // MicroParser.g:1:220: FLOATLITERAL { mFLOATLITERAL(); } break; case 35 : // MicroParser.g:1:233: COMMENT { mCOMMENT(); } break; case 36 : // MicroParser.g:1:241: STRINGLIETRAL { mSTRINGLIETRAL(); } break; case 37 : // MicroParser.g:1:255: WHITESPACE { mWHITESPACE(); } break; } } protected DFA10 dfa10 = new DFA10(this); protected DFA22 dfa22 = new DFA22(this); static final String DFA10_eotS = "\5\uffff"; static final String DFA10_eofS = "\5\uffff"; static final String DFA10_minS = "\2\56\3\uffff"; static final String DFA10_maxS = "\1\71\1\145\3\uffff"; static final String DFA10_acceptS = "\2\uffff\1\2\1\1\1\3"; static final String DFA10_specialS = "\5\uffff}>"; static final String[] DFA10_transitionS = { "\1\2\1\uffff\12\1", "\1\3\1\uffff\12\1\13\uffff\1\4\37\uffff\1\4", "", "", "" }; static final short[] DFA10_eot = DFA.unpackEncodedString(DFA10_eotS); static final short[] DFA10_eof = DFA.unpackEncodedString(DFA10_eofS); static final char[] DFA10_min = DFA.unpackEncodedStringToUnsignedChars(DFA10_minS); static final char[] DFA10_max = DFA.unpackEncodedStringToUnsignedChars(DFA10_maxS); static final short[] DFA10_accept = DFA.unpackEncodedString(DFA10_acceptS); static final short[] DFA10_special = DFA.unpackEncodedString(DFA10_specialS); static final short[][] DFA10_transition; static { int numStates = DFA10_transitionS.length; DFA10_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA10_transition[i] = DFA.unpackEncodedString(DFA10_transitionS[i]); } } class DFA10 extends DFA { public DFA10(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 10; this.eot = DFA10_eot; this.eof = DFA10_eof; this.min = DFA10_min; this.max = DFA10_max; this.accept = DFA10_accept; this.special = DFA10_special; this.transition = DFA10_transition; } public String getDescription() { return "203:1: FLOATLITERAL : ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( EXPONENT )? | '.' ( '0' .. '9' )+ ( EXPONENT )? | ( '0' .. '9' )+ EXPONENT );"; } } static final String DFA22_eotS = "\7\uffff\1\40\1\41\5\uffff\14\32\1\uffff\1\62\6\uffff\6\32\1\71"+ "\11\32\1\uffff\3\32\1\111\2\32\1\uffff\1\114\14\32\1\131\1\32\1"+ "\uffff\2\32\1\uffff\1\32\1\136\3\32\1\142\1\32\1\144\2\32\1\147"+ "\1\150\1\uffff\1\151\1\152\2\32\1\uffff\3\32\1\uffff\1\160\1\uffff"+ "\1\161\1\32\4\uffff\2\32\1\165\1\166\1\167\2\uffff\2\32\1\172\3"+ "\uffff\1\32\1\174\1\uffff\1\150\1\uffff"; static final String DFA22_eofS = "\175\uffff"; static final String DFA22_minS = "\1\11\6\uffff\1\55\1\52\5\uffff\1\105\2\114\1\106\1\122\1\105\1"+ "\124\1\110\1\116\1\117\1\122\1\117\1\uffff\1\56\6\uffff\1\107\1"+ "\105\1\123\1\104\1\117\1\116\1\60\1\124\1\117\1\101\1\122\1\105"+ "\1\124\2\111\1\116\1\uffff\1\111\1\101\1\105\1\60\1\101\1\103\1"+ "\uffff\1\60\1\107\1\104\1\105\1\125\1\111\1\116\1\111\1\104\2\124"+ "\1\116\1\113\1\60\1\106\1\uffff\2\124\1\uffff\1\122\1\60\1\101\1"+ "\122\1\116\1\60\1\114\1\60\1\105\1\111\2\60\1\uffff\2\60\1\111\1"+ "\101\1\uffff\1\124\1\116\1\107\1\uffff\1\60\1\uffff\1\60\1\116\4"+ "\uffff\1\117\1\115\3\60\2\uffff\1\125\1\116\1\60\3\uffff\1\105\1"+ "\60\1\uffff\1\60\1\uffff"; static final String DFA22_maxS = "\1\172\6\uffff\1\55\1\52\5\uffff\1\122\1\116\1\125\1\116\1\122\1"+ "\105\1\124\1\110\1\116\1\117\1\122\1\117\1\uffff\1\145\6\uffff\1"+ "\107\1\105\1\123\1\104\1\117\1\116\1\172\1\124\1\117\1\124\1\122"+ "\1\105\1\124\2\111\1\116\1\uffff\1\111\1\101\1\105\1\172\1\101\1"+ "\103\1\uffff\1\172\1\107\1\104\1\105\1\125\1\111\1\116\1\111\1\104"+ "\2\124\1\116\1\113\1\172\1\106\1\uffff\2\124\1\uffff\1\122\1\172"+ "\1\101\1\122\1\116\1\172\1\114\1\172\1\105\1\111\2\172\1\uffff\2"+ "\172\1\111\1\101\1\uffff\1\124\1\116\1\107\1\uffff\1\172\1\uffff"+ "\1\172\1\116\4\uffff\1\117\1\115\3\172\2\uffff\1\125\1\116\1\172"+ "\3\uffff\1\105\1\172\1\uffff\1\172\1\uffff"; static final String DFA22_acceptS = "\1\uffff\1\1\1\2\1\3\1\4\1\5\1\6\2\uffff\1\11\1\12\1\13\1\14\1\15"+ "\14\uffff\1\40\1\uffff\1\42\1\44\1\45\1\43\1\7\1\10\20\uffff\1\41"+ "\6\uffff\1\24\17\uffff\1\20\2\uffff\1\25\14\uffff\1\17\4\uffff\1"+ "\27\3\uffff\1\33\1\uffff\1\35\2\uffff\1\16\1\37\1\21\1\22\5\uffff"+ "\1\34\1\36\3\uffff\1\30\1\31\1\32\2\uffff\1\26\1\uffff\1\23"; static final String DFA22_specialS = "\175\uffff}>"; static final String[] DFA22_transitionS = { "\2\36\1\uffff\2\36\22\uffff\1\36\1\1\1\35\5\uffff\1\2\1\3\1"+ "\4\1\5\1\6\1\7\1\34\1\10\12\33\1\11\1\12\1\13\1\14\1\15\2\uffff"+ "\1\32\1\16\1\31\1\32\1\17\1\20\2\32\1\21\6\32\1\22\1\32\1\23"+ "\1\24\1\25\1\26\1\27\1\30\3\32\4\uffff\1\32\1\uffff\32\32", "", "", "", "", "", "", "\1\37", "\1\37", "", "", "", "", "", "\1\42\14\uffff\1\43", "\1\44\1\uffff\1\45", "\1\46\10\uffff\1\47", "\1\50\7\uffff\1\51", "\1\52", "\1\53", "\1\54", "\1\55", "\1\56", "\1\57", "\1\60", "\1\61", "", "\1\34\1\uffff\12\33\13\uffff\1\34\37\uffff\1\34", "", "", "", "", "", "", "\1\63", "\1\64", "\1\65", "\1\66", "\1\67", "\1\70", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\72", "\1\73", "\1\74\16\uffff\1\75\3\uffff\1\76", "\1\77", "\1\100", "\1\101", "\1\102", "\1\103", "\1\104", "", "\1\105", "\1\106", "\1\107", "\12\32\7\uffff\10\32\1\110\21\32\4\uffff\1\32\1\uffff\32\32", "\1\112", "\1\113", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\115", "\1\116", "\1\117", "\1\120", "\1\121", "\1\122", "\1\123", "\1\124", "\1\125", "\1\126", "\1\127", "\1\130", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\132", "", "\1\133", "\1\134", "", "\1\135", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\137", "\1\140", "\1\141", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\143", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\145", "\1\146", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\153", "\1\154", "", "\1\155", "\1\156", "\1\157", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\162", "", "", "", "", "\1\163", "\1\164", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "", "\1\170", "\1\171", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "", "", "\1\173", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "" }; static final short[] DFA22_eot = DFA.unpackEncodedString(DFA22_eotS); static final short[] DFA22_eof = DFA.unpackEncodedString(DFA22_eofS); static final char[] DFA22_min = DFA.unpackEncodedStringToUnsignedChars(DFA22_minS); static final char[] DFA22_max = DFA.unpackEncodedStringToUnsignedChars(DFA22_maxS); static final short[] DFA22_accept = DFA.unpackEncodedString(DFA22_acceptS); static final short[] DFA22_special = DFA.unpackEncodedString(DFA22_specialS); static final short[][] DFA22_transition; static { int numStates = DFA22_transitionS.length; DFA22_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA22_transition[i] = DFA.unpackEncodedString(DFA22_transitionS[i]); } } class DFA22 extends DFA { public DFA22(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 22; this.eot = DFA22_eot; this.eof = DFA22_eof; this.min = DFA22_min; this.max = DFA22_max; this.accept = DFA22_accept; this.special = DFA22_special; this.transition = DFA22_transition; } public String getDescription() { return "1:1: Tokens : ( T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | KEYWORD | IDENTIFIER | INTLITERAL | FLOATLITERAL | COMMENT | STRINGLIETRAL | WHITESPACE );"; } } }
UTF-8
Java
82,839
java
MicroParserLexer.java
Java
[]
null
[]
// $ANTLR 3.4 MicroParser.g 2012-10-14 00:46:37 import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked"}) public class MicroParserLexer extends Lexer { public static final int EOF=-1; public static final int T__17=17; public static final int T__18=18; public static final int T__19=19; public static final int T__20=20; public static final int T__21=21; public static final int T__22=22; public static final int T__23=23; public static final int T__24=24; public static final int T__25=25; public static final int T__26=26; public static final int T__27=27; public static final int T__28=28; public static final int T__29=29; public static final int T__30=30; public static final int T__31=31; public static final int T__32=32; public static final int T__33=33; public static final int T__34=34; public static final int T__35=35; public static final int T__36=36; public static final int T__37=37; public static final int T__38=38; public static final int T__39=39; public static final int T__40=40; public static final int T__41=41; public static final int T__42=42; public static final int T__43=43; public static final int T__44=44; public static final int T__45=45; public static final int T__46=46; public static final int COMMENT=4; public static final int ESC_SEQ=5; public static final int EXPONENT=6; public static final int FLOATLITERAL=7; public static final int HEX_DIGIT=8; public static final int IDENTIFIER=9; public static final int INTLITERAL=10; public static final int KEYWORD=11; public static final int OCTAL_ESC=12; public static final int OPERATORS=13; public static final int STRINGLIETRAL=14; public static final int UNICODE_ESC=15; public static final int WHITESPACE=16; // delegates // delegators public Lexer[] getDelegates() { return new Lexer[] {}; } public MicroParserLexer() {} public MicroParserLexer(CharStream input) { this(input, new RecognizerSharedState()); } public MicroParserLexer(CharStream input, RecognizerSharedState state) { super(input,state); } public String getGrammarFileName() { return "MicroParser.g"; } // $ANTLR start "T__17" public final void mT__17() throws RecognitionException { try { int _type = T__17; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:7:7: ( '!=' ) // MicroParser.g:7:9: '!=' { match("!="); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__17" // $ANTLR start "T__18" public final void mT__18() throws RecognitionException { try { int _type = T__18; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:8:7: ( '(' ) // MicroParser.g:8:9: '(' { match('('); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__18" // $ANTLR start "T__19" public final void mT__19() throws RecognitionException { try { int _type = T__19; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:9:7: ( ')' ) // MicroParser.g:9:9: ')' { match(')'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__19" // $ANTLR start "T__20" public final void mT__20() throws RecognitionException { try { int _type = T__20; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:10:7: ( '*' ) // MicroParser.g:10:9: '*' { match('*'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__20" // $ANTLR start "T__21" public final void mT__21() throws RecognitionException { try { int _type = T__21; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:11:7: ( '+' ) // MicroParser.g:11:9: '+' { match('+'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__21" // $ANTLR start "T__22" public final void mT__22() throws RecognitionException { try { int _type = T__22; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:12:7: ( ',' ) // MicroParser.g:12:9: ',' { match(','); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__22" // $ANTLR start "T__23" public final void mT__23() throws RecognitionException { try { int _type = T__23; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:13:7: ( '-' ) // MicroParser.g:13:9: '-' { match('-'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__23" // $ANTLR start "T__24" public final void mT__24() throws RecognitionException { try { int _type = T__24; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:14:7: ( '/' ) // MicroParser.g:14:9: '/' { match('/'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__24" // $ANTLR start "T__25" public final void mT__25() throws RecognitionException { try { int _type = T__25; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:15:7: ( ':=' ) // MicroParser.g:15:9: ':=' { match(":="); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__25" // $ANTLR start "T__26" public final void mT__26() throws RecognitionException { try { int _type = T__26; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:16:7: ( ';' ) // MicroParser.g:16:9: ';' { match(';'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__26" // $ANTLR start "T__27" public final void mT__27() throws RecognitionException { try { int _type = T__27; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:17:7: ( '<' ) // MicroParser.g:17:9: '<' { match('<'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__27" // $ANTLR start "T__28" public final void mT__28() throws RecognitionException { try { int _type = T__28; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:18:7: ( '=' ) // MicroParser.g:18:9: '=' { match('='); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__28" // $ANTLR start "T__29" public final void mT__29() throws RecognitionException { try { int _type = T__29; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:19:7: ( '>' ) // MicroParser.g:19:9: '>' { match('>'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__29" // $ANTLR start "T__30" public final void mT__30() throws RecognitionException { try { int _type = T__30; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:20:7: ( 'BEGIN' ) // MicroParser.g:20:9: 'BEGIN' { match("BEGIN"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__30" // $ANTLR start "T__31" public final void mT__31() throws RecognitionException { try { int _type = T__31; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:21:7: ( 'ELSE' ) // MicroParser.g:21:9: 'ELSE' { match("ELSE"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__31" // $ANTLR start "T__32" public final void mT__32() throws RecognitionException { try { int _type = T__32; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:22:7: ( 'END' ) // MicroParser.g:22:9: 'END' { match("END"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__32" // $ANTLR start "T__33" public final void mT__33() throws RecognitionException { try { int _type = T__33; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:23:7: ( 'ENDIF' ) // MicroParser.g:23:9: 'ENDIF' { match("ENDIF"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__33" // $ANTLR start "T__34" public final void mT__34() throws RecognitionException { try { int _type = T__34; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:24:7: ( 'FLOAT' ) // MicroParser.g:24:9: 'FLOAT' { match("FLOAT"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__34" // $ANTLR start "T__35" public final void mT__35() throws RecognitionException { try { int _type = T__35; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:25:7: ( 'FUNCTION' ) // MicroParser.g:25:9: 'FUNCTION' { match("FUNCTION"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__35" // $ANTLR start "T__36" public final void mT__36() throws RecognitionException { try { int _type = T__36; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:26:7: ( 'IF' ) // MicroParser.g:26:9: 'IF' { match("IF"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__36" // $ANTLR start "T__37" public final void mT__37() throws RecognitionException { try { int _type = T__37; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:27:7: ( 'INT' ) // MicroParser.g:27:9: 'INT' { match("INT"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__37" // $ANTLR start "T__38" public final void mT__38() throws RecognitionException { try { int _type = T__38; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:28:7: ( 'PROGRAM' ) // MicroParser.g:28:9: 'PROGRAM' { match("PROGRAM"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__38" // $ANTLR start "T__39" public final void mT__39() throws RecognitionException { try { int _type = T__39; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:29:7: ( 'READ' ) // MicroParser.g:29:9: 'READ' { match("READ"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__39" // $ANTLR start "T__40" public final void mT__40() throws RecognitionException { try { int _type = T__40; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:30:7: ( 'REPEAT' ) // MicroParser.g:30:9: 'REPEAT' { match("REPEAT"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__40" // $ANTLR start "T__41" public final void mT__41() throws RecognitionException { try { int _type = T__41; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:31:7: ( 'RETURN' ) // MicroParser.g:31:9: 'RETURN' { match("RETURN"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__41" // $ANTLR start "T__42" public final void mT__42() throws RecognitionException { try { int _type = T__42; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:32:7: ( 'STRING' ) // MicroParser.g:32:9: 'STRING' { match("STRING"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__42" // $ANTLR start "T__43" public final void mT__43() throws RecognitionException { try { int _type = T__43; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:33:7: ( 'THEN' ) // MicroParser.g:33:9: 'THEN' { match("THEN"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__43" // $ANTLR start "T__44" public final void mT__44() throws RecognitionException { try { int _type = T__44; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:34:7: ( 'UNTIL' ) // MicroParser.g:34:9: 'UNTIL' { match("UNTIL"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__44" // $ANTLR start "T__45" public final void mT__45() throws RecognitionException { try { int _type = T__45; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:35:7: ( 'VOID' ) // MicroParser.g:35:9: 'VOID' { match("VOID"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__45" // $ANTLR start "T__46" public final void mT__46() throws RecognitionException { try { int _type = T__46; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:36:7: ( 'WRITE' ) // MicroParser.g:36:9: 'WRITE' { match("WRITE"); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "T__46" // $ANTLR start "KEYWORD" public final void mKEYWORD() throws RecognitionException { try { int _type = KEYWORD; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:192:9: ( ( 'PROGRAM' ) | ( 'BEGIN' ) | ( 'FUNCTION' ) | ( 'END' ) | ( 'READ' ) | ( 'WRITE' ) | ( 'IF' ) | ( 'THEN' ) | ( 'ELSE' ) | ( 'ENDIF' ) | ( 'REPEAT' ) | ( 'UNTIL' ) | ( 'CONTINUE' ) | ( 'BREAK' ) | ( 'RETURN' ) | ( 'INT' ) | ( 'VOID' ) | ( 'STRING' ) | ( 'FLOAT' ) ) int alt1=19; switch ( input.LA(1) ) { case 'P': { alt1=1; } break; case 'B': { int LA1_2 = input.LA(2); if ( (LA1_2=='E') ) { alt1=2; } else if ( (LA1_2=='R') ) { alt1=14; } else { NoViableAltException nvae = new NoViableAltException("", 1, 2, input); throw nvae; } } break; case 'F': { int LA1_3 = input.LA(2); if ( (LA1_3=='U') ) { alt1=3; } else if ( (LA1_3=='L') ) { alt1=19; } else { NoViableAltException nvae = new NoViableAltException("", 1, 3, input); throw nvae; } } break; case 'E': { int LA1_4 = input.LA(2); if ( (LA1_4=='N') ) { int LA1_17 = input.LA(3); if ( (LA1_17=='D') ) { int LA1_22 = input.LA(4); if ( (LA1_22=='I') ) { alt1=10; } else { alt1=4; } } else { NoViableAltException nvae = new NoViableAltException("", 1, 17, input); throw nvae; } } else if ( (LA1_4=='L') ) { alt1=9; } else { NoViableAltException nvae = new NoViableAltException("", 1, 4, input); throw nvae; } } break; case 'R': { int LA1_5 = input.LA(2); if ( (LA1_5=='E') ) { switch ( input.LA(3) ) { case 'A': { alt1=5; } break; case 'P': { alt1=11; } break; case 'T': { alt1=15; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 19, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 1, 5, input); throw nvae; } } break; case 'W': { alt1=6; } break; case 'I': { int LA1_7 = input.LA(2); if ( (LA1_7=='F') ) { alt1=7; } else if ( (LA1_7=='N') ) { alt1=16; } else { NoViableAltException nvae = new NoViableAltException("", 1, 7, input); throw nvae; } } break; case 'T': { alt1=8; } break; case 'U': { alt1=12; } break; case 'C': { alt1=13; } break; case 'V': { alt1=17; } break; case 'S': { alt1=18; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 0, input); throw nvae; } switch (alt1) { case 1 : // MicroParser.g:192:11: ( 'PROGRAM' ) { // MicroParser.g:192:11: ( 'PROGRAM' ) // MicroParser.g:192:12: 'PROGRAM' { match("PROGRAM"); } } break; case 2 : // MicroParser.g:192:25: ( 'BEGIN' ) { // MicroParser.g:192:25: ( 'BEGIN' ) // MicroParser.g:192:26: 'BEGIN' { match("BEGIN"); } } break; case 3 : // MicroParser.g:192:37: ( 'FUNCTION' ) { // MicroParser.g:192:37: ( 'FUNCTION' ) // MicroParser.g:192:38: 'FUNCTION' { match("FUNCTION"); } } break; case 4 : // MicroParser.g:192:52: ( 'END' ) { // MicroParser.g:192:52: ( 'END' ) // MicroParser.g:192:53: 'END' { match("END"); } } break; case 5 : // MicroParser.g:192:62: ( 'READ' ) { // MicroParser.g:192:62: ( 'READ' ) // MicroParser.g:192:63: 'READ' { match("READ"); } } break; case 6 : // MicroParser.g:192:73: ( 'WRITE' ) { // MicroParser.g:192:73: ( 'WRITE' ) // MicroParser.g:192:74: 'WRITE' { match("WRITE"); } } break; case 7 : // MicroParser.g:193:4: ( 'IF' ) { // MicroParser.g:193:4: ( 'IF' ) // MicroParser.g:193:5: 'IF' { match("IF"); } } break; case 8 : // MicroParser.g:193:13: ( 'THEN' ) { // MicroParser.g:193:13: ( 'THEN' ) // MicroParser.g:193:14: 'THEN' { match("THEN"); } } break; case 9 : // MicroParser.g:193:24: ( 'ELSE' ) { // MicroParser.g:193:24: ( 'ELSE' ) // MicroParser.g:193:25: 'ELSE' { match("ELSE"); } } break; case 10 : // MicroParser.g:193:35: ( 'ENDIF' ) { // MicroParser.g:193:35: ( 'ENDIF' ) // MicroParser.g:193:36: 'ENDIF' { match("ENDIF"); } } break; case 11 : // MicroParser.g:193:47: ( 'REPEAT' ) { // MicroParser.g:193:47: ( 'REPEAT' ) // MicroParser.g:193:48: 'REPEAT' { match("REPEAT"); } } break; case 12 : // MicroParser.g:193:60: ( 'UNTIL' ) { // MicroParser.g:193:60: ( 'UNTIL' ) // MicroParser.g:193:61: 'UNTIL' { match("UNTIL"); } } break; case 13 : // MicroParser.g:194:4: ( 'CONTINUE' ) { // MicroParser.g:194:4: ( 'CONTINUE' ) // MicroParser.g:194:5: 'CONTINUE' { match("CONTINUE"); } } break; case 14 : // MicroParser.g:194:19: ( 'BREAK' ) { // MicroParser.g:194:19: ( 'BREAK' ) // MicroParser.g:194:20: 'BREAK' { match("BREAK"); } } break; case 15 : // MicroParser.g:194:31: ( 'RETURN' ) { // MicroParser.g:194:31: ( 'RETURN' ) // MicroParser.g:194:32: 'RETURN' { match("RETURN"); } } break; case 16 : // MicroParser.g:194:44: ( 'INT' ) { // MicroParser.g:194:44: ( 'INT' ) // MicroParser.g:194:45: 'INT' { match("INT"); } } break; case 17 : // MicroParser.g:194:54: ( 'VOID' ) { // MicroParser.g:194:54: ( 'VOID' ) // MicroParser.g:194:55: 'VOID' { match("VOID"); } } break; case 18 : // MicroParser.g:194:65: ( 'STRING' ) { // MicroParser.g:194:65: ( 'STRING' ) // MicroParser.g:194:66: 'STRING' { match("STRING"); } } break; case 19 : // MicroParser.g:194:78: ( 'FLOAT' ) { // MicroParser.g:194:78: ( 'FLOAT' ) // MicroParser.g:194:79: 'FLOAT' { match("FLOAT"); } } break; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "KEYWORD" // $ANTLR start "IDENTIFIER" public final void mIDENTIFIER() throws RecognitionException { try { int _type = IDENTIFIER; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:197:13: ( ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* ) // MicroParser.g:197:15: ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* { if ( (input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } // MicroParser.g:197:39: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* loop2: do { int alt2=2; int LA2_0 = input.LA(1); if ( ((LA2_0 >= '0' && LA2_0 <= '9')||(LA2_0 >= 'A' && LA2_0 <= 'Z')||LA2_0=='_'||(LA2_0 >= 'a' && LA2_0 <= 'z')) ) { alt2=1; } switch (alt2) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop2; } } while (true); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "IDENTIFIER" // $ANTLR start "INTLITERAL" public final void mINTLITERAL() throws RecognitionException { try { int _type = INTLITERAL; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:200:12: ( ( '0' .. '9' )+ ) // MicroParser.g:200:14: ( '0' .. '9' )+ { // MicroParser.g:200:14: ( '0' .. '9' )+ int cnt3=0; loop3: do { int alt3=2; int LA3_0 = input.LA(1); if ( ((LA3_0 >= '0' && LA3_0 <= '9')) ) { alt3=1; } switch (alt3) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt3 >= 1 ) break loop3; EarlyExitException eee = new EarlyExitException(3, input); throw eee; } cnt3++; } while (true); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "INTLITERAL" // $ANTLR start "FLOATLITERAL" public final void mFLOATLITERAL() throws RecognitionException { try { int _type = FLOATLITERAL; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:204:5: ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( EXPONENT )? | '.' ( '0' .. '9' )+ ( EXPONENT )? | ( '0' .. '9' )+ EXPONENT ) int alt10=3; alt10 = dfa10.predict(input); switch (alt10) { case 1 : // MicroParser.g:204:9: ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( EXPONENT )? { // MicroParser.g:204:9: ( '0' .. '9' )+ int cnt4=0; loop4: do { int alt4=2; int LA4_0 = input.LA(1); if ( ((LA4_0 >= '0' && LA4_0 <= '9')) ) { alt4=1; } switch (alt4) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt4 >= 1 ) break loop4; EarlyExitException eee = new EarlyExitException(4, input); throw eee; } cnt4++; } while (true); match('.'); // MicroParser.g:204:25: ( '0' .. '9' )* loop5: do { int alt5=2; int LA5_0 = input.LA(1); if ( ((LA5_0 >= '0' && LA5_0 <= '9')) ) { alt5=1; } switch (alt5) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop5; } } while (true); // MicroParser.g:204:37: ( EXPONENT )? int alt6=2; int LA6_0 = input.LA(1); if ( (LA6_0=='E'||LA6_0=='e') ) { alt6=1; } switch (alt6) { case 1 : // MicroParser.g:204:37: EXPONENT { mEXPONENT(); } break; } } break; case 2 : // MicroParser.g:205:9: '.' ( '0' .. '9' )+ ( EXPONENT )? { match('.'); // MicroParser.g:205:13: ( '0' .. '9' )+ int cnt7=0; loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( ((LA7_0 >= '0' && LA7_0 <= '9')) ) { alt7=1; } switch (alt7) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt7 >= 1 ) break loop7; EarlyExitException eee = new EarlyExitException(7, input); throw eee; } cnt7++; } while (true); // MicroParser.g:205:25: ( EXPONENT )? int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0=='E'||LA8_0=='e') ) { alt8=1; } switch (alt8) { case 1 : // MicroParser.g:205:25: EXPONENT { mEXPONENT(); } break; } } break; case 3 : // MicroParser.g:206:9: ( '0' .. '9' )+ EXPONENT { // MicroParser.g:206:9: ( '0' .. '9' )+ int cnt9=0; loop9: do { int alt9=2; int LA9_0 = input.LA(1); if ( ((LA9_0 >= '0' && LA9_0 <= '9')) ) { alt9=1; } switch (alt9) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt9 >= 1 ) break loop9; EarlyExitException eee = new EarlyExitException(9, input); throw eee; } cnt9++; } while (true); mEXPONENT(); } break; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "FLOATLITERAL" // $ANTLR start "COMMENT" public final void mCOMMENT() throws RecognitionException { try { int _type = COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:210:5: ( '--' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' | '/*' ( options {greedy=false; } : . )* '*/' ) int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='-') ) { alt14=1; } else if ( (LA14_0=='/') ) { alt14=2; } else { NoViableAltException nvae = new NoViableAltException("", 14, 0, input); throw nvae; } switch (alt14) { case 1 : // MicroParser.g:210:9: '--' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' { match("--"); // MicroParser.g:210:15: (~ ( '\\n' | '\\r' ) )* loop11: do { int alt11=2; int LA11_0 = input.LA(1); if ( ((LA11_0 >= '\u0000' && LA11_0 <= '\t')||(LA11_0 >= '\u000B' && LA11_0 <= '\f')||(LA11_0 >= '\u000E' && LA11_0 <= '\uFFFF')) ) { alt11=1; } switch (alt11) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '\t')||(input.LA(1) >= '\u000B' && input.LA(1) <= '\f')||(input.LA(1) >= '\u000E' && input.LA(1) <= '\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop11; } } while (true); // MicroParser.g:210:29: ( '\\r' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\r') ) { alt12=1; } switch (alt12) { case 1 : // MicroParser.g:210:29: '\\r' { match('\r'); } break; } match('\n'); _channel=HIDDEN; } break; case 2 : // MicroParser.g:211:9: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // MicroParser.g:211:14: ( options {greedy=false; } : . )* loop13: do { int alt13=2; int LA13_0 = input.LA(1); if ( (LA13_0=='*') ) { int LA13_1 = input.LA(2); if ( (LA13_1=='/') ) { alt13=2; } else if ( ((LA13_1 >= '\u0000' && LA13_1 <= '.')||(LA13_1 >= '0' && LA13_1 <= '\uFFFF')) ) { alt13=1; } } else if ( ((LA13_0 >= '\u0000' && LA13_0 <= ')')||(LA13_0 >= '+' && LA13_0 <= '\uFFFF')) ) { alt13=1; } switch (alt13) { case 1 : // MicroParser.g:211:42: . { matchAny(); } break; default : break loop13; } } while (true); match("*/"); _channel=HIDDEN; } break; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "COMMENT" // $ANTLR start "STRINGLIETRAL" public final void mSTRINGLIETRAL() throws RecognitionException { try { int _type = STRINGLIETRAL; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:215:5: ( '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' ) // MicroParser.g:215:8: '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' { match('\"'); // MicroParser.g:215:12: ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* loop15: do { int alt15=3; int LA15_0 = input.LA(1); if ( (LA15_0=='\\') ) { alt15=1; } else if ( ((LA15_0 >= '\u0000' && LA15_0 <= '!')||(LA15_0 >= '#' && LA15_0 <= '[')||(LA15_0 >= ']' && LA15_0 <= '\uFFFF')) ) { alt15=2; } switch (alt15) { case 1 : // MicroParser.g:215:14: ESC_SEQ { mESC_SEQ(); } break; case 2 : // MicroParser.g:215:24: ~ ( '\\\\' | '\"' ) { if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '!')||(input.LA(1) >= '#' && input.LA(1) <= '[')||(input.LA(1) >= ']' && input.LA(1) <= '\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : break loop15; } } while (true); match('\"'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "STRINGLIETRAL" // $ANTLR start "OPERATORS" public final void mOPERATORS() throws RecognitionException { try { // MicroParser.g:219:11: ( ( ':=' ) | ( '+' ) | ( '-' ) | ( '*' ) | ( '/' ) | ( '=' ) | ( '!=' ) | ( '<' ) | ( '>' ) | ( '(' ) | ( ')' ) | ( ';' ) | ( ',' ) ) int alt16=13; switch ( input.LA(1) ) { case ':': { alt16=1; } break; case '+': { alt16=2; } break; case '-': { alt16=3; } break; case '*': { alt16=4; } break; case '/': { alt16=5; } break; case '=': { alt16=6; } break; case '!': { alt16=7; } break; case '<': { alt16=8; } break; case '>': { alt16=9; } break; case '(': { alt16=10; } break; case ')': { alt16=11; } break; case ';': { alt16=12; } break; case ',': { alt16=13; } break; default: NoViableAltException nvae = new NoViableAltException("", 16, 0, input); throw nvae; } switch (alt16) { case 1 : // MicroParser.g:219:13: ( ':=' ) { // MicroParser.g:219:13: ( ':=' ) // MicroParser.g:219:14: ':=' { match(":="); } } break; case 2 : // MicroParser.g:219:22: ( '+' ) { // MicroParser.g:219:22: ( '+' ) // MicroParser.g:219:23: '+' { match('+'); } } break; case 3 : // MicroParser.g:219:30: ( '-' ) { // MicroParser.g:219:30: ( '-' ) // MicroParser.g:219:31: '-' { match('-'); } } break; case 4 : // MicroParser.g:219:38: ( '*' ) { // MicroParser.g:219:38: ( '*' ) // MicroParser.g:219:39: '*' { match('*'); } } break; case 5 : // MicroParser.g:219:46: ( '/' ) { // MicroParser.g:219:46: ( '/' ) // MicroParser.g:219:47: '/' { match('/'); } } break; case 6 : // MicroParser.g:219:54: ( '=' ) { // MicroParser.g:219:54: ( '=' ) // MicroParser.g:219:55: '=' { match('='); } } break; case 7 : // MicroParser.g:219:62: ( '!=' ) { // MicroParser.g:219:62: ( '!=' ) // MicroParser.g:219:63: '!=' { match("!="); } } break; case 8 : // MicroParser.g:219:71: ( '<' ) { // MicroParser.g:219:71: ( '<' ) // MicroParser.g:219:72: '<' { match('<'); } } break; case 9 : // MicroParser.g:219:79: ( '>' ) { // MicroParser.g:219:79: ( '>' ) // MicroParser.g:219:80: '>' { match('>'); } } break; case 10 : // MicroParser.g:219:87: ( '(' ) { // MicroParser.g:219:87: ( '(' ) // MicroParser.g:219:88: '(' { match('('); } } break; case 11 : // MicroParser.g:219:95: ( ')' ) { // MicroParser.g:219:95: ( ')' ) // MicroParser.g:219:96: ')' { match(')'); } } break; case 12 : // MicroParser.g:219:103: ( ';' ) { // MicroParser.g:219:103: ( ';' ) // MicroParser.g:219:104: ';' { match(';'); } } break; case 13 : // MicroParser.g:219:111: ( ',' ) { // MicroParser.g:219:111: ( ',' ) // MicroParser.g:219:112: ',' { match(','); } } break; } } finally { // do for sure before leaving } } // $ANTLR end "OPERATORS" // $ANTLR start "WHITESPACE" public final void mWHITESPACE() throws RecognitionException { try { int _type = WHITESPACE; int _channel = DEFAULT_TOKEN_CHANNEL; // MicroParser.g:221:12: ( ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ ) // MicroParser.g:221:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ { // MicroParser.g:221:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ int cnt17=0; loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( ((LA17_0 >= '\t' && LA17_0 <= '\n')||(LA17_0 >= '\f' && LA17_0 <= '\r')||LA17_0==' ') ) { alt17=1; } switch (alt17) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '\t' && input.LA(1) <= '\n')||(input.LA(1) >= '\f' && input.LA(1) <= '\r')||input.LA(1)==' ' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt17 >= 1 ) break loop17; EarlyExitException eee = new EarlyExitException(17, input); throw eee; } cnt17++; } while (true); _channel = HIDDEN; } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } } // $ANTLR end "WHITESPACE" // $ANTLR start "EXPONENT" public final void mEXPONENT() throws RecognitionException { try { // MicroParser.g:225:10: ( ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ ) // MicroParser.g:225:12: ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ { if ( input.LA(1)=='E'||input.LA(1)=='e' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } // MicroParser.g:225:22: ( '+' | '-' )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0=='+'||LA18_0=='-') ) { alt18=1; } switch (alt18) { case 1 : // MicroParser.g: { if ( input.LA(1)=='+'||input.LA(1)=='-' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; } // MicroParser.g:225:33: ( '0' .. '9' )+ int cnt19=0; loop19: do { int alt19=2; int LA19_0 = input.LA(1); if ( ((LA19_0 >= '0' && LA19_0 <= '9')) ) { alt19=1; } switch (alt19) { case 1 : // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; default : if ( cnt19 >= 1 ) break loop19; EarlyExitException eee = new EarlyExitException(19, input); throw eee; } cnt19++; } while (true); } } finally { // do for sure before leaving } } // $ANTLR end "EXPONENT" // $ANTLR start "HEX_DIGIT" public final void mHEX_DIGIT() throws RecognitionException { try { // MicroParser.g:228:11: ( ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) ) // MicroParser.g: { if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'F')||(input.LA(1) >= 'a' && input.LA(1) <= 'f') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } } finally { // do for sure before leaving } } // $ANTLR end "HEX_DIGIT" // $ANTLR start "ESC_SEQ" public final void mESC_SEQ() throws RecognitionException { try { // MicroParser.g:232:5: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC ) int alt20=3; int LA20_0 = input.LA(1); if ( (LA20_0=='\\') ) { switch ( input.LA(2) ) { case '\"': case '\'': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': { alt20=1; } break; case 'u': { alt20=2; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { alt20=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 20, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 20, 0, input); throw nvae; } switch (alt20) { case 1 : // MicroParser.g:232:9: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) { match('\\'); if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 2 : // MicroParser.g:233:9: UNICODE_ESC { mUNICODE_ESC(); } break; case 3 : // MicroParser.g:234:9: OCTAL_ESC { mOCTAL_ESC(); } break; } } finally { // do for sure before leaving } } // $ANTLR end "ESC_SEQ" // $ANTLR start "OCTAL_ESC" public final void mOCTAL_ESC() throws RecognitionException { try { // MicroParser.g:239:5: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ) int alt21=3; int LA21_0 = input.LA(1); if ( (LA21_0=='\\') ) { int LA21_1 = input.LA(2); if ( ((LA21_1 >= '0' && LA21_1 <= '3')) ) { int LA21_2 = input.LA(3); if ( ((LA21_2 >= '0' && LA21_2 <= '7')) ) { int LA21_4 = input.LA(4); if ( ((LA21_4 >= '0' && LA21_4 <= '7')) ) { alt21=1; } else { alt21=2; } } else { alt21=3; } } else if ( ((LA21_1 >= '4' && LA21_1 <= '7')) ) { int LA21_3 = input.LA(3); if ( ((LA21_3 >= '0' && LA21_3 <= '7')) ) { alt21=2; } else { alt21=3; } } else { NoViableAltException nvae = new NoViableAltException("", 21, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 21, 0, input); throw nvae; } switch (alt21) { case 1 : // MicroParser.g:239:9: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) { match('\\'); if ( (input.LA(1) >= '0' && input.LA(1) <= '3') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 2 : // MicroParser.g:240:9: '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) { match('\\'); if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 3 : // MicroParser.g:241:9: '\\\\' ( '0' .. '7' ) { match('\\'); if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; } } finally { // do for sure before leaving } } // $ANTLR end "OCTAL_ESC" // $ANTLR start "UNICODE_ESC" public final void mUNICODE_ESC() throws RecognitionException { try { // MicroParser.g:246:5: ( '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ) // MicroParser.g:246:9: '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT { match('\\'); match('u'); mHEX_DIGIT(); mHEX_DIGIT(); mHEX_DIGIT(); mHEX_DIGIT(); } } finally { // do for sure before leaving } } // $ANTLR end "UNICODE_ESC" public void mTokens() throws RecognitionException { // MicroParser.g:1:8: ( T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | KEYWORD | IDENTIFIER | INTLITERAL | FLOATLITERAL | COMMENT | STRINGLIETRAL | WHITESPACE ) int alt22=37; alt22 = dfa22.predict(input); switch (alt22) { case 1 : // MicroParser.g:1:10: T__17 { mT__17(); } break; case 2 : // MicroParser.g:1:16: T__18 { mT__18(); } break; case 3 : // MicroParser.g:1:22: T__19 { mT__19(); } break; case 4 : // MicroParser.g:1:28: T__20 { mT__20(); } break; case 5 : // MicroParser.g:1:34: T__21 { mT__21(); } break; case 6 : // MicroParser.g:1:40: T__22 { mT__22(); } break; case 7 : // MicroParser.g:1:46: T__23 { mT__23(); } break; case 8 : // MicroParser.g:1:52: T__24 { mT__24(); } break; case 9 : // MicroParser.g:1:58: T__25 { mT__25(); } break; case 10 : // MicroParser.g:1:64: T__26 { mT__26(); } break; case 11 : // MicroParser.g:1:70: T__27 { mT__27(); } break; case 12 : // MicroParser.g:1:76: T__28 { mT__28(); } break; case 13 : // MicroParser.g:1:82: T__29 { mT__29(); } break; case 14 : // MicroParser.g:1:88: T__30 { mT__30(); } break; case 15 : // MicroParser.g:1:94: T__31 { mT__31(); } break; case 16 : // MicroParser.g:1:100: T__32 { mT__32(); } break; case 17 : // MicroParser.g:1:106: T__33 { mT__33(); } break; case 18 : // MicroParser.g:1:112: T__34 { mT__34(); } break; case 19 : // MicroParser.g:1:118: T__35 { mT__35(); } break; case 20 : // MicroParser.g:1:124: T__36 { mT__36(); } break; case 21 : // MicroParser.g:1:130: T__37 { mT__37(); } break; case 22 : // MicroParser.g:1:136: T__38 { mT__38(); } break; case 23 : // MicroParser.g:1:142: T__39 { mT__39(); } break; case 24 : // MicroParser.g:1:148: T__40 { mT__40(); } break; case 25 : // MicroParser.g:1:154: T__41 { mT__41(); } break; case 26 : // MicroParser.g:1:160: T__42 { mT__42(); } break; case 27 : // MicroParser.g:1:166: T__43 { mT__43(); } break; case 28 : // MicroParser.g:1:172: T__44 { mT__44(); } break; case 29 : // MicroParser.g:1:178: T__45 { mT__45(); } break; case 30 : // MicroParser.g:1:184: T__46 { mT__46(); } break; case 31 : // MicroParser.g:1:190: KEYWORD { mKEYWORD(); } break; case 32 : // MicroParser.g:1:198: IDENTIFIER { mIDENTIFIER(); } break; case 33 : // MicroParser.g:1:209: INTLITERAL { mINTLITERAL(); } break; case 34 : // MicroParser.g:1:220: FLOATLITERAL { mFLOATLITERAL(); } break; case 35 : // MicroParser.g:1:233: COMMENT { mCOMMENT(); } break; case 36 : // MicroParser.g:1:241: STRINGLIETRAL { mSTRINGLIETRAL(); } break; case 37 : // MicroParser.g:1:255: WHITESPACE { mWHITESPACE(); } break; } } protected DFA10 dfa10 = new DFA10(this); protected DFA22 dfa22 = new DFA22(this); static final String DFA10_eotS = "\5\uffff"; static final String DFA10_eofS = "\5\uffff"; static final String DFA10_minS = "\2\56\3\uffff"; static final String DFA10_maxS = "\1\71\1\145\3\uffff"; static final String DFA10_acceptS = "\2\uffff\1\2\1\1\1\3"; static final String DFA10_specialS = "\5\uffff}>"; static final String[] DFA10_transitionS = { "\1\2\1\uffff\12\1", "\1\3\1\uffff\12\1\13\uffff\1\4\37\uffff\1\4", "", "", "" }; static final short[] DFA10_eot = DFA.unpackEncodedString(DFA10_eotS); static final short[] DFA10_eof = DFA.unpackEncodedString(DFA10_eofS); static final char[] DFA10_min = DFA.unpackEncodedStringToUnsignedChars(DFA10_minS); static final char[] DFA10_max = DFA.unpackEncodedStringToUnsignedChars(DFA10_maxS); static final short[] DFA10_accept = DFA.unpackEncodedString(DFA10_acceptS); static final short[] DFA10_special = DFA.unpackEncodedString(DFA10_specialS); static final short[][] DFA10_transition; static { int numStates = DFA10_transitionS.length; DFA10_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA10_transition[i] = DFA.unpackEncodedString(DFA10_transitionS[i]); } } class DFA10 extends DFA { public DFA10(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 10; this.eot = DFA10_eot; this.eof = DFA10_eof; this.min = DFA10_min; this.max = DFA10_max; this.accept = DFA10_accept; this.special = DFA10_special; this.transition = DFA10_transition; } public String getDescription() { return "203:1: FLOATLITERAL : ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( EXPONENT )? | '.' ( '0' .. '9' )+ ( EXPONENT )? | ( '0' .. '9' )+ EXPONENT );"; } } static final String DFA22_eotS = "\7\uffff\1\40\1\41\5\uffff\14\32\1\uffff\1\62\6\uffff\6\32\1\71"+ "\11\32\1\uffff\3\32\1\111\2\32\1\uffff\1\114\14\32\1\131\1\32\1"+ "\uffff\2\32\1\uffff\1\32\1\136\3\32\1\142\1\32\1\144\2\32\1\147"+ "\1\150\1\uffff\1\151\1\152\2\32\1\uffff\3\32\1\uffff\1\160\1\uffff"+ "\1\161\1\32\4\uffff\2\32\1\165\1\166\1\167\2\uffff\2\32\1\172\3"+ "\uffff\1\32\1\174\1\uffff\1\150\1\uffff"; static final String DFA22_eofS = "\175\uffff"; static final String DFA22_minS = "\1\11\6\uffff\1\55\1\52\5\uffff\1\105\2\114\1\106\1\122\1\105\1"+ "\124\1\110\1\116\1\117\1\122\1\117\1\uffff\1\56\6\uffff\1\107\1"+ "\105\1\123\1\104\1\117\1\116\1\60\1\124\1\117\1\101\1\122\1\105"+ "\1\124\2\111\1\116\1\uffff\1\111\1\101\1\105\1\60\1\101\1\103\1"+ "\uffff\1\60\1\107\1\104\1\105\1\125\1\111\1\116\1\111\1\104\2\124"+ "\1\116\1\113\1\60\1\106\1\uffff\2\124\1\uffff\1\122\1\60\1\101\1"+ "\122\1\116\1\60\1\114\1\60\1\105\1\111\2\60\1\uffff\2\60\1\111\1"+ "\101\1\uffff\1\124\1\116\1\107\1\uffff\1\60\1\uffff\1\60\1\116\4"+ "\uffff\1\117\1\115\3\60\2\uffff\1\125\1\116\1\60\3\uffff\1\105\1"+ "\60\1\uffff\1\60\1\uffff"; static final String DFA22_maxS = "\1\172\6\uffff\1\55\1\52\5\uffff\1\122\1\116\1\125\1\116\1\122\1"+ "\105\1\124\1\110\1\116\1\117\1\122\1\117\1\uffff\1\145\6\uffff\1"+ "\107\1\105\1\123\1\104\1\117\1\116\1\172\1\124\1\117\1\124\1\122"+ "\1\105\1\124\2\111\1\116\1\uffff\1\111\1\101\1\105\1\172\1\101\1"+ "\103\1\uffff\1\172\1\107\1\104\1\105\1\125\1\111\1\116\1\111\1\104"+ "\2\124\1\116\1\113\1\172\1\106\1\uffff\2\124\1\uffff\1\122\1\172"+ "\1\101\1\122\1\116\1\172\1\114\1\172\1\105\1\111\2\172\1\uffff\2"+ "\172\1\111\1\101\1\uffff\1\124\1\116\1\107\1\uffff\1\172\1\uffff"+ "\1\172\1\116\4\uffff\1\117\1\115\3\172\2\uffff\1\125\1\116\1\172"+ "\3\uffff\1\105\1\172\1\uffff\1\172\1\uffff"; static final String DFA22_acceptS = "\1\uffff\1\1\1\2\1\3\1\4\1\5\1\6\2\uffff\1\11\1\12\1\13\1\14\1\15"+ "\14\uffff\1\40\1\uffff\1\42\1\44\1\45\1\43\1\7\1\10\20\uffff\1\41"+ "\6\uffff\1\24\17\uffff\1\20\2\uffff\1\25\14\uffff\1\17\4\uffff\1"+ "\27\3\uffff\1\33\1\uffff\1\35\2\uffff\1\16\1\37\1\21\1\22\5\uffff"+ "\1\34\1\36\3\uffff\1\30\1\31\1\32\2\uffff\1\26\1\uffff\1\23"; static final String DFA22_specialS = "\175\uffff}>"; static final String[] DFA22_transitionS = { "\2\36\1\uffff\2\36\22\uffff\1\36\1\1\1\35\5\uffff\1\2\1\3\1"+ "\4\1\5\1\6\1\7\1\34\1\10\12\33\1\11\1\12\1\13\1\14\1\15\2\uffff"+ "\1\32\1\16\1\31\1\32\1\17\1\20\2\32\1\21\6\32\1\22\1\32\1\23"+ "\1\24\1\25\1\26\1\27\1\30\3\32\4\uffff\1\32\1\uffff\32\32", "", "", "", "", "", "", "\1\37", "\1\37", "", "", "", "", "", "\1\42\14\uffff\1\43", "\1\44\1\uffff\1\45", "\1\46\10\uffff\1\47", "\1\50\7\uffff\1\51", "\1\52", "\1\53", "\1\54", "\1\55", "\1\56", "\1\57", "\1\60", "\1\61", "", "\1\34\1\uffff\12\33\13\uffff\1\34\37\uffff\1\34", "", "", "", "", "", "", "\1\63", "\1\64", "\1\65", "\1\66", "\1\67", "\1\70", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\72", "\1\73", "\1\74\16\uffff\1\75\3\uffff\1\76", "\1\77", "\1\100", "\1\101", "\1\102", "\1\103", "\1\104", "", "\1\105", "\1\106", "\1\107", "\12\32\7\uffff\10\32\1\110\21\32\4\uffff\1\32\1\uffff\32\32", "\1\112", "\1\113", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\115", "\1\116", "\1\117", "\1\120", "\1\121", "\1\122", "\1\123", "\1\124", "\1\125", "\1\126", "\1\127", "\1\130", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\132", "", "\1\133", "\1\134", "", "\1\135", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\137", "\1\140", "\1\141", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\143", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\145", "\1\146", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\153", "\1\154", "", "\1\155", "\1\156", "\1\157", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\1\162", "", "", "", "", "\1\163", "\1\164", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "", "\1\170", "\1\171", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "", "", "\1\173", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "" }; static final short[] DFA22_eot = DFA.unpackEncodedString(DFA22_eotS); static final short[] DFA22_eof = DFA.unpackEncodedString(DFA22_eofS); static final char[] DFA22_min = DFA.unpackEncodedStringToUnsignedChars(DFA22_minS); static final char[] DFA22_max = DFA.unpackEncodedStringToUnsignedChars(DFA22_maxS); static final short[] DFA22_accept = DFA.unpackEncodedString(DFA22_acceptS); static final short[] DFA22_special = DFA.unpackEncodedString(DFA22_specialS); static final short[][] DFA22_transition; static { int numStates = DFA22_transitionS.length; DFA22_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA22_transition[i] = DFA.unpackEncodedString(DFA22_transitionS[i]); } } class DFA22 extends DFA { public DFA22(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 22; this.eot = DFA22_eot; this.eof = DFA22_eof; this.min = DFA22_min; this.max = DFA22_max; this.accept = DFA22_accept; this.special = DFA22_special; this.transition = DFA22_transition; } public String getDescription() { return "1:1: Tokens : ( T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | KEYWORD | IDENTIFIER | INTLITERAL | FLOATLITERAL | COMMENT | STRINGLIETRAL | WHITESPACE );"; } } }
82,839
0.334697
0.27854
3,076
25.93108
24.18693
368
false
false
0
0
0
0
0
0
0.473992
false
false
2
ed013c90219176bdee0fab3ccf2f480bc3dc646c
20,968,030,409,528
805985326d824afc4d3df577f5e6d8de9f25ef71
/src/org/ds/handlingtypes/filehandler/FileHandler.java
2a1f82a4607c28b5cef9e9ea76a5b19861bc4b74
[ "MIT" ]
permissive
zhanghehua/Desktop-Search-1
https://github.com/zhanghehua/Desktop-Search-1
8b5dcfc68d1dcc578a894cba580d2160a8c6c978
93b13c0bf2791711fa07b5204b09c6883fa8ea92
refs/heads/master
2019-04-02T02:22:27.308000
2014-04-21T06:03:54
2014-04-21T06:03:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ds.handlingtypes.filehandler; import java.io.File; import org.apache.lucene.document.Document; /** * 定义getDocument方法 */ public interface FileHandler { /** * 从文件获取一个Document类的实例 * @param file 文件对象 * @return 一个新的Document类的实例 * @throws FileHandlerException DocumentHandler异常 */ Document getDocument(File file) throws FileHandlerException; }
GB18030
Java
458
java
FileHandler.java
Java
[]
null
[]
package org.ds.handlingtypes.filehandler; import java.io.File; import org.apache.lucene.document.Document; /** * 定义getDocument方法 */ public interface FileHandler { /** * 从文件获取一个Document类的实例 * @param file 文件对象 * @return 一个新的Document类的实例 * @throws FileHandlerException DocumentHandler异常 */ Document getDocument(File file) throws FileHandlerException; }
458
0.7
0.7
20
19
16.935171
53
false
false
0
0
0
0
0
0
0.2
false
false
2
c65cb02cc42f6987bb96ab49e8e912fe7cbd66d1
5,626,407,182,489
eb3a2284fad8aac2e02153e8ad9eee4804119b23
/src/main/java/org/jeecgframework/core/common/model/common/QueryCondition.java
e792f1fc55c10ddc32e54aace326221139755598
[ "Apache-2.0" ]
permissive
capricornstone/jeecg-3.8-hzwm
https://github.com/capricornstone/jeecg-3.8-hzwm
c9d10ba1c4c73630ef8f8e2a90954362f1969edd
f5d0042db7f2c3e8b00f99b6cf39ea60f1e58e82
refs/heads/master
2022-12-23T10:51:47.038000
2019-07-08T07:32:45
2019-07-08T07:32:45
195,143,819
2
1
Apache-2.0
false
2022-12-06T00:43:02
2019-07-04T00:37:43
2021-09-13T07:46:40
2022-12-06T00:43:02
42,113
1
1
17
JavaScript
false
false
package org.jeecgframework.core.common.model.common; import java.util.List; import org.jeecgframework.core.util.PropertiesUtil; public class QueryCondition { Integer id; String state; String field; String type; String condition; String value; String relation; List<QueryCondition> children; public List<QueryCondition> getChildren() { return children; } public void setChildren(List<QueryCondition> children) { this.children = children; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getRelation() { return relation; } public void setRelation(String relation) { this.relation = relation; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String toString(){ if(field == null || "".equals(field)){ return ""; } StringBuffer sb =new StringBuffer(); sb.append(this.relation).append(" "); sb.append(this.field).append(" ") .append(this.condition).append(" "); if("Integer".equals(this.type) ||"BigDecimal".equals(this.type) ||"Double".equals(this.type) ||"Long".equals(this.type)){//TODO 需要按类型处理 sb.append(this.value); }else if("Date".equals(this.type)){ PropertiesUtil util = new PropertiesUtil("sysConfig.properties"); String dbtype = util.readProperty("jdbc.url.jeecg"); if("oracle".equalsIgnoreCase(dbtype)){ sb.append("to_date("); } //mysql slqserver无须函数,其他数据库情况未处理 sb.append("'").append(this.value).append("'"); if("oracle".equalsIgnoreCase(dbtype)){ sb.append(",'yyyy-MM-dd')"); } }else { sb.append("'").append(this.value.replaceAll("'","\'")).append("'");//TODO 需要处理特殊字符 } return sb.toString(); } }
UTF-8
Java
2,263
java
QueryCondition.java
Java
[]
null
[]
package org.jeecgframework.core.common.model.common; import java.util.List; import org.jeecgframework.core.util.PropertiesUtil; public class QueryCondition { Integer id; String state; String field; String type; String condition; String value; String relation; List<QueryCondition> children; public List<QueryCondition> getChildren() { return children; } public void setChildren(List<QueryCondition> children) { this.children = children; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getRelation() { return relation; } public void setRelation(String relation) { this.relation = relation; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String toString(){ if(field == null || "".equals(field)){ return ""; } StringBuffer sb =new StringBuffer(); sb.append(this.relation).append(" "); sb.append(this.field).append(" ") .append(this.condition).append(" "); if("Integer".equals(this.type) ||"BigDecimal".equals(this.type) ||"Double".equals(this.type) ||"Long".equals(this.type)){//TODO 需要按类型处理 sb.append(this.value); }else if("Date".equals(this.type)){ PropertiesUtil util = new PropertiesUtil("sysConfig.properties"); String dbtype = util.readProperty("jdbc.url.jeecg"); if("oracle".equalsIgnoreCase(dbtype)){ sb.append("to_date("); } //mysql slqserver无须函数,其他数据库情况未处理 sb.append("'").append(this.value).append("'"); if("oracle".equalsIgnoreCase(dbtype)){ sb.append(",'yyyy-MM-dd')"); } }else { sb.append("'").append(this.value.replaceAll("'","\'")).append("'");//TODO 需要处理特殊字符 } return sb.toString(); } }
2,263
0.678166
0.678166
98
21.479591
17.702894
85
false
false
0
0
0
0
0
0
2.040816
false
false
2
70d01d9345281f086bc5d1ffea36b2545ea7e75c
1,322,849,934,127
cd0efa127073847b7b00a50a816d5a910d815602
/src/test/java/bdd/example2/bddexample2/page/objects/MainPage.java
ca357412b16af52ff22c5cd724a5e2d26b6cd927
[]
no_license
alanwardrope/bddexample2
https://github.com/alanwardrope/bddexample2
9e360338ee7b5f6226541c63e7d1e78cd39dc8b5
1d1dae2ccce5a331bde9ac97fd16481ee0d79c9e
refs/heads/master
2021-01-11T16:02:32.501000
2017-01-25T07:30:42
2017-01-25T07:30:42
79,992,711
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bdd.example2.bddexample2.page.objects; /** * Created by vanwh on 18/01/2017. */ import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import bdd.example2.bddexample2.framework.ParentPage; import org.openqa.selenium.WebElement; import java.util.List; public class MainPage extends ParentPage { public MainPage(WebDriver driver) { super(driver); } public void clickTab(String tab) { click(tab); } //private static final String SECTION_HEADER = "//*[@id='mainContent']/h2/text()='%s'"; private static final String SECTION_HEADER = "//*[@id='mainContent']/h2/text()"; public boolean hasSectionHeaderFor(String sectionHeaderText) { //boolean isTextPresent=false; By hasSectionHeader = By.xpath(String.format(SECTION_HEADER, sectionHeaderText)); System.out.println("The section header is : " + hasSectionHeader); //isTextPresent = driver.findElement(By.xpath(String.format(SECTION_HEADER, sectionHeaderText)) return hasSection(hasSectionHeader, sectionHeaderText); } }
UTF-8
Java
1,084
java
MainPage.java
Java
[ { "context": "mple2.bddexample2.page.objects;\n\n/**\n * Created by vanwh on 18/01/2017.\n */\n\nimport org.openqa.selenium.By", "end": 71, "score": 0.999695897102356, "start": 66, "tag": "USERNAME", "value": "vanwh" } ]
null
[]
package bdd.example2.bddexample2.page.objects; /** * Created by vanwh on 18/01/2017. */ import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import bdd.example2.bddexample2.framework.ParentPage; import org.openqa.selenium.WebElement; import java.util.List; public class MainPage extends ParentPage { public MainPage(WebDriver driver) { super(driver); } public void clickTab(String tab) { click(tab); } //private static final String SECTION_HEADER = "//*[@id='mainContent']/h2/text()='%s'"; private static final String SECTION_HEADER = "//*[@id='mainContent']/h2/text()"; public boolean hasSectionHeaderFor(String sectionHeaderText) { //boolean isTextPresent=false; By hasSectionHeader = By.xpath(String.format(SECTION_HEADER, sectionHeaderText)); System.out.println("The section header is : " + hasSectionHeader); //isTextPresent = driver.findElement(By.xpath(String.format(SECTION_HEADER, sectionHeaderText)) return hasSection(hasSectionHeader, sectionHeaderText); } }
1,084
0.708487
0.695572
35
30
30.964497
103
false
false
0
0
0
0
0
0
0.485714
false
false
2
d12b464acf061609e8325b15407e183b773b1839
10,411,000,734,208
12823b910d5eb51d5907f38a5de0c4648ae27308
/src/io/trivium/extension/binding/webui/RegistryRequestHandler.java
d8f3957baa59a1a6ba6017ccd2bbf85a1a187558
[ "Apache-2.0" ]
permissive
JensWalter/trivium
https://github.com/JensWalter/trivium
428330f4cb09229312a601581c380a67f77b7467
e0000bbe59429b1b90f2e1b208fb3be222927a90
refs/heads/master
2021-05-31T10:15:47.682000
2016-03-26T13:29:25
2016-03-26T13:29:25
30,550,214
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2016 Jens Walter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trivium.extension.binding.webui; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import io.trivium.NVList; import io.trivium.NVPair; import io.trivium.anystore.TypeRef; import io.trivium.extension.Binding; import io.trivium.extension.BindingState; import io.trivium.extension.Fact; import io.trivium.extension.Task; import io.trivium.glue.binding.http.HttpUtils; import io.trivium.glue.binding.http.Session; import io.trivium.glue.om.Json; import io.trivium.Registry; import io.trivium.anystore.statics.MimeTypes; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class RegistryRequestHandler implements HttpHandler { Logger logger = Logger.getLogger(getClass().getName()); @Override public void handle(HttpExchange httpexchange) { logger.log(Level.FINE, "registry handler"); NVList params = HttpUtils.getInputAsNVList(httpexchange); /** list {"command" : "list"} */ /** {"id" : "...", "command" : "start"|"stop"|"status"} */ Session s = new Session(httpexchange); try { String cmd = params.findValue("command"); if (cmd.equals("list")) { Registry.INSTANCE.reload(); NVList list = new NVList(); Collection<Binding> bindings = Registry.INSTANCE.getAllBindings(); NVPair nvbind = new NVPair("binding"); for (Binding binding : bindings) { nvbind.addValue(binding.getTypeRef().toString()); list.add(new NVPair(binding.getTypeRef().toString(), binding.getName())); } list.add(nvbind); ConcurrentHashMap<TypeRef, Class<?extends Fact>> types = Registry.INSTANCE.types; NVPair tybind = new NVPair("type"); for (Class<? extends Fact> clazz : types.values()) { Fact prototype = clazz.newInstance(); tybind.addValue(prototype.getTypeRef().toString()); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getFactName())); } list.add(tybind); ConcurrentHashMap<TypeRef, Class<? extends Task>> tasks = Registry.INSTANCE.tasks; NVPair tskpair = new NVPair("task"); for (Class<? extends Task> clazz : tasks.values()) { Task prototype = clazz.newInstance(); tskpair.addValue(prototype.getTypeRef().toString()); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getName())); } list.add(tskpair); String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("listTypes")) { Registry.INSTANCE.reload(); NVList list = new NVList(); ConcurrentHashMap<TypeRef, Class<?extends Fact>> types = Registry.INSTANCE.types; for (Class<? extends Fact> clazz : types.values()) { Fact prototype = clazz.newInstance(); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getFactName())); } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("listTasks")) { Registry.INSTANCE.reload(); NVList list = new NVList(); ConcurrentHashMap<TypeRef, Class<? extends Task>> tasks = Registry.INSTANCE.tasks; for (Class<? extends Task> clazz : tasks.values()) { Task prototype = clazz.newInstance(); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getName())); } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("listBindings")) { Registry.INSTANCE.reload(); NVList list = new NVList(); Collection<Binding> bindings = Registry.INSTANCE.getAllBindings(); for (Binding binding : bindings) { list.add(new NVPair(binding.getTypeRef().toString(), binding.getName())); } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("status")) { String id = params.findValue("id"); TypeRef ref = TypeRef.getInstance(id); Binding bind = Registry.INSTANCE.getBinding(ref); if (bind != null) { BindingState state = bind.getState(); NVList list = new NVList(); list.add(new NVPair("id",id)); switch (state) { case stopped: list.add(new NVPair("state", "stopped")); break; case running: list.add(new NVPair("state", "running")); break; } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else { s.ok(); } } else if (cmd.equals("start")) { String id = params.findValue("id"); TypeRef ref = TypeRef.getInstance(id); ArrayList<LogRecord> logs = Registry.INSTANCE.startBinding(ref); if(logs.size()==0) { s.ok(); }else{ StringBuilder sb = new StringBuilder(); for(LogRecord record: logs) { sb.append(record.getLevel().toString() + " "+record.getLoggerName() + ": " + record.getMessage()); } s.ok("text/plain",sb.toString()); } } else if (cmd.equals("stop")) { String id = params.findValue("id"); TypeRef ref = TypeRef.getInstance(id); Registry.INSTANCE.getBinding(ref).stopBinding(); s.ok(); } else { s.ok(); } } catch (Exception ex) { logger.log(Level.SEVERE, "error while processing registry request", ex); s.ok(); } } }
UTF-8
Java
7,383
java
RegistryRequestHandler.java
Java
[ { "context": "/*\n * Copyright 2016 Jens Walter\n *\n * Licensed under the Apache License, Version ", "end": 32, "score": 0.9996429681777954, "start": 21, "tag": "NAME", "value": "Jens Walter" } ]
null
[]
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trivium.extension.binding.webui; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import io.trivium.NVList; import io.trivium.NVPair; import io.trivium.anystore.TypeRef; import io.trivium.extension.Binding; import io.trivium.extension.BindingState; import io.trivium.extension.Fact; import io.trivium.extension.Task; import io.trivium.glue.binding.http.HttpUtils; import io.trivium.glue.binding.http.Session; import io.trivium.glue.om.Json; import io.trivium.Registry; import io.trivium.anystore.statics.MimeTypes; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class RegistryRequestHandler implements HttpHandler { Logger logger = Logger.getLogger(getClass().getName()); @Override public void handle(HttpExchange httpexchange) { logger.log(Level.FINE, "registry handler"); NVList params = HttpUtils.getInputAsNVList(httpexchange); /** list {"command" : "list"} */ /** {"id" : "...", "command" : "start"|"stop"|"status"} */ Session s = new Session(httpexchange); try { String cmd = params.findValue("command"); if (cmd.equals("list")) { Registry.INSTANCE.reload(); NVList list = new NVList(); Collection<Binding> bindings = Registry.INSTANCE.getAllBindings(); NVPair nvbind = new NVPair("binding"); for (Binding binding : bindings) { nvbind.addValue(binding.getTypeRef().toString()); list.add(new NVPair(binding.getTypeRef().toString(), binding.getName())); } list.add(nvbind); ConcurrentHashMap<TypeRef, Class<?extends Fact>> types = Registry.INSTANCE.types; NVPair tybind = new NVPair("type"); for (Class<? extends Fact> clazz : types.values()) { Fact prototype = clazz.newInstance(); tybind.addValue(prototype.getTypeRef().toString()); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getFactName())); } list.add(tybind); ConcurrentHashMap<TypeRef, Class<? extends Task>> tasks = Registry.INSTANCE.tasks; NVPair tskpair = new NVPair("task"); for (Class<? extends Task> clazz : tasks.values()) { Task prototype = clazz.newInstance(); tskpair.addValue(prototype.getTypeRef().toString()); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getName())); } list.add(tskpair); String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("listTypes")) { Registry.INSTANCE.reload(); NVList list = new NVList(); ConcurrentHashMap<TypeRef, Class<?extends Fact>> types = Registry.INSTANCE.types; for (Class<? extends Fact> clazz : types.values()) { Fact prototype = clazz.newInstance(); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getFactName())); } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("listTasks")) { Registry.INSTANCE.reload(); NVList list = new NVList(); ConcurrentHashMap<TypeRef, Class<? extends Task>> tasks = Registry.INSTANCE.tasks; for (Class<? extends Task> clazz : tasks.values()) { Task prototype = clazz.newInstance(); list.add(new NVPair(prototype.getTypeRef().toString(), prototype.getName())); } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("listBindings")) { Registry.INSTANCE.reload(); NVList list = new NVList(); Collection<Binding> bindings = Registry.INSTANCE.getAllBindings(); for (Binding binding : bindings) { list.add(new NVPair(binding.getTypeRef().toString(), binding.getName())); } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else if (cmd.equals("status")) { String id = params.findValue("id"); TypeRef ref = TypeRef.getInstance(id); Binding bind = Registry.INSTANCE.getBinding(ref); if (bind != null) { BindingState state = bind.getState(); NVList list = new NVList(); list.add(new NVPair("id",id)); switch (state) { case stopped: list.add(new NVPair("state", "stopped")); break; case running: list.add(new NVPair("state", "running")); break; } String json = Json.NVPairsToJson(list); s.ok(MimeTypes.getMimeType("json"), json); } else { s.ok(); } } else if (cmd.equals("start")) { String id = params.findValue("id"); TypeRef ref = TypeRef.getInstance(id); ArrayList<LogRecord> logs = Registry.INSTANCE.startBinding(ref); if(logs.size()==0) { s.ok(); }else{ StringBuilder sb = new StringBuilder(); for(LogRecord record: logs) { sb.append(record.getLevel().toString() + " "+record.getLoggerName() + ": " + record.getMessage()); } s.ok("text/plain",sb.toString()); } } else if (cmd.equals("stop")) { String id = params.findValue("id"); TypeRef ref = TypeRef.getInstance(id); Registry.INSTANCE.getBinding(ref).stopBinding(); s.ok(); } else { s.ok(); } } catch (Exception ex) { logger.log(Level.SEVERE, "error while processing registry request", ex); s.ok(); } } }
7,378
0.546119
0.5449
168
42.94643
25.190998
101
false
false
0
0
0
0
0
0
0.738095
false
false
2
588b69a20d7fd6c40f809841fa4764aa080075da
11,218,454,583,541
09660d14c28a5a884d8da35a94133264bd9d67d6
/site-alitalia/component/src/main/java/com/alitalia/aem/consumer/booking/render/SeatsMapRender.java
dc5b0b936085e091c3cc2f23e69323b02814893d
[]
no_license
R0b3rt0M/az
https://github.com/R0b3rt0M/az
9d4070111a4e34b7ae8c35fdbf996c076baa1e08
3f48265dc81a0b1c134347c8865c30b5d1b1ae3d
refs/heads/master
2020-08-08T06:35:44.906000
2019-10-08T20:52:31
2019-10-08T20:52:31
213,745,864
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alitalia.aem.consumer.booking.render; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alitalia.aem.common.data.home.SeatData; import com.alitalia.aem.common.data.home.SeatMapData; import com.alitalia.aem.common.data.home.SeatMapRowData; import com.alitalia.aem.common.data.home.SeatMapSectorData; import com.alitalia.aem.common.data.home.enumerations.AvailabilitySeatEnum; import com.alitalia.aem.common.data.home.enumerations.TypeSeatEnum; public class SeatsMapRender { private Logger logger = LoggerFactory.getLogger(this.getClass()); private final static String NOT_EXISTS = ""; private final static String OCCUPIED_SEAT = "occupied"; private final static String AVAILABLE_SEAT = "available"; private final static String AISLE_SEAT = "seatAisle"; private final static String LEFT_EXIT = "i-emergencyL"; private final static String RIGHT_EXIT = "i-emergencyR"; private SeatMapData seatMapData; private String[] sectorLabel; private String[][] sectorNavigation; private String[][] sectorRowLabel; private String[][] headerMap; private String[][][] seatsMap; private HashMap<Integer, String> seatToHeader; private String classSeatMap; public SeatsMapRender () { init(); } public SeatsMapRender (SeatMapData seatMapData) { this.seatMapData = seatMapData; init(); } private void init() { this.sectorLabel = null; this.sectorRowLabel = null; this.headerMap = null; this.seatsMap = null; this.seatToHeader = null; this.sectorNavigation = null; // check data if (seatMapData == null) { return; } if (seatMapData.getSeatMapSectors() == null || seatMapData.getSeatMapSectors().size() == 0) { logger.warn("Ignored seat map data: sectors list is null or empty"); return; } for (SeatMapSectorData sector : seatMapData.getSeatMapSectors()) { if (sector.getSeatMapRows() == null || sector.getSeatMapRows().size() == 0) { logger.warn("Ignored seat map data: rows list for a section is null or empty"); return; } for (SeatMapRowData row : sector.getSeatMapRows()) { if (row.getSeats() == null || row.getSeats().size() == 0) { logger.warn("Ignored seat map data: seats list for a row is null or empty"); return; } } } // process data List<Integer> airplaneStructure = new ArrayList<Integer>(); this.sectorLabel = new String[seatMapData.getSeatMapSectors().size()]; this.sectorRowLabel = new String[seatMapData.getSeatMapSectors().size()][]; this.headerMap = new String[seatMapData.getSeatMapSectors().size()][]; this.seatsMap = new String[seatMapData.getSeatMapSectors().size()][][]; this.sectorNavigation = new String[seatMapData.getSeatMapSectors().size()][2]; int sectorIndex = -1; int rowIndex = -1; int seatIndex = -1; sectorIndex = -1; ListIterator<SeatMapSectorData> sectorsIterator = (new LinkedList<SeatMapSectorData>(seatMapData.getSeatMapSectors())).listIterator(); while (sectorsIterator.hasNext()) { sectorIndex++; SeatMapSectorData section = sectorsIterator.next(); // for each section, prepare the section label this.sectorLabel[sectorIndex] = StringUtils.stripStart(section.getStartingRow(), "0") + "-" + StringUtils.stripStart(section.getEndingRow(), "0"); this.seatsMap[sectorIndex] = new String[section.getSeatMapRows().size()][]; rowIndex = -1; for (SeatMapRowData sectionRow : section.getSeatMapRows()) { rowIndex++; // on first row of each section, initialize the header // label map and the row label for the section if (rowIndex == 0) { // include room for two additional header elements for the exit // graphical indications, presetting them to an empty string this.headerMap[sectorIndex] = new String[sectionRow.getSeats().size() + 2]; this.headerMap[sectorIndex][0] = ""; this.headerMap[sectorIndex][sectionRow.getSeats().size() + 1] = ""; this.sectorRowLabel[sectorIndex] = new String[section.getSeatMapRows().size()]; } // set the global row label this.sectorRowLabel[sectorIndex][rowIndex] = sectionRow.getNumber().replaceAll("^[0]*",""); // include room for two additional elements for the exit graphical indications this.seatsMap[sectorIndex][rowIndex] = new String[sectionRow.getSeats().size() + 2]; // preset the first and last seats (used to display emergency exists) to blank this.seatsMap[sectorIndex][rowIndex][0] = NOT_EXISTS; this.seatsMap[sectorIndex][rowIndex][sectionRow.getSeats().size() + 1] = NOT_EXISTS; seatIndex = -1; int cont = 0; for (SeatData seat : sectionRow.getSeats()) { seatIndex++; // on first row of each section, initialize the elements of the header label map for the section if (rowIndex == 0) { this.headerMap[sectorIndex][seatIndex + 1] = seat.getNumber(); if (!seat.getNumber().equals("")) { cont++; } else { airplaneStructure.add(cont); cont = 0; } } // set seat type if (seat.getTypeSeat() == TypeSeatEnum.AISLE) { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = AISLE_SEAT; } else if (seat.getTypeSeat() == TypeSeatEnum.NOT_EXIST) { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = NOT_EXISTS; } else { if (seat.getAvailability() == AvailabilitySeatEnum.FREE) { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = AVAILABLE_SEAT; } else { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = OCCUPIED_SEAT; } } // evaluate emergency exits if (seat.getTypeSeat() == TypeSeatEnum.WINDOW_EXIT_SEAT) { if (seatIndex == 0) { seatsMap[sectorIndex][rowIndex][0] = LEFT_EXIT; } else if (seatIndex == (sectionRow.getSeats().size() - 1)) { seatsMap[sectorIndex][rowIndex][sectionRow.getSeats().size() + 1] = RIGHT_EXIT; } } } } } sectorIndex = -1; sectorsIterator = (new LinkedList<SeatMapSectorData>(seatMapData.getSeatMapSectors())).listIterator(); while (sectorsIterator.hasNext()) { sectorIndex++; //first check if this section has a previous one if (sectorsIterator.hasPrevious()){ sectorNavigation[sectorIndex][0] = sectorLabel[sectorIndex - 1]; } else { sectorNavigation[sectorIndex][0] = ""; } sectorsIterator.next(); //check if this section has a next one if (sectorsIterator.hasNext()){ sectorNavigation[sectorIndex][1] = sectorLabel[sectorIndex + 1]; } else { sectorNavigation[sectorIndex][1] = ""; } } classSeatMap = "seatMap"; for (Integer structureCol : airplaneStructure) { classSeatMap += "_" + structureCol.toString(); } } public SeatMapData getSeatMapData() { return seatMapData; } public String[][] getHeaderMap() { return headerMap; } public String[] getSectorLabel() { return sectorLabel; } public String[][] getSectorNavigation() { return sectorNavigation; } public String[][] getSectorRowLabel() { return sectorRowLabel; } public String[][][] getSeatsMap() { return seatsMap; } public HashMap<Integer, String> getSeatToHeader() { return seatToHeader; } public String getClassSeatMap() { return classSeatMap; } }
UTF-8
Java
7,475
java
SeatsMapRender.java
Java
[]
null
[]
package com.alitalia.aem.consumer.booking.render; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alitalia.aem.common.data.home.SeatData; import com.alitalia.aem.common.data.home.SeatMapData; import com.alitalia.aem.common.data.home.SeatMapRowData; import com.alitalia.aem.common.data.home.SeatMapSectorData; import com.alitalia.aem.common.data.home.enumerations.AvailabilitySeatEnum; import com.alitalia.aem.common.data.home.enumerations.TypeSeatEnum; public class SeatsMapRender { private Logger logger = LoggerFactory.getLogger(this.getClass()); private final static String NOT_EXISTS = ""; private final static String OCCUPIED_SEAT = "occupied"; private final static String AVAILABLE_SEAT = "available"; private final static String AISLE_SEAT = "seatAisle"; private final static String LEFT_EXIT = "i-emergencyL"; private final static String RIGHT_EXIT = "i-emergencyR"; private SeatMapData seatMapData; private String[] sectorLabel; private String[][] sectorNavigation; private String[][] sectorRowLabel; private String[][] headerMap; private String[][][] seatsMap; private HashMap<Integer, String> seatToHeader; private String classSeatMap; public SeatsMapRender () { init(); } public SeatsMapRender (SeatMapData seatMapData) { this.seatMapData = seatMapData; init(); } private void init() { this.sectorLabel = null; this.sectorRowLabel = null; this.headerMap = null; this.seatsMap = null; this.seatToHeader = null; this.sectorNavigation = null; // check data if (seatMapData == null) { return; } if (seatMapData.getSeatMapSectors() == null || seatMapData.getSeatMapSectors().size() == 0) { logger.warn("Ignored seat map data: sectors list is null or empty"); return; } for (SeatMapSectorData sector : seatMapData.getSeatMapSectors()) { if (sector.getSeatMapRows() == null || sector.getSeatMapRows().size() == 0) { logger.warn("Ignored seat map data: rows list for a section is null or empty"); return; } for (SeatMapRowData row : sector.getSeatMapRows()) { if (row.getSeats() == null || row.getSeats().size() == 0) { logger.warn("Ignored seat map data: seats list for a row is null or empty"); return; } } } // process data List<Integer> airplaneStructure = new ArrayList<Integer>(); this.sectorLabel = new String[seatMapData.getSeatMapSectors().size()]; this.sectorRowLabel = new String[seatMapData.getSeatMapSectors().size()][]; this.headerMap = new String[seatMapData.getSeatMapSectors().size()][]; this.seatsMap = new String[seatMapData.getSeatMapSectors().size()][][]; this.sectorNavigation = new String[seatMapData.getSeatMapSectors().size()][2]; int sectorIndex = -1; int rowIndex = -1; int seatIndex = -1; sectorIndex = -1; ListIterator<SeatMapSectorData> sectorsIterator = (new LinkedList<SeatMapSectorData>(seatMapData.getSeatMapSectors())).listIterator(); while (sectorsIterator.hasNext()) { sectorIndex++; SeatMapSectorData section = sectorsIterator.next(); // for each section, prepare the section label this.sectorLabel[sectorIndex] = StringUtils.stripStart(section.getStartingRow(), "0") + "-" + StringUtils.stripStart(section.getEndingRow(), "0"); this.seatsMap[sectorIndex] = new String[section.getSeatMapRows().size()][]; rowIndex = -1; for (SeatMapRowData sectionRow : section.getSeatMapRows()) { rowIndex++; // on first row of each section, initialize the header // label map and the row label for the section if (rowIndex == 0) { // include room for two additional header elements for the exit // graphical indications, presetting them to an empty string this.headerMap[sectorIndex] = new String[sectionRow.getSeats().size() + 2]; this.headerMap[sectorIndex][0] = ""; this.headerMap[sectorIndex][sectionRow.getSeats().size() + 1] = ""; this.sectorRowLabel[sectorIndex] = new String[section.getSeatMapRows().size()]; } // set the global row label this.sectorRowLabel[sectorIndex][rowIndex] = sectionRow.getNumber().replaceAll("^[0]*",""); // include room for two additional elements for the exit graphical indications this.seatsMap[sectorIndex][rowIndex] = new String[sectionRow.getSeats().size() + 2]; // preset the first and last seats (used to display emergency exists) to blank this.seatsMap[sectorIndex][rowIndex][0] = NOT_EXISTS; this.seatsMap[sectorIndex][rowIndex][sectionRow.getSeats().size() + 1] = NOT_EXISTS; seatIndex = -1; int cont = 0; for (SeatData seat : sectionRow.getSeats()) { seatIndex++; // on first row of each section, initialize the elements of the header label map for the section if (rowIndex == 0) { this.headerMap[sectorIndex][seatIndex + 1] = seat.getNumber(); if (!seat.getNumber().equals("")) { cont++; } else { airplaneStructure.add(cont); cont = 0; } } // set seat type if (seat.getTypeSeat() == TypeSeatEnum.AISLE) { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = AISLE_SEAT; } else if (seat.getTypeSeat() == TypeSeatEnum.NOT_EXIST) { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = NOT_EXISTS; } else { if (seat.getAvailability() == AvailabilitySeatEnum.FREE) { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = AVAILABLE_SEAT; } else { this.seatsMap[sectorIndex][rowIndex][seatIndex + 1] = OCCUPIED_SEAT; } } // evaluate emergency exits if (seat.getTypeSeat() == TypeSeatEnum.WINDOW_EXIT_SEAT) { if (seatIndex == 0) { seatsMap[sectorIndex][rowIndex][0] = LEFT_EXIT; } else if (seatIndex == (sectionRow.getSeats().size() - 1)) { seatsMap[sectorIndex][rowIndex][sectionRow.getSeats().size() + 1] = RIGHT_EXIT; } } } } } sectorIndex = -1; sectorsIterator = (new LinkedList<SeatMapSectorData>(seatMapData.getSeatMapSectors())).listIterator(); while (sectorsIterator.hasNext()) { sectorIndex++; //first check if this section has a previous one if (sectorsIterator.hasPrevious()){ sectorNavigation[sectorIndex][0] = sectorLabel[sectorIndex - 1]; } else { sectorNavigation[sectorIndex][0] = ""; } sectorsIterator.next(); //check if this section has a next one if (sectorsIterator.hasNext()){ sectorNavigation[sectorIndex][1] = sectorLabel[sectorIndex + 1]; } else { sectorNavigation[sectorIndex][1] = ""; } } classSeatMap = "seatMap"; for (Integer structureCol : airplaneStructure) { classSeatMap += "_" + structureCol.toString(); } } public SeatMapData getSeatMapData() { return seatMapData; } public String[][] getHeaderMap() { return headerMap; } public String[] getSectorLabel() { return sectorLabel; } public String[][] getSectorNavigation() { return sectorNavigation; } public String[][] getSectorRowLabel() { return sectorRowLabel; } public String[][][] getSeatsMap() { return seatsMap; } public HashMap<Integer, String> getSeatToHeader() { return seatToHeader; } public String getClassSeatMap() { return classSeatMap; } }
7,475
0.684147
0.678528
230
31.5
28.331078
136
false
false
0
0
0
0
0
0
3.173913
false
false
2
9c47a871ab2b5eb00abbc8c24c83e40e037fbb37
29,944,511,995,160
1a2daf068134c5e04c6d180a8bf678a76d579b70
/com/ifmo/jjd/lesson12/exceptions/ChatException.java
3bcf3a3edafc25e5772e612ea7b7184a40bbc96e
[]
no_license
Shipiguzov/Java
https://github.com/Shipiguzov/Java
9b1b5810ba286cc8d4881d088bf9145cc2173046
aebca9a761c6e5eb4f23f22e708e41f15219661b
refs/heads/master
2023-01-30T05:05:15.886000
2020-12-18T08:20:08
2020-12-18T08:20:08
300,535,026
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package src.com.ifmo.jjd.lesson12.exceptions; // Если необходимо создать собственный класс исключения времени выполнения, то класс должен наследоваться от // RuntimeException // Если необходимо создать собственный класс исключения времени компиляции, то класс должен наследоваться от // Exception public class ChatException extends Exception { public ChatException(String message) { super(message); } public ChatException(String message, Throwable cause) { super(message, cause); } // можем переопределить методы родителя @Override public String getMessage() { return super.getMessage() + " Будьте внимательны"; } }
UTF-8
Java
911
java
ChatException.java
Java
[]
null
[]
package src.com.ifmo.jjd.lesson12.exceptions; // Если необходимо создать собственный класс исключения времени выполнения, то класс должен наследоваться от // RuntimeException // Если необходимо создать собственный класс исключения времени компиляции, то класс должен наследоваться от // Exception public class ChatException extends Exception { public ChatException(String message) { super(message); } public ChatException(String message, Throwable cause) { super(message, cause); } // можем переопределить методы родителя @Override public String getMessage() { return super.getMessage() + " Будьте внимательны"; } }
911
0.731167
0.728213
23
28.434782
31.300543
108
false
false
0
0
0
0
0
0
0.347826
false
false
2
5623f5ba023b10db3546fea178a5e29e5f11f7e0
8,091,718,396,817
606ca96aaf6196c3c2c54a5ae7a4f0524e736a1f
/Reverse.java
3fb7b2269d1e5fa559f6801c378666792e99c5d9
[]
no_license
bigdata-twitter/cascade
https://github.com/bigdata-twitter/cascade
85d6297c300249a8675ea9a92c749a0c0aa25fa1
77ee1c921032e03d2e214f691e9b27a57179cc05
refs/heads/master
2021-01-23T14:58:47.209000
2015-03-15T15:22:50
2015-03-15T15:22:50
28,139,794
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class Reverse { public static void main() throws IOException { BufferedReader br = new BufferedReader(new FileReader("leftover_roots")); HashSet<Long> roots = new HashSet<Long>(); String in; while ((in = br.readLine()) != null) roots.add(Long.parseLong(in)); br.close(); br = new BufferedReader(new FileReader("roots_all")); while ((in = br.readLine()) != null) if (!roots.contains(Long.parseLong(in))) System.out.println(in); br.close(); } }
UTF-8
Java
591
java
Reverse.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class Reverse { public static void main() throws IOException { BufferedReader br = new BufferedReader(new FileReader("leftover_roots")); HashSet<Long> roots = new HashSet<Long>(); String in; while ((in = br.readLine()) != null) roots.add(Long.parseLong(in)); br.close(); br = new BufferedReader(new FileReader("roots_all")); while ((in = br.readLine()) != null) if (!roots.contains(Long.parseLong(in))) System.out.println(in); br.close(); } }
591
0.695431
0.695431
20
28.549999
18.639944
75
false
false
0
0
0
0
0
0
2
false
false
2
da9c1aa5fbb94bf65650db6b0f639842d8bc5933
13,357,348,303,957
758892eed2a10b0edd5d2dcc7170301a58927187
/ai/botbuilding/bot_clean.java
891344c8193014ea146ed9ebb41d97f132ca8b22
[]
no_license
gardncl/hackerrank
https://github.com/gardncl/hackerrank
db0a77cef1dbca56c2b81bbfa406adae1cf7231c
c7c8a231a4b8b4bc0d7ccc77bf57e5d0ef651bd0
refs/heads/master
2016-08-11T04:08:33.464000
2015-12-20T05:30:08
2015-12-20T05:30:08
48,135,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package artificial_intelligence; /* Problem Statement The goal of Artificial Intelligence is to create a rational agent (Artificial Intelligence 1.1.4). An agent gets input from the environment through sensors and acts on the environment with actuators. In this challenge, you will program a simple bot to perform the correct actions based on environmental input. Meet the bot MarkZoid. It's a cleaning bot whose sensor is a head mounted camera and whose actuators are the wheels beneath it. It's used to clean the floor. The bot here is positioned at the top left corner of a 5*5 grid. Your task is to move the bot to clean all the dirty cells. Input Format The first line contains two space separated integers which indicate the current position of the bot. The board is indexed using Matrix Convention 5 lines follow representing the grid. Each cell in the grid is represented by any of the following 3 characters: 'b' (ascii value 98) indicates the bot's current position, 'd' (ascii value 100) indicates a dirty cell and '-' (ascii value 45) indicates a clean cell in the grid. Note If the bot is on a dirty cell, the cell will still have 'd' on it. Output Format The output is the action that is taken by the bot in the current step, and it can be either one of the movements in 4 directions or cleaning up the cell in which it is currently located. The valid output strings are LEFT, RIGHT, UP and DOWN or CLEAN. If the bot ever reaches a dirty cell, output CLEAN to clean the dirty cell. Repeat this process until all the cells on the grid are cleaned. Sample Input #00 0 0 b---d -d--d --dd- --d-- ----d Sample Output #00 RIGHT Resultant state -b--d -d--d --dd- --d-- ----d Sample Input #01 0 1 -b--d -d--d --dd- --d-- ----d Sample Output #01 DOWN Resultant state ----d -d--d --dd- --d-- ----d Task Complete the function next_move that takes in 3 parameters posr, posc being the co-ordinates of the bot's current position and board which indicates the board state to print the bot's next move. The codechecker will keep calling the function next_move till the game is over or you make an invalid move. */ import java.awt.Point; import java.util.Scanner; public class bot_clean { public static void move_next( int r, int c, char[][] board){ Point b = new Point(c,r); Point closest = new Point(100,100); for(int i = 0; i < board.length; i++){ for(int j = 0; j < board.length; j++) { if(board[j][i]=='d') { if(b.distance(closest)>b.distance(new Point(j,i))) { closest = new Point(j,i); } } } } if (b.equals(closest)){ System.out.println("CLEAN"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX()+1,(int)b.getY()))) { System.out.println("RIGHT"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX()-1,(int)b.getY()))) { System.out.println("LEFT"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX(),(int)b.getY()+1))) { System.out.println("DOWN"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX(),(int)b.getY()-1))) { System.out.println("UP"); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=5; char[][] board =new char[n][n]; String temp = ""; int r = in.nextInt(); int c = in.nextInt(); for(int i = 0; i < n; i++){ temp = in.next(); for(int j = 0; j < n; j++) { board[j][i]=temp.charAt(j); } } in.close(); move_next(r,c,board); } }
UTF-8
Java
3,532
java
bot_clean.java
Java
[ { "context": "ctions based on environmental input.\n\nMeet the bot MarkZoid. It's a cleaning bot whose sensor is a head mount", "end": 393, "score": 0.9646689295768738, "start": 385, "tag": "USERNAME", "value": "MarkZoid" } ]
null
[]
package artificial_intelligence; /* Problem Statement The goal of Artificial Intelligence is to create a rational agent (Artificial Intelligence 1.1.4). An agent gets input from the environment through sensors and acts on the environment with actuators. In this challenge, you will program a simple bot to perform the correct actions based on environmental input. Meet the bot MarkZoid. It's a cleaning bot whose sensor is a head mounted camera and whose actuators are the wheels beneath it. It's used to clean the floor. The bot here is positioned at the top left corner of a 5*5 grid. Your task is to move the bot to clean all the dirty cells. Input Format The first line contains two space separated integers which indicate the current position of the bot. The board is indexed using Matrix Convention 5 lines follow representing the grid. Each cell in the grid is represented by any of the following 3 characters: 'b' (ascii value 98) indicates the bot's current position, 'd' (ascii value 100) indicates a dirty cell and '-' (ascii value 45) indicates a clean cell in the grid. Note If the bot is on a dirty cell, the cell will still have 'd' on it. Output Format The output is the action that is taken by the bot in the current step, and it can be either one of the movements in 4 directions or cleaning up the cell in which it is currently located. The valid output strings are LEFT, RIGHT, UP and DOWN or CLEAN. If the bot ever reaches a dirty cell, output CLEAN to clean the dirty cell. Repeat this process until all the cells on the grid are cleaned. Sample Input #00 0 0 b---d -d--d --dd- --d-- ----d Sample Output #00 RIGHT Resultant state -b--d -d--d --dd- --d-- ----d Sample Input #01 0 1 -b--d -d--d --dd- --d-- ----d Sample Output #01 DOWN Resultant state ----d -d--d --dd- --d-- ----d Task Complete the function next_move that takes in 3 parameters posr, posc being the co-ordinates of the bot's current position and board which indicates the board state to print the bot's next move. The codechecker will keep calling the function next_move till the game is over or you make an invalid move. */ import java.awt.Point; import java.util.Scanner; public class bot_clean { public static void move_next( int r, int c, char[][] board){ Point b = new Point(c,r); Point closest = new Point(100,100); for(int i = 0; i < board.length; i++){ for(int j = 0; j < board.length; j++) { if(board[j][i]=='d') { if(b.distance(closest)>b.distance(new Point(j,i))) { closest = new Point(j,i); } } } } if (b.equals(closest)){ System.out.println("CLEAN"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX()+1,(int)b.getY()))) { System.out.println("RIGHT"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX()-1,(int)b.getY()))) { System.out.println("LEFT"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX(),(int)b.getY()+1))) { System.out.println("DOWN"); } else if (closest.distance(b)> closest.distance(new Point((int)b.getX(),(int)b.getY()-1))) { System.out.println("UP"); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=5; char[][] board =new char[n][n]; String temp = ""; int r = in.nextInt(); int c = in.nextInt(); for(int i = 0; i < n; i++){ temp = in.next(); for(int j = 0; j < n; j++) { board[j][i]=temp.charAt(j); } } in.close(); move_next(r,c,board); } }
3,532
0.680634
0.66846
131
25.961832
32.779488
194
false
false
0
0
0
0
0
0
1.267176
false
false
2
c29f7afc2bfc49fcb993a18d5ddb45f59c327f5b
5,360,119,198,407
6ad215d36c1a1e2e14ec5dc2023cf43227134ab9
/src/day34_LocalDateAndTime/Birthday.java
e82874c02ee42caf2c543bd73a483b0f1d2f84d5
[]
no_license
KseniiaMazanko/JavaProgramming_B23
https://github.com/KseniiaMazanko/JavaProgramming_B23
839f3504b808bb0510c70f1ac041c0650d566b1d
ef3862ba8a40bae90545d1cfe3564ebc822ea4e5
refs/heads/master
2023-08-16T04:31:36.981000
2021-09-30T22:59:19
2021-09-30T22:59:19
387,605,760
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day34_LocalDateAndTime; import java.time.LocalDate; public class Birthday { public static void main(String[] args) { birthday(1994, 7, 22); } public static void birthday (int year, int month, int day){ LocalDate DOB = LocalDate.of(year, month, day); LocalDate today = LocalDate.now(); if(DOB.getMonthValue() == today.getMonthValue() && DOB.getDayOfMonth() == today.getDayOfMonth() ){ System.out.println("Happy birthday, you are " + (today.getYear() - DOB.getYear()) + " today"); } else{ System.out.println("Today is not your birthday"); } } }
UTF-8
Java
696
java
Birthday.java
Java
[]
null
[]
package day34_LocalDateAndTime; import java.time.LocalDate; public class Birthday { public static void main(String[] args) { birthday(1994, 7, 22); } public static void birthday (int year, int month, int day){ LocalDate DOB = LocalDate.of(year, month, day); LocalDate today = LocalDate.now(); if(DOB.getMonthValue() == today.getMonthValue() && DOB.getDayOfMonth() == today.getDayOfMonth() ){ System.out.println("Happy birthday, you are " + (today.getYear() - DOB.getYear()) + " today"); } else{ System.out.println("Today is not your birthday"); } } }
696
0.567529
0.554598
31
21.451612
24.716246
66
false
false
0
0
0
0
0
0
0.451613
false
false
2
71244a5d18b55e2525a1202bdceaf9a61f73d3fb
11,991,548,701,898
d57dcf29e17043eef7e48e896a244f1a7fa3423c
/src/manager/MenuManager.java
894cb9254c1195d68bc3c011c42bd5677da23c34
[]
no_license
junho0901/TimetableManagementSystem
https://github.com/junho0901/TimetableManagementSystem
99f23a427b4f307d65363111475c42dbf02008ad
2b70c460301a69a752abdc18ae25890a83b5d41b
refs/heads/master
2021-04-17T13:41:11.624000
2020-07-02T11:59:46
2020-07-02T11:59:46
249,449,417
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package manager; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.InputMismatchException; import java.util.Scanner; import gui.WindowFrame; import log.EventLogger; public class MenuManager { static EventLogger logger = new EventLogger("logging.txt"); public static void main(String[]args) { Scanner input = new Scanner(System.in); TimetableManager timetableManager = getObject("timetablemanager.ser"); if(timetableManager ==null) { timetableManager = new TimetableManager(input); } else { timetableManager.setScanner(input); } WindowFrame frame = new WindowFrame(timetableManager); selectMenu(input, timetableManager); putObject(timetableManager, "timetablemanager.ser"); } public static void selectMenu(Scanner input, TimetableManager timetableManager) { int num = -1; while(num != 6) { try { showMenu(); num = input.nextInt(); switch(num) { case 1: timetableManager.addTimetable(); logger.log("add a timetable"); break; case 2: timetableManager.deleteTimetable(); logger.log("delete a timetable"); break; case 3: timetableManager.editTimetable(); logger.log("edit a timetable"); break; case 4: timetableManager.searchTimetables(); logger.log("search a timetable"); break; case 5: timetableManager.viewTimetables(); logger.log("view a list of timetable"); default: continue; } }catch(InputMismatchException e) { System.out.println("Please Select the number between 1 -6"); if(input.hasNext()) { input.next(); } num = -1; } } } public static void showMenu() { System.out.println(" Timetable Management System Menu ***"); System.out.println(" 1. Add Timetable "); System.out.println(" 2. Delete Timetable "); System.out.println(" 3. Edit Timetable "); System.out.println(" 4. Search Timetables "); System.out.println(" 5. View Timetables "); System.out.println(" 6. Exit "); System.out.println(" Select one number between 1 - 6 "); } public static TimetableManager getObject(String filename) { TimetableManager timetableManager = null; try { FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); timetableManager = (TimetableManager)in.readObject(); in.close(); file.close(); } catch (FileNotFoundException e) { return timetableManager; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return timetableManager; } public static void putObject(TimetableManager timetableManager ,String filename) { try { FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(timetableManager); out.close(); file.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
3,430
java
MenuManager.java
Java
[]
null
[]
package manager; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.InputMismatchException; import java.util.Scanner; import gui.WindowFrame; import log.EventLogger; public class MenuManager { static EventLogger logger = new EventLogger("logging.txt"); public static void main(String[]args) { Scanner input = new Scanner(System.in); TimetableManager timetableManager = getObject("timetablemanager.ser"); if(timetableManager ==null) { timetableManager = new TimetableManager(input); } else { timetableManager.setScanner(input); } WindowFrame frame = new WindowFrame(timetableManager); selectMenu(input, timetableManager); putObject(timetableManager, "timetablemanager.ser"); } public static void selectMenu(Scanner input, TimetableManager timetableManager) { int num = -1; while(num != 6) { try { showMenu(); num = input.nextInt(); switch(num) { case 1: timetableManager.addTimetable(); logger.log("add a timetable"); break; case 2: timetableManager.deleteTimetable(); logger.log("delete a timetable"); break; case 3: timetableManager.editTimetable(); logger.log("edit a timetable"); break; case 4: timetableManager.searchTimetables(); logger.log("search a timetable"); break; case 5: timetableManager.viewTimetables(); logger.log("view a list of timetable"); default: continue; } }catch(InputMismatchException e) { System.out.println("Please Select the number between 1 -6"); if(input.hasNext()) { input.next(); } num = -1; } } } public static void showMenu() { System.out.println(" Timetable Management System Menu ***"); System.out.println(" 1. Add Timetable "); System.out.println(" 2. Delete Timetable "); System.out.println(" 3. Edit Timetable "); System.out.println(" 4. Search Timetables "); System.out.println(" 5. View Timetables "); System.out.println(" 6. Exit "); System.out.println(" Select one number between 1 - 6 "); } public static TimetableManager getObject(String filename) { TimetableManager timetableManager = null; try { FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); timetableManager = (TimetableManager)in.readObject(); in.close(); file.close(); } catch (FileNotFoundException e) { return timetableManager; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return timetableManager; } public static void putObject(TimetableManager timetableManager ,String filename) { try { FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(timetableManager); out.close(); file.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3,430
0.674344
0.669096
121
26.363636
19.854845
83
false
false
0
0
0
0
0
0
3.016529
false
false
2
b7e6c31d148186aa46cd8bc3936d55e613930dcf
20,804,821,594,573
b0cb567004ed8f441f4d78095848d61fef9bf7a4
/src/main/java/com/wtsd/myspring/mapper/HkAdverMapper.java
c6cb43e4f6d90997382865bc3a3dd56f832b0382
[]
no_license
trntaken/spring-gradle-mybatis
https://github.com/trntaken/spring-gradle-mybatis
3717492d9a6536adc1c4e55a6a910ebdacd7e54d
a1397eb539d01f3019b4fecbd7d2d2228f975206
refs/heads/master
2017-12-16T14:56:06.093000
2016-12-30T09:15:46
2016-12-30T09:15:46
77,665,437
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wtsd.myspring.mapper; import com.wtsd.myspring.entity.HkAdver; import com.wtsd.myspring.entity.HkAdverExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface HkAdverMapper { int countByExample(HkAdverExample example); int deleteByExample(HkAdverExample example); int deleteByPrimaryKey(Integer id); int insert(HkAdver record); int insertSelective(HkAdver record); List<HkAdver> selectByExample(HkAdverExample example); HkAdver selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") HkAdver record, @Param("example") HkAdverExample example); int updateByExample(@Param("record") HkAdver record, @Param("example") HkAdverExample example); int updateByPrimaryKeySelective(HkAdver record); int updateByPrimaryKey(HkAdver record); }
UTF-8
Java
855
java
HkAdverMapper.java
Java
[]
null
[]
package com.wtsd.myspring.mapper; import com.wtsd.myspring.entity.HkAdver; import com.wtsd.myspring.entity.HkAdverExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface HkAdverMapper { int countByExample(HkAdverExample example); int deleteByExample(HkAdverExample example); int deleteByPrimaryKey(Integer id); int insert(HkAdver record); int insertSelective(HkAdver record); List<HkAdver> selectByExample(HkAdverExample example); HkAdver selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") HkAdver record, @Param("example") HkAdverExample example); int updateByExample(@Param("record") HkAdver record, @Param("example") HkAdverExample example); int updateByPrimaryKeySelective(HkAdver record); int updateByPrimaryKey(HkAdver record); }
855
0.775439
0.775439
30
27.533333
29.062843
108
false
false
0
0
0
0
0
0
0.6
false
false
2
dacc42cd6f2f46d12bbb646f1a3fe6a3725a3af1
10,316,511,458,555
a6800a5abf0841cb806ff21bb4f482fefbcbe873
/src/main/java/org/sid/web/ControllerStudent.java
e7e8a4f651f510d36ffc30bf60eb92327cfb284a
[]
no_license
guahmed/E-learning
https://github.com/guahmed/E-learning
0ccf6abfce725bbdaa54666e2e5609a9d6736a11
c9be8554c6e315f071c32111d594bbd7bc3636f5
refs/heads/master
2022-11-28T09:45:36.534000
2020-07-25T12:07:44
2020-07-25T12:07:44
256,256,216
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.sid.web; import java.util.List; import javax.management.RuntimeErrorException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.sql.SQLException; import org.hibernate.engine.jdbc.BlobProxy; import org.sid.dao.CourseDao; import org.sid.dao.InstitutDao; import org.sid.dao.SessionDao; import org.sid.dao.StudentDao; import org.sid.entites.Agent; import org.sid.entites.Course; import org.sid.entites.Institut; import org.sid.entites.Place; import org.sid.entites.Session; import org.sid.entites.Student; import org.sid.exception.ChangePasswordException; import org.sid.service.ChangePassword; import org.sid.service.GetLoggedUser; import org.sid.service.ModifyProfil; import org.sid.service.ObjectServiceChangePassword; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.http.HttpStatus; @RestController @CrossOrigin("*") @RequestMapping("/student" ) public class ControllerStudent { @Autowired private ControllerStudent controller; @Autowired private StudentDao studentDao; @Autowired private CourseDao courseDao; @Autowired private InstitutDao institutDao; @Autowired private SessionDao sessionDao; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private ChangePassword changePassword; @Autowired private GetLoggedUser getLoggedUser; @Autowired private ModifyProfil modifyProfil; @PostMapping(path = "/subscribe/secondstep") public String testsub(Model model, Student std) { studentDao.save(std); return "redirect:/index"; } @GetMapping(path = "/template") public String temp() { return "template"; } @GetMapping(path="/photoFormation/{id}") public ResponseEntity<byte[]> getPhoto(@PathVariable("id")Long id) throws SQLException { Session session=sessionDao.findById(id).get(); //Files.readAllBytes( form.getPhoto()); return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(session.getImage().getBytes(1, (int) session.getImage().length())); } //@GetMapping(path="/anvailible") @GetMapping(path="/getStudentinfo/{id}") public Student getStudent(@PathVariable("id") Long id) { return studentDao.findById(id).get(); } @DeleteMapping("/deleteStudent/{id}") public void deleteStudent(@PathVariable("id") Long id) { studentDao.deleteById(id); } @PostMapping("/uploadPhoto/{name}") public void uploadPhoto(@PathVariable("name") String name, @RequestParam("file") MultipartFile file ) throws IOException { Student student =studentDao.findByName(name); System.out.println(file.getBytes()); student.setPhoto(BlobProxy.generateProxy(file.getBytes())); studentDao.save(student); //return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(student.getPhoto()); } @GetMapping("/getStudent/{name}") public Student addStudent(@PathVariable("name") String name ) { return studentDao.findByName(name); } @GetMapping("/getPhotoUser/{name}") public ResponseEntity<byte[]> getPhotoUser(@PathVariable("name") String name) throws SQLException{ Student student =studentDao.findByName(name); return ResponseEntity.ok(). contentType(MediaType.IMAGE_PNG). body(student.getPhoto().getBytes(1, (int) student.getPhoto().length())); } @PutMapping("updateStudent/{name}") public Student updateStudent(@PathVariable("name") String name, @RequestBody Student studentAfter) { Student studentBefore=studentDao.findByName(name); System.out.println("email"+studentBefore.getEmail()); studentBefore.setName(studentAfter.getName()); studentBefore.setLastName(studentAfter.getLastName()); studentBefore.setAge(studentAfter.getAge()); studentBefore.setIdCard(studentAfter.getIdCard()); //studentBefore.setPassword(bCryptPasswordEncoder.encode(studentAfter.getPassword())); studentBefore.setEmail(studentAfter.getEmail()); studentBefore.setRole(studentAfter.getRole()); studentBefore.setAdress(studentAfter.getAdress()); studentBefore.setExperience(studentAfter.getExperience()); //studentBefore.setId(id); return studentDao.save(studentBefore); /* * std.setAge(age); std.setEmail(email); std.setIdCard(idCard); * std.setLastName(lastName); std.setName(name); std.setPhoto(photo); */ } @PostMapping("/SubscribeSession") public void Subscribe(@RequestBody StudentAndSession objet ) { Student student=studentDao.findByName(objet.StudentName); /* * Session session =sessionDao.findByName(objet.SessionName); * * if (session.getInscribedStudent().contains(student)) throw new * RuntimeException("Vous etes deja inscri"); else { * * session.getInscribedStudent().add(student); * * } * * //session.getInscribedStudent().clean(); * session.getInscribedStudent().forEach(s->System.out.print(s.getAdresse())); */ } @GetMapping("/testinstitutPlace") public ResponseEntity<Course> diplayPlace(){ Course course = courseDao.findById((long) 1).get(); return new ResponseEntity<Course>(course ,HttpStatus.OK); } @GetMapping("/aaa") public String getuser(){ return getLoggedUser.getuser(); } @PostMapping("/changePassword" ) public void changePassword( @RequestBody ObjectServiceChangePassword objectServiceChangePassword ) { System.out.print(objectServiceChangePassword.toString()); changePassword.CheckAndSavePassword( objectServiceChangePassword.getOldPassword() , objectServiceChangePassword.getNewPassword() , objectServiceChangePassword.getConfirmPassWord()); } @PostMapping("/editProfil" ) public void changePassword( @RequestBody Student student ) { modifyProfil.ModifyProfilStudent(student); } }
UTF-8
Java
6,852
java
ControllerStudent.java
Java
[]
null
[]
package org.sid.web; import java.util.List; import javax.management.RuntimeErrorException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.sql.SQLException; import org.hibernate.engine.jdbc.BlobProxy; import org.sid.dao.CourseDao; import org.sid.dao.InstitutDao; import org.sid.dao.SessionDao; import org.sid.dao.StudentDao; import org.sid.entites.Agent; import org.sid.entites.Course; import org.sid.entites.Institut; import org.sid.entites.Place; import org.sid.entites.Session; import org.sid.entites.Student; import org.sid.exception.ChangePasswordException; import org.sid.service.ChangePassword; import org.sid.service.GetLoggedUser; import org.sid.service.ModifyProfil; import org.sid.service.ObjectServiceChangePassword; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.http.HttpStatus; @RestController @CrossOrigin("*") @RequestMapping("/student" ) public class ControllerStudent { @Autowired private ControllerStudent controller; @Autowired private StudentDao studentDao; @Autowired private CourseDao courseDao; @Autowired private InstitutDao institutDao; @Autowired private SessionDao sessionDao; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private ChangePassword changePassword; @Autowired private GetLoggedUser getLoggedUser; @Autowired private ModifyProfil modifyProfil; @PostMapping(path = "/subscribe/secondstep") public String testsub(Model model, Student std) { studentDao.save(std); return "redirect:/index"; } @GetMapping(path = "/template") public String temp() { return "template"; } @GetMapping(path="/photoFormation/{id}") public ResponseEntity<byte[]> getPhoto(@PathVariable("id")Long id) throws SQLException { Session session=sessionDao.findById(id).get(); //Files.readAllBytes( form.getPhoto()); return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(session.getImage().getBytes(1, (int) session.getImage().length())); } //@GetMapping(path="/anvailible") @GetMapping(path="/getStudentinfo/{id}") public Student getStudent(@PathVariable("id") Long id) { return studentDao.findById(id).get(); } @DeleteMapping("/deleteStudent/{id}") public void deleteStudent(@PathVariable("id") Long id) { studentDao.deleteById(id); } @PostMapping("/uploadPhoto/{name}") public void uploadPhoto(@PathVariable("name") String name, @RequestParam("file") MultipartFile file ) throws IOException { Student student =studentDao.findByName(name); System.out.println(file.getBytes()); student.setPhoto(BlobProxy.generateProxy(file.getBytes())); studentDao.save(student); //return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(student.getPhoto()); } @GetMapping("/getStudent/{name}") public Student addStudent(@PathVariable("name") String name ) { return studentDao.findByName(name); } @GetMapping("/getPhotoUser/{name}") public ResponseEntity<byte[]> getPhotoUser(@PathVariable("name") String name) throws SQLException{ Student student =studentDao.findByName(name); return ResponseEntity.ok(). contentType(MediaType.IMAGE_PNG). body(student.getPhoto().getBytes(1, (int) student.getPhoto().length())); } @PutMapping("updateStudent/{name}") public Student updateStudent(@PathVariable("name") String name, @RequestBody Student studentAfter) { Student studentBefore=studentDao.findByName(name); System.out.println("email"+studentBefore.getEmail()); studentBefore.setName(studentAfter.getName()); studentBefore.setLastName(studentAfter.getLastName()); studentBefore.setAge(studentAfter.getAge()); studentBefore.setIdCard(studentAfter.getIdCard()); //studentBefore.setPassword(bCryptPasswordEncoder.encode(studentAfter.getPassword())); studentBefore.setEmail(studentAfter.getEmail()); studentBefore.setRole(studentAfter.getRole()); studentBefore.setAdress(studentAfter.getAdress()); studentBefore.setExperience(studentAfter.getExperience()); //studentBefore.setId(id); return studentDao.save(studentBefore); /* * std.setAge(age); std.setEmail(email); std.setIdCard(idCard); * std.setLastName(lastName); std.setName(name); std.setPhoto(photo); */ } @PostMapping("/SubscribeSession") public void Subscribe(@RequestBody StudentAndSession objet ) { Student student=studentDao.findByName(objet.StudentName); /* * Session session =sessionDao.findByName(objet.SessionName); * * if (session.getInscribedStudent().contains(student)) throw new * RuntimeException("Vous etes deja inscri"); else { * * session.getInscribedStudent().add(student); * * } * * //session.getInscribedStudent().clean(); * session.getInscribedStudent().forEach(s->System.out.print(s.getAdresse())); */ } @GetMapping("/testinstitutPlace") public ResponseEntity<Course> diplayPlace(){ Course course = courseDao.findById((long) 1).get(); return new ResponseEntity<Course>(course ,HttpStatus.OK); } @GetMapping("/aaa") public String getuser(){ return getLoggedUser.getuser(); } @PostMapping("/changePassword" ) public void changePassword( @RequestBody ObjectServiceChangePassword objectServiceChangePassword ) { System.out.print(objectServiceChangePassword.toString()); changePassword.CheckAndSavePassword( objectServiceChangePassword.getOldPassword() , objectServiceChangePassword.getNewPassword() , objectServiceChangePassword.getConfirmPassWord()); } @PostMapping("/editProfil" ) public void changePassword( @RequestBody Student student ) { modifyProfil.ModifyProfilStudent(student); } }
6,852
0.763281
0.762843
250
26.408001
25.461687
134
false
false
0
0
0
0
0
0
1.58
false
false
2
3849f87e27b40caa83541c17a3b7088810131d58
36,850,819,434,265
a2bf12456639dddfe62e051826c0679daf1b7b1c
/Banco/src/banco/Banco.java
a9003aa75532512873a4522fe216a10e0487e5b8
[]
no_license
Eweline/projetos-java
https://github.com/Eweline/projetos-java
263ae84739232526981fc710e8dc4f39f3bbffe9
e51529804ac3ed8163083f8deb9098e5e7787f89
refs/heads/master
2021-01-25T07:19:15.333000
2013-04-02T19:52:01
2013-04-02T19:52:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package banco; public class Banco { public static void main(String[] args) { //Criando funcionários Funcionario f1 = new Funcionario(); f1.nome = "Fiodor"; f1.salario = 100.0; f1.bonificar(50); Funcionario f2 = new Funcionario(); f2.nome = "Luana"; f2.salario = 200.0; f2.bonificar(100); Funcionario f3 = new Funcionario(); f3.nome = "Antony"; f3.salario = 300.0; f3.bonificar(100); // criando os objetos data Data data = new Data(); Data data2 = new Data(); //atribuindo data à um funcionário. f1.dataEntrada = data; f1.dataEntrada.dia = 18; f1.dataEntrada.mes = 03; f1.dataEntrada.ano = 2013; f3.dataEntrada = data2; f3.dataEntrada.dia = 23; f3.dataEntrada.mes = 02; f3.dataEntrada.ano = 2012; System.out.println("salario atual:" + f1.salario + ", do empregado: "+f1.nome); System.out.println("salario atual:" + f2.salario + ", do empregado: "+f2.nome); System.out.println("salario atual:" + f3.salario + ", do empregado: "+f3.nome); System.out.println(""); f1.demitir(); f1.verificarDemicao(); f2.verificarDemicao(); System.out.println(""); f1.mostrar(); System.out.println(""); f3.mostrar(); } }
UTF-8
Java
1,476
java
Banco.java
Java
[ { "context": "onario f1 = new Funcionario();\n f1.nome = \"Fiodor\"; \n f1.salario = 100.0;\n f1.bonific", "end": 191, "score": 0.9997228980064392, "start": 185, "tag": "NAME", "value": "Fiodor" }, { "context": "onario f2 = new Funcionario();\n f2.nome = \...
null
[]
package banco; public class Banco { public static void main(String[] args) { //Criando funcionários Funcionario f1 = new Funcionario(); f1.nome = "Fiodor"; f1.salario = 100.0; f1.bonificar(50); Funcionario f2 = new Funcionario(); f2.nome = "Luana"; f2.salario = 200.0; f2.bonificar(100); Funcionario f3 = new Funcionario(); f3.nome = "Antony"; f3.salario = 300.0; f3.bonificar(100); // criando os objetos data Data data = new Data(); Data data2 = new Data(); //atribuindo data à um funcionário. f1.dataEntrada = data; f1.dataEntrada.dia = 18; f1.dataEntrada.mes = 03; f1.dataEntrada.ano = 2013; f3.dataEntrada = data2; f3.dataEntrada.dia = 23; f3.dataEntrada.mes = 02; f3.dataEntrada.ano = 2012; System.out.println("salario atual:" + f1.salario + ", do empregado: "+f1.nome); System.out.println("salario atual:" + f2.salario + ", do empregado: "+f2.nome); System.out.println("salario atual:" + f3.salario + ", do empregado: "+f3.nome); System.out.println(""); f1.demitir(); f1.verificarDemicao(); f2.verificarDemicao(); System.out.println(""); f1.mostrar(); System.out.println(""); f3.mostrar(); } }
1,476
0.5241
0.477257
53
26.773584
19.411766
87
false
false
0
0
0
0
0
0
0.698113
false
false
7
d6220471000257ccaa6ae060569c26ecf2fec031
2,010,044,717,237
5593b25213aa13e7928408c41cff7e1ea984ab00
/app/src/main/java/com/hapramp/utils/StringUtils.java
af35e48a8d62086a2cdd083fd30490eb3031ee8b
[ "MIT" ]
permissive
hapramp/Hapramp-Android
https://github.com/hapramp/Hapramp-Android
e48fa86cc41ddda3b07282b4b6be3e6f644062d4
7c254b2b3b30560ea171d6942490b039e9c85a1e
refs/heads/master
2018-10-16T22:29:53.732000
2018-10-16T16:11:09
2018-10-16T16:11:09
132,155,805
6
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hapramp.utils; public class StringUtils { // replace with single escape character public static String stringify(String s) { s = s.replace("\n","\\n"); s = s.replace("\"", "\\\""); s = s.replace("\\\\", "\\\\\\"); return s; } }
UTF-8
Java
263
java
StringUtils.java
Java
[]
null
[]
package com.hapramp.utils; public class StringUtils { // replace with single escape character public static String stringify(String s) { s = s.replace("\n","\\n"); s = s.replace("\"", "\\\""); s = s.replace("\\\\", "\\\\\\"); return s; } }
263
0.555133
0.555133
11
22.90909
15.359063
44
false
false
0
0
0
0
0
0
0.727273
false
false
7
258992397f21a54e3c4ef8da962df36f8038baf7
10,316,511,464,680
6bba8ac5bd0d345a1c4b5eb90df052434438aa76
/projectno2/src/CollectionsAssignment/Program3.java
2d9cd2e6b0b2eece238f0c10548fb470d16e63be
[]
no_license
charan-3876/Java-Programs
https://github.com/charan-3876/Java-Programs
6d474a921bc49cd976d8d6082cbc4344b69803f3
ec1f33a0c0ed59ad387f3ad78d7a442e97ec3a32
refs/heads/master
2023-03-06T23:18:11.051000
2021-02-17T11:23:47
2021-02-17T11:23:47
339,609,395
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package CollectionsAssignment; import java.util.*; public class Program3 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); Vector<Integer> v1=new Vector<Integer>(); int cos=0; do { System.out.println("Enter integer element: "); int ele=scan.nextInt(); v1.add(ele); System.out.println("Press 1 to continue 0 to stop: "); cos=scan.nextInt(); }while(cos==1); System.out.println("The vector elements are: "); System.out.println(v1); System.out.println("The sorted elements are: "); Collections.sort(v1); System.out.println(v1); } }
UTF-8
Java
587
java
Program3.java
Java
[]
null
[]
package CollectionsAssignment; import java.util.*; public class Program3 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); Vector<Integer> v1=new Vector<Integer>(); int cos=0; do { System.out.println("Enter integer element: "); int ele=scan.nextInt(); v1.add(ele); System.out.println("Press 1 to continue 0 to stop: "); cos=scan.nextInt(); }while(cos==1); System.out.println("The vector elements are: "); System.out.println(v1); System.out.println("The sorted elements are: "); Collections.sort(v1); System.out.println(v1); } }
587
0.693356
0.67632
24
23.458334
16.958231
56
false
false
0
0
0
0
0
0
1.333333
false
false
7
a2a05ffbc33be292920e258692dd03c380d27354
10,316,511,466,936
3da0b8f4bf7c2857c431ecbb94ceaaa7248604f8
/main/java/com/eBay/NativeApp/PageComponents/SharePanelComponent.java
caeab1727132544158e5236d5450910d7a0018fd
[]
no_license
asartabe/newRepo
https://github.com/asartabe/newRepo
1a76bebba20a533bf8aea65ec2fde6487bc90d0f
e68423b8e50c569e1e0518deb82aad73a18828b8
refs/heads/master
2020-12-07T14:38:18.945000
2020-01-09T18:43:22
2020-01-09T18:43:22
232,739,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eBay.NativeApp.PageComponents; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.eBay.NativeApp.Enums.ShareOptionsMenu; import com.eBay.NativeApp.Locators.SharePanelComponentLocators; public class SharePanelComponent extends SharePanelComponentLocators{ public SharePanelComponent(WebDriver driver) { super(driver); // TODO Auto-generated constructor stub } public void shareViaOption(ShareOptionsMenu option){ actions.touchScreen().withinParent(SHARE_PANEL_ITEMS_CONTAINER).scrollTo(By.xpath("//android.widget.TextView[@text='"+ShareOptionsMenu.MESSAGING.getValue()+"']")); List<String> allOptions = actions.element() .withinParent(SHARE_PANEL_ITEMS_CONTAINER) .withinParent(SHARE_PANEL_ITEMS).get() .textFromAllElementsWithSameLocatorAsList(By.xpath("//android.widget.TextView"), "Share Menu Options could not be found!"); if(allOptions.contains(option.getValue())){ actions.touchScreen().withinParent(SHARE_PANEL_ITEMS_CONTAINER) .tap((By.xpath("//android.widget.TextView[@text='"+option.getValue()+"']"))); switch (option) { case FACEBOOK: clickPostForFacebook(); break; case TWITTER: clickTweetForTwitter(); break; case GMAIL: clickSendViaGmail(); break; default: break; } } else breezeReport.logRedStep("["+option.getValue()+"] Menu option is not available!"); } private void clickTweetForTwitter(){ if(actions.element().present().byPolling(TWITTER_TWEET)) actions.element().click().by(TWITTER_TWEET); else breezeReport.logRedStep("Seems Twitter Share window did not open...!!!"); } private void clickPostForFacebook(){ if(actions.element().present().byPolling(FACEBOOK_POST_BTN)) actions.element().click().by(FACEBOOK_POST_BTN); else breezeReport.logRedStep("Seems Facebook Share window did not open...!!!"); } private void clickSendViaGmail(){ if(actions.element().present().byPolling(GMAIL_RCPNT_TO)){ actions.element().textBox().sendKeys(GMAIL_RCPNT_TO, "ebaymobreg@gmail.com"); actions.element().click().by(GMAIL_SEND_BTN); } else breezeReport.logRedStep("Seems Gmail Share window did not open...!!!"); } }
UTF-8
Java
2,208
java
SharePanelComponent.java
Java
[ { "context": "h(\"//android.widget.TextView[@text='\"+ShareOptionsMenu.MESSAGING.getValue()+\"']\"));\n\t\t\n\t\tList<String> allOptions = actions.", "end": 648, "score": 0.6331009864807129, "start": 625, "tag": "EMAIL", "value": "Menu.MESSAGING.getValue" }, { "context": "ons.element...
null
[]
package com.eBay.NativeApp.PageComponents; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.eBay.NativeApp.Enums.ShareOptionsMenu; import com.eBay.NativeApp.Locators.SharePanelComponentLocators; public class SharePanelComponent extends SharePanelComponentLocators{ public SharePanelComponent(WebDriver driver) { super(driver); // TODO Auto-generated constructor stub } public void shareViaOption(ShareOptionsMenu option){ actions.touchScreen().withinParent(SHARE_PANEL_ITEMS_CONTAINER).scrollTo(By.xpath("//android.widget.TextView[@text='"+ShareOptions<EMAIL>()+"']")); List<String> allOptions = actions.element() .withinParent(SHARE_PANEL_ITEMS_CONTAINER) .withinParent(SHARE_PANEL_ITEMS).get() .textFromAllElementsWithSameLocatorAsList(By.xpath("//android.widget.TextView"), "Share Menu Options could not be found!"); if(allOptions.contains(option.getValue())){ actions.touchScreen().withinParent(SHARE_PANEL_ITEMS_CONTAINER) .tap((By.xpath("//android.widget.TextView[@text='"+option.getValue()+"']"))); switch (option) { case FACEBOOK: clickPostForFacebook(); break; case TWITTER: clickTweetForTwitter(); break; case GMAIL: clickSendViaGmail(); break; default: break; } } else breezeReport.logRedStep("["+option.getValue()+"] Menu option is not available!"); } private void clickTweetForTwitter(){ if(actions.element().present().byPolling(TWITTER_TWEET)) actions.element().click().by(TWITTER_TWEET); else breezeReport.logRedStep("Seems Twitter Share window did not open...!!!"); } private void clickPostForFacebook(){ if(actions.element().present().byPolling(FACEBOOK_POST_BTN)) actions.element().click().by(FACEBOOK_POST_BTN); else breezeReport.logRedStep("Seems Facebook Share window did not open...!!!"); } private void clickSendViaGmail(){ if(actions.element().present().byPolling(GMAIL_RCPNT_TO)){ actions.element().textBox().sendKeys(GMAIL_RCPNT_TO, "<EMAIL>"); actions.element().click().by(GMAIL_SEND_BTN); } else breezeReport.logRedStep("Seems Gmail Share window did not open...!!!"); } }
2,179
0.734601
0.734601
64
33.5
34.07666
165
false
false
0
0
0
0
0
0
2.140625
false
false
7
1d0e9df58fe7f2a2e8795477822ee11b3cae2ecf
3,822,520,912,909
89f6bf8a5e850aa275a081758f4fae99ad8af020
/app/src/main/java/edu/auburn/eng/csse/comp3710/cma0036/droidclicker/models/questions/JsonQuestion.java
a0efabd23297d629db05d2543865fd7938bd6624
[]
no_license
Caio-Margutti-Alves/droidClicker
https://github.com/Caio-Margutti-Alves/droidClicker
c1bf89cb51df93bf7d2c8888cc48a81f7e69b3f7
261ec4af15543fefef9b753274eedd0de2259631
refs/heads/master
2021-05-16T02:49:23.804000
2015-05-04T04:27:23
2015-05-04T04:27:23
34,538,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.questions; import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.codeUtils.Util; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.http.HttpUtil; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.alternatives.Alternative; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.alternatives.JsonAlternative; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.quiz.Quiz; public class JsonQuestion { private static final String TAG_QUESTION = "question"; private static final String TAG_QUESTIONS = "questions"; private static final String TAG_ID = "id"; private static final String TAG_ENUNCIATE = "enunciate"; private static final String TAG_ID_RIGHT_ALTERNATIVE = "id_right_alternative"; private static final String TAG_ID_QUIZ = "id"; public static ArrayList<Question> getQuestionsByQuizId(String id) { HttpUtil client = new HttpUtil(); // MEXER AQUI client.AddParam(TAG_ID_QUIZ, id); try { client.Execute(HttpUtil.RequestMethod.GET, HttpUtil.getUrlGetQuestionByQuizId()); } catch (Exception e) { e.printStackTrace(); } //System.out.println(client.getResponse()); return parseJsonQuestion(Util.fix(client.getResponse())); } public static ArrayList<Question> parseJsonQuestion(String in) { ArrayList<Question> questions = null; ArrayList<Alternative> alternatives; try { questions = new ArrayList<Question>(); JSONObject reader = new JSONObject(in); JSONArray jsonQuestions = reader.getJSONArray(TAG_QUESTIONS); // looping through All Contacts for (int i = 0; i < jsonQuestions.length(); i++) { JSONObject jsonCurQuestion = jsonQuestions.getJSONObject(i); JSONObject jsonQuestion = jsonCurQuestion.getJSONObject(TAG_QUESTION); Question question = new Question(); System.out.println(jsonQuestion.toString()); question.setId(jsonQuestion.getString(TAG_ID)); question.setEnunciate(jsonQuestion.getString(TAG_ENUNCIATE)); question.setIdRightAlternative(jsonQuestion.getString(TAG_ID_RIGHT_ALTERNATIVE)); //aqui alternatives = JsonAlternative.getAlternativesFromQuestion(question.getId()); question.setAlternatives(alternatives); questions.add(question); } } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } return questions; } }
UTF-8
Java
2,868
java
JsonQuestion.java
Java
[]
null
[]
package edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.questions; import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.codeUtils.Util; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.http.HttpUtil; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.alternatives.Alternative; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.alternatives.JsonAlternative; import edu.auburn.eng.csse.comp3710.cma0036.droidclicker.models.quiz.Quiz; public class JsonQuestion { private static final String TAG_QUESTION = "question"; private static final String TAG_QUESTIONS = "questions"; private static final String TAG_ID = "id"; private static final String TAG_ENUNCIATE = "enunciate"; private static final String TAG_ID_RIGHT_ALTERNATIVE = "id_right_alternative"; private static final String TAG_ID_QUIZ = "id"; public static ArrayList<Question> getQuestionsByQuizId(String id) { HttpUtil client = new HttpUtil(); // MEXER AQUI client.AddParam(TAG_ID_QUIZ, id); try { client.Execute(HttpUtil.RequestMethod.GET, HttpUtil.getUrlGetQuestionByQuizId()); } catch (Exception e) { e.printStackTrace(); } //System.out.println(client.getResponse()); return parseJsonQuestion(Util.fix(client.getResponse())); } public static ArrayList<Question> parseJsonQuestion(String in) { ArrayList<Question> questions = null; ArrayList<Alternative> alternatives; try { questions = new ArrayList<Question>(); JSONObject reader = new JSONObject(in); JSONArray jsonQuestions = reader.getJSONArray(TAG_QUESTIONS); // looping through All Contacts for (int i = 0; i < jsonQuestions.length(); i++) { JSONObject jsonCurQuestion = jsonQuestions.getJSONObject(i); JSONObject jsonQuestion = jsonCurQuestion.getJSONObject(TAG_QUESTION); Question question = new Question(); System.out.println(jsonQuestion.toString()); question.setId(jsonQuestion.getString(TAG_ID)); question.setEnunciate(jsonQuestion.getString(TAG_ENUNCIATE)); question.setIdRightAlternative(jsonQuestion.getString(TAG_ID_RIGHT_ALTERNATIVE)); //aqui alternatives = JsonAlternative.getAlternativesFromQuestion(question.getId()); question.setAlternatives(alternatives); questions.add(question); } } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } return questions; } }
2,868
0.664226
0.647141
82
33.987804
31.793732
101
false
false
0
0
0
0
0
0
0.707317
false
false
7
089a01c574c7379ee816b174813e7ba8fd7bf5b2
29,678,224,034,300
558db86c64f8551c0ec3bbd00d7a2eb6f4b7f917
/PongKlient/src/com/pong/klient/Main.java
3b5b401bd79bfcaa30cd92b8d3e9c517aaf2252e
[]
no_license
kamilkolmus/PongJava
https://github.com/kamilkolmus/PongJava
8999f29230417decc5d38645bafb527c7665ffa5
130d2db56ba70a53b77254cb1bb72156c763c057
refs/heads/master
2021-05-07T22:56:59.611000
2018-01-31T18:38:30
2018-01-31T18:38:30
107,377,626
0
1
null
false
2018-01-25T02:41:44
2017-10-18T08:08:05
2017-11-13T18:43:41
2018-01-25T02:41:43
805
0
1
0
Java
false
null
package com.pong.klient; import com.pong.gameengine.NumberOfPlayers; import javafx.application.Application; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import java.io.IOException; import java.net.UnknownHostException; public class Main extends Application { private static Main instance; Stage window; MainMenuView mainMenuView; Scene mainMenuScene; GameViewNetworkMultiplayer gameViewNetworkMultiplayer; @Override public void start(Stage primaryStage) throws Exception { window = primaryStage; window.setTitle("Game Pong"); mainMenuView = new MainMenuView(); mainMenuScene = new Scene(mainMenuView); window.setScene(mainMenuScene); window.show(); window.setResizable(false); System.out.println("java version: "+System.getProperty("java.version")); System.out.println("javafx.version: " + System.getProperty("javafx.version")); // przy kliknieciu X wylogowywanie z sewra oraz zakończenie Eventloop window.setOnHiding(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { Platform.runLater(new Runnable() { @Override public void run() { FXMLLoader loader = new FXMLLoader(getClass().getResource("scane_connection_to_serwer.fxml")); try { loader.load(); } catch (IOException e) { e.printStackTrace(); } ControlerConnetionToServer c = loader.getController(); try { if(ControlerConnetionToServer.is_connected_to_server){ c.loguotFromServer(); } } catch (UnknownHostException e) { e.printStackTrace(); } Thread thread= new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if(ControlerConnetionToServer.group!=null){ ControlerConnetionToServer.group.shutdownGracefully(); } } }); thread.start(); } }); } }); } public static void main(String[] args) throws InterruptedException { launch(args); } void setSceneCreditsView(){ CreditsView creditsView = new CreditsView(); window.setScene(new Scene(creditsView)); } void setSceneSinglePlayer(){ GameView gameView = new GameView(NumberOfPlayers.VS_BOT); window.setScene(new Scene(gameView)); gameView.addListener(window); } void setSceneGameModeSelect(){ window.setScene(mainMenuScene); } void setSceneMultiPlayer() { MultiPlayerMenuView multiPlayerMenuView = new MultiPlayerMenuView(); window.setScene(new Scene(multiPlayerMenuView)); } void setSceneGameMultiplayerLocal(){ GameView gameView = new GameView(NumberOfPlayers.TWO_PLAYERS); window.setScene(new Scene(gameView)); gameView.addListener(window); } void setSceneGameMultiplayerNetwork(){ try { window.setScene(new Scene(FXMLLoader.load(getClass().getResource("scane_connection_to_serwer.fxml")))); } catch (IOException e) { e.printStackTrace(); } } void setSceneGameMultiplayerNetworkGame(){ try { gameViewNetworkMultiplayer=new GameViewNetworkMultiplayer(); } catch (IOException e) { e.printStackTrace(); } Main.getInstance().window.setScene(new Scene(gameViewNetworkMultiplayer)); gameViewNetworkMultiplayer.addListener(window); } public Main() { instance = this; } static Main getInstance() { return instance; } }
UTF-8
Java
4,564
java
Main.java
Java
[]
null
[]
package com.pong.klient; import com.pong.gameengine.NumberOfPlayers; import javafx.application.Application; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import java.io.IOException; import java.net.UnknownHostException; public class Main extends Application { private static Main instance; Stage window; MainMenuView mainMenuView; Scene mainMenuScene; GameViewNetworkMultiplayer gameViewNetworkMultiplayer; @Override public void start(Stage primaryStage) throws Exception { window = primaryStage; window.setTitle("Game Pong"); mainMenuView = new MainMenuView(); mainMenuScene = new Scene(mainMenuView); window.setScene(mainMenuScene); window.show(); window.setResizable(false); System.out.println("java version: "+System.getProperty("java.version")); System.out.println("javafx.version: " + System.getProperty("javafx.version")); // przy kliknieciu X wylogowywanie z sewra oraz zakończenie Eventloop window.setOnHiding(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { Platform.runLater(new Runnable() { @Override public void run() { FXMLLoader loader = new FXMLLoader(getClass().getResource("scane_connection_to_serwer.fxml")); try { loader.load(); } catch (IOException e) { e.printStackTrace(); } ControlerConnetionToServer c = loader.getController(); try { if(ControlerConnetionToServer.is_connected_to_server){ c.loguotFromServer(); } } catch (UnknownHostException e) { e.printStackTrace(); } Thread thread= new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if(ControlerConnetionToServer.group!=null){ ControlerConnetionToServer.group.shutdownGracefully(); } } }); thread.start(); } }); } }); } public static void main(String[] args) throws InterruptedException { launch(args); } void setSceneCreditsView(){ CreditsView creditsView = new CreditsView(); window.setScene(new Scene(creditsView)); } void setSceneSinglePlayer(){ GameView gameView = new GameView(NumberOfPlayers.VS_BOT); window.setScene(new Scene(gameView)); gameView.addListener(window); } void setSceneGameModeSelect(){ window.setScene(mainMenuScene); } void setSceneMultiPlayer() { MultiPlayerMenuView multiPlayerMenuView = new MultiPlayerMenuView(); window.setScene(new Scene(multiPlayerMenuView)); } void setSceneGameMultiplayerLocal(){ GameView gameView = new GameView(NumberOfPlayers.TWO_PLAYERS); window.setScene(new Scene(gameView)); gameView.addListener(window); } void setSceneGameMultiplayerNetwork(){ try { window.setScene(new Scene(FXMLLoader.load(getClass().getResource("scane_connection_to_serwer.fxml")))); } catch (IOException e) { e.printStackTrace(); } } void setSceneGameMultiplayerNetworkGame(){ try { gameViewNetworkMultiplayer=new GameViewNetworkMultiplayer(); } catch (IOException e) { e.printStackTrace(); } Main.getInstance().window.setScene(new Scene(gameViewNetworkMultiplayer)); gameViewNetworkMultiplayer.addListener(window); } public Main() { instance = this; } static Main getInstance() { return instance; } }
4,564
0.551392
0.550734
154
28.616882
26.090799
118
false
false
0
0
0
0
0
0
0.376623
false
false
7
bc527d2796084cc7fa6290de7c4359f8704e7af2
16,020,228,036,283
95b5310fe2c74d3321384311146f44997511fb42
/src/main/java/com/demo/mapper/TestMapper.java
1669d25a3e6df456199048df528936706d988eca
[]
no_license
q1054733797/springbootDemo
https://github.com/q1054733797/springbootDemo
c6172f2cc5214aed241657bcc4177669be926bba
68b625ab58fd36fa2e37aedf2c5424e364561eda
refs/heads/master
2020-04-03T09:38:35.639000
2019-02-14T01:13:47
2019-02-14T01:13:47
155,171,506
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.mapper; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.Date; import java.util.HashMap; import java.util.List; /** * @ClassName: TestMapper * @Author: zhanghongkai * @Date: Create in 2018/10/29 11:05 * @Version: 1.0 */ public interface TestMapper { @Insert("insert into t_test(date,name) values(#{date},#{name})") Integer isertTest(@Param("name") String name,@Param("date") Date date); @Delete("delete from t_test") Integer deleteAll(); @Select("Select * from t_test where date > #{beginTime} and date < #{endTime}") List<HashMap<String,Object>> selectBYTime(@Param("beginTime") Date beginTime, @Param("endTime") Date endTime); @Select("select * from t_test") List<HashMap<String,Object>> selectAll(); @Insert("insert into t_test(date,name) values(#{date},#{name})") Integer isertTestByHashMap(HashMap<String,Object> map); @Select("select count(*) from t_test") Integer getCount(); }
UTF-8
Java
1,110
java
TestMapper.java
Java
[ { "context": "l.List;\n\n/**\n * @ClassName: TestMapper\n * @Author: zhanghongkai\n * @Date: Create in 2018/10/29 11:05\n * @Version:", "end": 333, "score": 0.7504158020019531, "start": 321, "tag": "USERNAME", "value": "zhanghongkai" } ]
null
[]
package com.demo.mapper; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.Date; import java.util.HashMap; import java.util.List; /** * @ClassName: TestMapper * @Author: zhanghongkai * @Date: Create in 2018/10/29 11:05 * @Version: 1.0 */ public interface TestMapper { @Insert("insert into t_test(date,name) values(#{date},#{name})") Integer isertTest(@Param("name") String name,@Param("date") Date date); @Delete("delete from t_test") Integer deleteAll(); @Select("Select * from t_test where date > #{beginTime} and date < #{endTime}") List<HashMap<String,Object>> selectBYTime(@Param("beginTime") Date beginTime, @Param("endTime") Date endTime); @Select("select * from t_test") List<HashMap<String,Object>> selectAll(); @Insert("insert into t_test(date,name) values(#{date},#{name})") Integer isertTestByHashMap(HashMap<String,Object> map); @Select("select count(*) from t_test") Integer getCount(); }
1,110
0.7
0.687387
36
29.833334
27.307405
114
false
false
0
0
0
0
0
0
0.638889
false
false
7
c873356ce160fad6220886ad49faff35caca6ae1
13,683,765,832,444
ba561c83bf984087418af66f4fc58395ab5fcd5d
/XtremEngine/src/com/labs/xe/client/ui/XUIFactory.java
b22f8134a5d51e5c276401c2369350a142849e3e
[]
no_license
juanlerch/xe001
https://github.com/juanlerch/xe001
7bdc8e41c31c00befb4458ed836db44a7dcf00d1
c1f6e06fbd76e262fcc829617f9119d028759d22
refs/heads/master
2021-01-22T11:46:52.514000
2015-09-18T17:51:19
2015-09-18T17:51:19
31,987,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.labs.xe.client.ui; import com.labs.xe.client.ui.handler.ToServerHandler; public class XUIFactory { static public XUIBase create (String type) { if (type.equalsIgnoreCase("Button") || type.equalsIgnoreCase(XUIButton.class.getSimpleName())){ XUIButton b= new XUIButton(); b.addEventHandler(new ToServerHandler()); return b; } if (type.equalsIgnoreCase("Panel") || type.equalsIgnoreCase(XUIDockPanel.class.getSimpleName())){ XUIDockPanel b= new XUIDockPanel(); return b; } if (type.equalsIgnoreCase("DialogBox") || type.equalsIgnoreCase(XUIDialogBox.class.getSimpleName())){ XUIDialogBox b= new XUIDialogBox(); b.show(); return b; } if (type.equalsIgnoreCase("TextArea") || type.equalsIgnoreCase(XUITextArea.class.getSimpleName())){ XUITextArea b= new XUITextArea(); return b; } if (type.equalsIgnoreCase("HTML") || type.equalsIgnoreCase(XUIHTML.class.getSimpleName())){ XUIHTML b= new XUIHTML(); return b; } else { XUIHTML html = new XUIHTML(); html.setHTML("can't create : " + type); return html; } } }
UTF-8
Java
1,155
java
XUIFactory.java
Java
[]
null
[]
package com.labs.xe.client.ui; import com.labs.xe.client.ui.handler.ToServerHandler; public class XUIFactory { static public XUIBase create (String type) { if (type.equalsIgnoreCase("Button") || type.equalsIgnoreCase(XUIButton.class.getSimpleName())){ XUIButton b= new XUIButton(); b.addEventHandler(new ToServerHandler()); return b; } if (type.equalsIgnoreCase("Panel") || type.equalsIgnoreCase(XUIDockPanel.class.getSimpleName())){ XUIDockPanel b= new XUIDockPanel(); return b; } if (type.equalsIgnoreCase("DialogBox") || type.equalsIgnoreCase(XUIDialogBox.class.getSimpleName())){ XUIDialogBox b= new XUIDialogBox(); b.show(); return b; } if (type.equalsIgnoreCase("TextArea") || type.equalsIgnoreCase(XUITextArea.class.getSimpleName())){ XUITextArea b= new XUITextArea(); return b; } if (type.equalsIgnoreCase("HTML") || type.equalsIgnoreCase(XUIHTML.class.getSimpleName())){ XUIHTML b= new XUIHTML(); return b; } else { XUIHTML html = new XUIHTML(); html.setHTML("can't create : " + type); return html; } } }
1,155
0.661472
0.661472
43
24.860466
30.796844
103
false
false
0
0
0
0
0
0
2.534884
false
false
7
2b04441e5768a129910da39df99b07eba174e1bf
26,233,660,268,487
b131bd68b0724d050d713230ea433c8347cb01a6
/framework-admin/src/main/java/com/zyk/project/admin/sms/mapper/TSmsConfigMapper.java
ac5aaf72dd10fad342f835fbde567c7c8bf83619
[]
no_license
zyk492322922/framework
https://github.com/zyk492322922/framework
ac44023cc9c72ef6b4c247e672223dda66939e75
96a8e39943880e4f7e8c72780594f75ca2243376
refs/heads/master
2022-07-07T04:08:46.306000
2019-12-31T07:36:51
2019-12-31T07:36:51
184,706,893
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zyk.project.admin.sms.mapper; import com.zyk.project.admin.sms.domain.TSmsConfig; import java.util.List; /** * 短信配置Mapper接口 * * @author ruoyi * @date 2019-12-06 */ public interface TSmsConfigMapper { /** * 查询短信配置 * * @param id 短信配置ID * @return 短信配置 */ public TSmsConfig selectTSmsConfigById(Long id); /** * 查询短信配置列表 * * @param tSmsConfig 短信配置 * @return 短信配置集合 */ public List<TSmsConfig> selectTSmsConfigList(TSmsConfig tSmsConfig); /** * 新增短信配置 * * @param tSmsConfig 短信配置 * @return 结果 */ public int insertTSmsConfig(TSmsConfig tSmsConfig); /** * 修改短信配置 * * @param tSmsConfig 短信配置 * @return 结果 */ public int updateTSmsConfig(TSmsConfig tSmsConfig); /** * 删除短信配置 * * @param id 短信配置ID * @return 结果 */ public int deleteTSmsConfigById(Long id); /** * 批量删除短信配置 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteTSmsConfigByIds(Long[] ids); }
UTF-8
Java
1,256
java
TSmsConfigMapper.java
Java
[ { "context": "ava.util.List;\n\n/**\n * 短信配置Mapper接口\n * \n * @author ruoyi\n * @date 2019-12-06\n */\npublic interface TSmsConf", "end": 160, "score": 0.9995902180671692, "start": 155, "tag": "USERNAME", "value": "ruoyi" } ]
null
[]
package com.zyk.project.admin.sms.mapper; import com.zyk.project.admin.sms.domain.TSmsConfig; import java.util.List; /** * 短信配置Mapper接口 * * @author ruoyi * @date 2019-12-06 */ public interface TSmsConfigMapper { /** * 查询短信配置 * * @param id 短信配置ID * @return 短信配置 */ public TSmsConfig selectTSmsConfigById(Long id); /** * 查询短信配置列表 * * @param tSmsConfig 短信配置 * @return 短信配置集合 */ public List<TSmsConfig> selectTSmsConfigList(TSmsConfig tSmsConfig); /** * 新增短信配置 * * @param tSmsConfig 短信配置 * @return 结果 */ public int insertTSmsConfig(TSmsConfig tSmsConfig); /** * 修改短信配置 * * @param tSmsConfig 短信配置 * @return 结果 */ public int updateTSmsConfig(TSmsConfig tSmsConfig); /** * 删除短信配置 * * @param id 短信配置ID * @return 结果 */ public int deleteTSmsConfigById(Long id); /** * 批量删除短信配置 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteTSmsConfigByIds(Long[] ids); }
1,256
0.57635
0.568901
61
16.606558
16.535385
72
false
false
0
0
0
0
0
0
0.147541
false
false
7
e4f141ad52638f2d9d4b33dd6a732f38bb7f05f6
26,233,660,271,994
57f1f2d3dc6e4c01ed239ac4e288ccee0d6cc3cd
/mylintcode/src/mylintcode/RemoveDupInArray.java
e6497b99326caad20aca58ba1152f3ee7abe6cc3
[]
no_license
Lazybird-Chao/Miscellaneous
https://github.com/Lazybird-Chao/Miscellaneous
79fefda72513afce65ba81b5dab9393ad06c326f
516064b63d4223cbcbfd1a3026e4e10a9aa91678
refs/heads/master
2021-05-03T15:48:22.544000
2018-04-13T01:29:46
2018-04-13T01:29:46
69,478,742
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mylintcode; import java.util.Arrays; public class RemoveDupInArray { public int deduplication(int[] nums){ if(nums == null || nums.length ==0) return 0; Arrays.sort(nums); int i, j; i=j=1; while(j<nums.length){ if(nums[j]!=nums[j-1]){ nums[i]=nums[j]; i++; j++; } else j++; } return i; } }
UTF-8
Java
348
java
RemoveDupInArray.java
Java
[]
null
[]
package mylintcode; import java.util.Arrays; public class RemoveDupInArray { public int deduplication(int[] nums){ if(nums == null || nums.length ==0) return 0; Arrays.sort(nums); int i, j; i=j=1; while(j<nums.length){ if(nums[j]!=nums[j-1]){ nums[i]=nums[j]; i++; j++; } else j++; } return i; } }
348
0.563218
0.551724
25
12.92
11.433004
38
false
false
0
0
0
0
0
0
2.4
false
false
7
8ef87a9d9f103f4c32b142d5cb37112efcaae3f8
6,640,019,465,897
072bc3aeb54d5ee5c09557109bec7d9168b4d7ca
/src/main/java/app/controller/BookController.java
1219a7e1a87a179ce831274fe07940052af79dff
[]
no_license
esnosek/rest-assured-test
https://github.com/esnosek/rest-assured-test
aec7b2cf70304334eedc693a622f934297241c57
43435a26d8c05e026c75cd994829b42170bb4343
refs/heads/master
2021-08-15T06:47:06.877000
2017-11-17T14:53:32
2017-11-17T14:53:32
110,405,032
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.controller; import app.dto.BookDto; import app.model.Book; import app.model.Library; import app.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("") public class BookController { @Autowired private BookService bookService; @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Library> library(@RequestParam(name = "showBooks", required = false) Boolean showBooks){ Library library = new Library(); if(showBooks != null && showBooks) { List<Book> books = bookService.findAll(); library.setBooks(books); } return new ResponseEntity<>(library, HttpStatus.OK); } @PostMapping(value = "/books", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> create(@RequestBody BookDto bookDto){ Book book = bookService.create(new Book(bookDto.getTitle(), bookDto.getAuthor(), bookDto.getYear())); return new ResponseEntity<>(book, HttpStatus.OK); } @GetMapping(value = "/books/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> find(@PathVariable(name = "id") String id){ Book book = bookService.find(id); return book == null ? new ResponseEntity<>(HttpStatus.NOT_FOUND) : new ResponseEntity<>(book, HttpStatus.OK); } @GetMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Book>> findAuthor(@RequestParam(name = "author", required = false) String author){ List<Book> books; if(author != null) books = bookService.findByAuthor(author); else books = bookService.findAll(); return new ResponseEntity<>(books, HttpStatus.OK); } @PutMapping(value = "/books/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> put(@PathVariable(name = "id") String id, @RequestBody BookDto bookDto){ Book book = bookService.put(id, bookDto); return book == null ? new ResponseEntity<>(HttpStatus.BAD_REQUEST) : new ResponseEntity<>(book, HttpStatus.OK); } @DeleteMapping(value = "/books/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> delete(@PathVariable(name = "id") String id){ if(!bookService.exists(id)) return new ResponseEntity<>(HttpStatus.NOT_FOUND); bookService.delete(id); return new ResponseEntity<>(HttpStatus.OK); } @DeleteMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> deleteAll(){ bookService.deleteAll(); return new ResponseEntity<>(HttpStatus.OK); } }
UTF-8
Java
3,058
java
BookController.java
Java
[]
null
[]
package app.controller; import app.dto.BookDto; import app.model.Book; import app.model.Library; import app.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("") public class BookController { @Autowired private BookService bookService; @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Library> library(@RequestParam(name = "showBooks", required = false) Boolean showBooks){ Library library = new Library(); if(showBooks != null && showBooks) { List<Book> books = bookService.findAll(); library.setBooks(books); } return new ResponseEntity<>(library, HttpStatus.OK); } @PostMapping(value = "/books", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> create(@RequestBody BookDto bookDto){ Book book = bookService.create(new Book(bookDto.getTitle(), bookDto.getAuthor(), bookDto.getYear())); return new ResponseEntity<>(book, HttpStatus.OK); } @GetMapping(value = "/books/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> find(@PathVariable(name = "id") String id){ Book book = bookService.find(id); return book == null ? new ResponseEntity<>(HttpStatus.NOT_FOUND) : new ResponseEntity<>(book, HttpStatus.OK); } @GetMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Book>> findAuthor(@RequestParam(name = "author", required = false) String author){ List<Book> books; if(author != null) books = bookService.findByAuthor(author); else books = bookService.findAll(); return new ResponseEntity<>(books, HttpStatus.OK); } @PutMapping(value = "/books/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> put(@PathVariable(name = "id") String id, @RequestBody BookDto bookDto){ Book book = bookService.put(id, bookDto); return book == null ? new ResponseEntity<>(HttpStatus.BAD_REQUEST) : new ResponseEntity<>(book, HttpStatus.OK); } @DeleteMapping(value = "/books/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> delete(@PathVariable(name = "id") String id){ if(!bookService.exists(id)) return new ResponseEntity<>(HttpStatus.NOT_FOUND); bookService.delete(id); return new ResponseEntity<>(HttpStatus.OK); } @DeleteMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Book> deleteAll(){ bookService.deleteAll(); return new ResponseEntity<>(HttpStatus.OK); } }
3,058
0.685415
0.685415
75
39.773335
32.531654
124
false
false
0
0
0
0
0
0
0.666667
false
false
7
863c78edc18a9640282ae458a1a0652f421c196a
33,200,097,219,157
f2a938bf3e35d713524792368fa2afb4cabacf4d
/src/test/java/seleniumTesting/SetWaits.java
ab58b36bdfad2e5e61389278a9f9c0a3946ecc0c
[]
no_license
VolodymyrHunko/Hunko
https://github.com/VolodymyrHunko/Hunko
115233223817cf89489e1c60c060581b84df4699
bcb90419a756969f1263c0bfa79927bb76957a81
refs/heads/master
2023-05-10T16:22:58.166000
2022-10-18T17:19:07
2022-10-18T17:19:07
157,042,822
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package seleniumTesting; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; public class SetWaits { // WebDriver driver = new FirefoxDriver(); WebDriver driver = new ChromeDriver(); @Test public void implicitWait(){ driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://zoom.com"); } @Test public void explicitWait(){ WebDriverWait wait = new WebDriverWait(driver, 10); driver.get("https://zoom.com"); WebElement element = (WebElement) wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("nnnn"))); element.getText(); } @Test public void fluentWait(){ Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(20, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); driver.get("https://zoom.com"); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("nnnn"))); element.getText(); } @Test public void jsExecut(){ WebDriverWait wait = new WebDriverWait(driver, 30); //use JS query as condition Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() { @Override public boolean test(WebDriver driver) { return ((JavascriptExecutor) driver) .executeScript("return document.readyState") .equals("complete"); } }; // wait.until(pageLoaded); } }
UTF-8
Java
1,941
java
SetWaits.java
Java
[]
null
[]
package seleniumTesting; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; public class SetWaits { // WebDriver driver = new FirefoxDriver(); WebDriver driver = new ChromeDriver(); @Test public void implicitWait(){ driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://zoom.com"); } @Test public void explicitWait(){ WebDriverWait wait = new WebDriverWait(driver, 10); driver.get("https://zoom.com"); WebElement element = (WebElement) wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("nnnn"))); element.getText(); } @Test public void fluentWait(){ Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(20, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); driver.get("https://zoom.com"); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("nnnn"))); element.getText(); } @Test public void jsExecut(){ WebDriverWait wait = new WebDriverWait(driver, 30); //use JS query as condition Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() { @Override public boolean test(WebDriver driver) { return ((JavascriptExecutor) driver) .executeScript("return document.readyState") .equals("complete"); } }; // wait.until(pageLoaded); } }
1,941
0.647604
0.642968
62
30.306452
25.961876
115
false
false
0
0
0
0
0
0
0.5
false
false
7
612d045becafad7b1c4b517ecec2dfdb7233dd82
11,149,735,106,877
a6a877127620291450450fc5acb3947041a25517
/app/src/main/java/com/example/asus/smiley/Gerdaloo.java
8856d4a0766a4b10a5f0f4c34d6f0f7a4f1cc034
[]
no_license
s3000-f/CustomViewTest
https://github.com/s3000-f/CustomViewTest
8fc092d3ab30f47295fc7c387c7fb05c7fc24911
5c99e66ce87e74126768fb704f128a41b3d59033
refs/heads/master
2020-03-27T13:04:26.493000
2018-08-29T22:05:34
2018-08-29T22:05:34
146,588,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.asus.smiley; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.Path; import android.graphics.RectF; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.PathInterpolator; import android.widget.RelativeLayout; public class Gerdaloo extends RelativeLayout { String TAG = "Smiley"; private int size; EmotionalFaceView emotionalFaceView; InvCircle[] circles = new InvCircle[30]; float[] tetas = new float[30]; public Gerdaloo(Context context) { super(context); init(context); } public Gerdaloo(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public Gerdaloo(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { float x = ev.getX(); float y = ev.getY(); float loc = (size * 0.5f - x) * (size * 0.5f - x) + (size * 0.5f - y) * (size * 0.5f - y); float max = (size * 0.45f) * (size * 0.45f); float min = (size * 0.35f) * (size * 0.35f); return loc >= min && loc <= max; } //TODO attend warning bellow @Override public boolean onTouchEvent(MotionEvent event) { // Toast.makeText(getContext(), "Touched", Toast.LENGTH_SHORT).show(); float x = event.getX(); float y = event.getY(); float r = size * 0.4f; float ax = size * 0.5f; int n = 30; float ay = ax; float dis = (float) (Math.sqrt((x - ax) * (x - ax) + (y - ay) * (y - ay))); float cx = ax + r * ((x - ax) / dis); float cy = ay + r * ((y - ay) / dis); float cos = (ax - cx) / r; float sin = (ay - cy) / r; int state = 0; float min = (sin - (float) Math.sin(tetas[0]))*(sin - (float) Math.sin(tetas[0])) + (cos- (float) Math.cos(tetas[0]))*(cos- (float) Math.cos(tetas[0])); for (int i = 0; i < n; i++) { float sinT = (float) Math.sin(tetas[i]); float cosT = (float) Math.cos(tetas[i]); float shit = (sin - sinT)*(sin - sinT) * (cos - cosT)*(cos - cosT); if (min > shit) { min = shit; state = i; } } float currentTeta = sin / cos; Log.d(TAG, "onTouchEvent: " + state); circles[1].setAttrs(cx, cy, size * 0.08f); circles[1].invalidate(); float xx = circles[1].x; float yy = circles[1].y; circles[1].setAttrs(cx, cy, size * 0.08f); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Path path = new Path(); RectF oval3 = new RectF( 0, 0, (size-xx), (size-yy)); Log.d(TAG, "onTouchEvent: "+size*0.2+" , "+x); // path.addArc(oval3, 294, -340); path.addRect(oval3, Path.Direction.CCW); // path.arcTo(size * 0.2995f, size * 0.154f, size * 0.7005f, size * 0.8f, 300f, 300f, true); ObjectAnimator animator = ObjectAnimator.ofFloat(circles[1], View.X, View.Y, path); animator.setDuration(2000); animator.start(); } // circles[1].invalidate(); return true; } private void init(final Context context) { circles[0] = new InvCircle(context, null, 1); circles[1] = new InvCircle(context, null, 2); addView(circles[0]); emotionalFaceView = new EmotionalFaceView(context, null); addView(emotionalFaceView); addView(circles[1]); emotionalFaceView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // for (int i = 0; i < 30; i++) { // circles[i] = new InvCircle(context, null, i); // circles[i].setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); // addView(circles[i]); // final int finalI = i; // Log.d(TAG, "init: " + finalI); //// circles[i].setOnClickListener(); // } // Log.d(TAG, "init: here " + size); for (int i = 0; i < 30; i++) { tetas[i] = (float) (i * (2 * Math.PI / 30)); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); emotionalFaceView.setSize(size); circles[0].setAttrs(size * 0.5f, size * 0.5f, size * 0.35f); circles[1].setAttrs(size * 0.2995f, size * 0.154f, size * 0.08f); circles[1].setColor(Color.RED); // int cnt = 0; // for (double i = Math.PI / 6 - Math.PI / 2; i < (2 * Math.PI - Math.PI / 6 - Math.PI / 2) - Math.PI / 18; i += Math.PI / 18) { // float x = (float) (size * 0.5f + size * 0.45f * Math.cos(i)); // float y = (float) (size * 0.5f + size * 0.45f * Math.sin(i)); // if (cnt < 30) { // circles[cnt].setAttrs(x, y, size * 0.05f); // // cnt++; // } // Log.d(TAG, "drawShit: " + i + " , " + x + " , " + y + " , " + size); // } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); size = Math.min(getMeasuredHeight(), getMeasuredWidth()); Log.d(TAG, "onMeasure: " + size); // 2 setMeasuredDimension(size, size); } }
UTF-8
Java
5,756
java
Gerdaloo.java
Java
[]
null
[]
package com.example.asus.smiley; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.Path; import android.graphics.RectF; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.PathInterpolator; import android.widget.RelativeLayout; public class Gerdaloo extends RelativeLayout { String TAG = "Smiley"; private int size; EmotionalFaceView emotionalFaceView; InvCircle[] circles = new InvCircle[30]; float[] tetas = new float[30]; public Gerdaloo(Context context) { super(context); init(context); } public Gerdaloo(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public Gerdaloo(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { float x = ev.getX(); float y = ev.getY(); float loc = (size * 0.5f - x) * (size * 0.5f - x) + (size * 0.5f - y) * (size * 0.5f - y); float max = (size * 0.45f) * (size * 0.45f); float min = (size * 0.35f) * (size * 0.35f); return loc >= min && loc <= max; } //TODO attend warning bellow @Override public boolean onTouchEvent(MotionEvent event) { // Toast.makeText(getContext(), "Touched", Toast.LENGTH_SHORT).show(); float x = event.getX(); float y = event.getY(); float r = size * 0.4f; float ax = size * 0.5f; int n = 30; float ay = ax; float dis = (float) (Math.sqrt((x - ax) * (x - ax) + (y - ay) * (y - ay))); float cx = ax + r * ((x - ax) / dis); float cy = ay + r * ((y - ay) / dis); float cos = (ax - cx) / r; float sin = (ay - cy) / r; int state = 0; float min = (sin - (float) Math.sin(tetas[0]))*(sin - (float) Math.sin(tetas[0])) + (cos- (float) Math.cos(tetas[0]))*(cos- (float) Math.cos(tetas[0])); for (int i = 0; i < n; i++) { float sinT = (float) Math.sin(tetas[i]); float cosT = (float) Math.cos(tetas[i]); float shit = (sin - sinT)*(sin - sinT) * (cos - cosT)*(cos - cosT); if (min > shit) { min = shit; state = i; } } float currentTeta = sin / cos; Log.d(TAG, "onTouchEvent: " + state); circles[1].setAttrs(cx, cy, size * 0.08f); circles[1].invalidate(); float xx = circles[1].x; float yy = circles[1].y; circles[1].setAttrs(cx, cy, size * 0.08f); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Path path = new Path(); RectF oval3 = new RectF( 0, 0, (size-xx), (size-yy)); Log.d(TAG, "onTouchEvent: "+size*0.2+" , "+x); // path.addArc(oval3, 294, -340); path.addRect(oval3, Path.Direction.CCW); // path.arcTo(size * 0.2995f, size * 0.154f, size * 0.7005f, size * 0.8f, 300f, 300f, true); ObjectAnimator animator = ObjectAnimator.ofFloat(circles[1], View.X, View.Y, path); animator.setDuration(2000); animator.start(); } // circles[1].invalidate(); return true; } private void init(final Context context) { circles[0] = new InvCircle(context, null, 1); circles[1] = new InvCircle(context, null, 2); addView(circles[0]); emotionalFaceView = new EmotionalFaceView(context, null); addView(emotionalFaceView); addView(circles[1]); emotionalFaceView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // for (int i = 0; i < 30; i++) { // circles[i] = new InvCircle(context, null, i); // circles[i].setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); // addView(circles[i]); // final int finalI = i; // Log.d(TAG, "init: " + finalI); //// circles[i].setOnClickListener(); // } // Log.d(TAG, "init: here " + size); for (int i = 0; i < 30; i++) { tetas[i] = (float) (i * (2 * Math.PI / 30)); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); emotionalFaceView.setSize(size); circles[0].setAttrs(size * 0.5f, size * 0.5f, size * 0.35f); circles[1].setAttrs(size * 0.2995f, size * 0.154f, size * 0.08f); circles[1].setColor(Color.RED); // int cnt = 0; // for (double i = Math.PI / 6 - Math.PI / 2; i < (2 * Math.PI - Math.PI / 6 - Math.PI / 2) - Math.PI / 18; i += Math.PI / 18) { // float x = (float) (size * 0.5f + size * 0.45f * Math.cos(i)); // float y = (float) (size * 0.5f + size * 0.45f * Math.sin(i)); // if (cnt < 30) { // circles[cnt].setAttrs(x, y, size * 0.05f); // // cnt++; // } // Log.d(TAG, "drawShit: " + i + " , " + x + " , " + y + " , " + size); // } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); size = Math.min(getMeasuredHeight(), getMeasuredWidth()); Log.d(TAG, "onMeasure: " + size); // 2 setMeasuredDimension(size, size); } }
5,756
0.551077
0.524844
160
34.974998
29.084993
160
false
false
0
0
0
0
0
0
1.0625
false
false
7
1fb0a18c06166dc09b2dbcbe2eddccc85a16c484
28,656,021,804,163
58e442daa511dc23bd2f129b1a56af8529645eaa
/src/main/java/planning/service/TimeService.java
8faf1ac456e6b8eb3e823860ecd2dc8aa2faa4ae
[]
no_license
zmazloom/final-project
https://github.com/zmazloom/final-project
55de69bbbe4961af2c961d19c1c23489aee35ff0
d13fcf869364aa9758e8ac120640eb4eed236176
refs/heads/master
2021-03-20T19:37:58.975000
2021-01-05T09:15:06
2021-01-05T09:15:06
247,227,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package planning.service; import planning.model.Time; public class TimeService { public static String getTimePersian(Time time) { switch (time) { case SHANBE8T: return "شنبه 8"; case SHANBE10T: return "شنبه 10"; case SHANBE12T: case SHANBE12O: return "شنبه 12"; case SHANBE14T: return "شنبه 14"; case SHANBE16T: return "شنبه 16"; case SHANBE18O: case SHANBE18T: return "شنبه 18"; case YEKSHANBE8T: return "یکشنبه 8"; case YEKSHANBE10T: return "یکشنبه 10"; case YEKSHANBE12O: case YEKSHANBE12T: return "یکشنبه 12"; case YEKSHANBE14T: return "یکشنبه 14"; case YEKSHANBE16T: return "یکشنبه 16"; case YEKSHANBE18O: case YEKSHANBE18T: return "یکشنبه 18"; case DOSHANBE8T: return "دوشنبه 8"; case DOSHANBE10T: return "دوشنبه 10"; case DOSHANBE12O: case DOSHANBE12T: return "دوشنبه 12"; case DOSHANBE14T: return "دوشنبه 14"; case DOSHANBE16T: return "دوشنبه 16"; case DOSHANBE18O: case DOSHANBE18T: return "دوشنبه 18"; case SESHANBE8T: return "سه شنبه 8"; case SESHANBE10T: return "سه شنبه 10"; case SESHANBE12O: case SESHANBE12T: return "سه شنبه 12"; case SESHANBE14T: return "سه شنبه 14"; case SESHANBE16T: return "سه شنبه 16"; case SESHANBE18O: case SESHANBE18T: return "سه شنبه 18"; case CHARSHANBE8T: return "چهارشنبه 8"; case CHARSHANBE10T: return "چهارشنبه 10"; case CHARSHANBE12O: case CHARSHANBE12T: return "چهارشنبه 12"; case CHARSHANBE14T: return "چهارشنبه 14"; case CHARSHANBE16T: return "چهارشنبه 16"; case CHARSHANBE18O: case CHARSHANBE18T: return "چهارشنبه 18"; case SHANBE730O: return "شنبه 7:30"; case SHANBE9O: return "شنبه 9"; case SHANBE1030O: return "شنبه 10:30"; case SHANBE1330O: return "شنبه 13:30"; case SHANBE15O: return "شنبه 15"; case SHANBE1630O: return "شنبه 16:30"; case YEKSHANBE730O: return "یکشنبه 7:30"; case YEKSHANBE9O: return "یکشنبه 9"; case YEKSHANBE1030O: return "یکشنبه 10:30"; case YEKSHANBE1330O: return "یکشنبه 13:30"; case YEKSHANBE15O: return "یکشنبه 15"; case YEKSHANBE1630O: return "یکشنبه 16:30"; case DOSHANBE730O: return "دوشنبه 7:30"; case DOSHANBE9O: return "دوشنبه 9"; case DOSHANBE1030O: return "دوشنبه 10:30"; case DOSHANBE1330O: return "دوشنبه 13:30"; case DOSHANBE15O: return "دوشنبه 15"; case DOSHANBE1630O: return "دوشنبه 16:30"; case SESHANBE730O: return "سه شنبه 7:30"; case SESHANBE9O: return "سه شنبه 9"; case SESHANBE1030O: return "سه شنبه 10:30"; case SESHANBE1330O: return "سه شنبه 13:30"; case SESHANBE15O: return "سه شنبه 15"; case SESHANBE1630O: return "سه شنبه 16:30"; case CHARSHANBE730O: return "چهارشنبه 7:30"; case CHARSHANBE9O: return "چهارشنبه 9"; case CHARSHANBE1030O: return "چهارشنبه 10:30"; case CHARSHANBE1330O: return "چهارشنبه 13:30"; case CHARSHANBE15O: return "چهارشنبه 15"; case CHARSHANBE1630O: return "چهارشنبه 16:30"; } return ""; } }
UTF-8
Java
4,917
java
TimeService.java
Java
[]
null
[]
package planning.service; import planning.model.Time; public class TimeService { public static String getTimePersian(Time time) { switch (time) { case SHANBE8T: return "شنبه 8"; case SHANBE10T: return "شنبه 10"; case SHANBE12T: case SHANBE12O: return "شنبه 12"; case SHANBE14T: return "شنبه 14"; case SHANBE16T: return "شنبه 16"; case SHANBE18O: case SHANBE18T: return "شنبه 18"; case YEKSHANBE8T: return "یکشنبه 8"; case YEKSHANBE10T: return "یکشنبه 10"; case YEKSHANBE12O: case YEKSHANBE12T: return "یکشنبه 12"; case YEKSHANBE14T: return "یکشنبه 14"; case YEKSHANBE16T: return "یکشنبه 16"; case YEKSHANBE18O: case YEKSHANBE18T: return "یکشنبه 18"; case DOSHANBE8T: return "دوشنبه 8"; case DOSHANBE10T: return "دوشنبه 10"; case DOSHANBE12O: case DOSHANBE12T: return "دوشنبه 12"; case DOSHANBE14T: return "دوشنبه 14"; case DOSHANBE16T: return "دوشنبه 16"; case DOSHANBE18O: case DOSHANBE18T: return "دوشنبه 18"; case SESHANBE8T: return "سه شنبه 8"; case SESHANBE10T: return "سه شنبه 10"; case SESHANBE12O: case SESHANBE12T: return "سه شنبه 12"; case SESHANBE14T: return "سه شنبه 14"; case SESHANBE16T: return "سه شنبه 16"; case SESHANBE18O: case SESHANBE18T: return "سه شنبه 18"; case CHARSHANBE8T: return "چهارشنبه 8"; case CHARSHANBE10T: return "چهارشنبه 10"; case CHARSHANBE12O: case CHARSHANBE12T: return "چهارشنبه 12"; case CHARSHANBE14T: return "چهارشنبه 14"; case CHARSHANBE16T: return "چهارشنبه 16"; case CHARSHANBE18O: case CHARSHANBE18T: return "چهارشنبه 18"; case SHANBE730O: return "شنبه 7:30"; case SHANBE9O: return "شنبه 9"; case SHANBE1030O: return "شنبه 10:30"; case SHANBE1330O: return "شنبه 13:30"; case SHANBE15O: return "شنبه 15"; case SHANBE1630O: return "شنبه 16:30"; case YEKSHANBE730O: return "یکشنبه 7:30"; case YEKSHANBE9O: return "یکشنبه 9"; case YEKSHANBE1030O: return "یکشنبه 10:30"; case YEKSHANBE1330O: return "یکشنبه 13:30"; case YEKSHANBE15O: return "یکشنبه 15"; case YEKSHANBE1630O: return "یکشنبه 16:30"; case DOSHANBE730O: return "دوشنبه 7:30"; case DOSHANBE9O: return "دوشنبه 9"; case DOSHANBE1030O: return "دوشنبه 10:30"; case DOSHANBE1330O: return "دوشنبه 13:30"; case DOSHANBE15O: return "دوشنبه 15"; case DOSHANBE1630O: return "دوشنبه 16:30"; case SESHANBE730O: return "سه شنبه 7:30"; case SESHANBE9O: return "سه شنبه 9"; case SESHANBE1030O: return "سه شنبه 10:30"; case SESHANBE1330O: return "سه شنبه 13:30"; case SESHANBE15O: return "سه شنبه 15"; case SESHANBE1630O: return "سه شنبه 16:30"; case CHARSHANBE730O: return "چهارشنبه 7:30"; case CHARSHANBE9O: return "چهارشنبه 9"; case CHARSHANBE1030O: return "چهارشنبه 10:30"; case CHARSHANBE1330O: return "چهارشنبه 13:30"; case CHARSHANBE15O: return "چهارشنبه 15"; case CHARSHANBE1630O: return "چهارشنبه 16:30"; } return ""; } }
4,917
0.455782
0.387755
145
30.427586
8.538549
52
false
false
0
0
0
0
0
0
0.434483
false
false
7
253b3412a6c989a4be3c5333479b0b00eca0401a
33,311,766,353,211
962328c0f5e44123991bbcde6a5158755c235013
/src/main/java/cn/qingtianr/util/ScanPackage.java
4a6b20f47772e416bffb38cbf430a5e68fc1e716
[]
no_license
yang2yang/YangMvc
https://github.com/yang2yang/YangMvc
4874a8f98147d1d9497779d25fd466a77e3e2688
27f466e62b5931f294f0038f87de64dc092270a0
refs/heads/master
2021-01-23T04:09:49.120000
2017-04-29T15:02:47
2017-04-29T15:02:47
86,167,348
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.qingtianr.util; import cn.qingtianr.Annotation.YangController; import cn.qingtianr.Annotation.YangRequestMapping; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by ding on 2017/4/1. */ public class ScanPackage { //输入 public static List<Class<?>> scan(String packageName) throws ClassNotFoundException, IOException { // String path= getSrcPath()+packageToDir(packageName); String path = "D:\\Documents\\IdeaProjects\\base\\YangMvc\\src\\main\\java" + packageToDir(packageName); ClassLoader cl = ScanPackage.class.getClassLoader(); File dir = new File(path); List<Class<?>> list = new ArrayList<>(); //f.getName()的值是HomeController.java for (File f : dir.listFiles()) { //将下面的名字拼接名字的给优化掉 String s = packageName + "." + f.getName().split("\\.")[0]; Class clazz = Class.forName(s); //判断有没有下面的该目录下面的java文件有没有被YangController注解着 //只获取被YangController注释着的Controller if (clazz.getAnnotation(YangController.class) != null) { list.add(clazz); } } return list; } /** * 获取当前路径 */ public static String getSrcPath() throws IOException { File file = new File(""); String path = file.getCanonicalPath() + File.separator + "src"; return path; } /** * package转换为路径格式 */ public static String packageToDir(String packageName) { String[] array = packageName.split("\\."); StringBuffer sb = new StringBuffer(); for (String str : array) { sb.append(File.separator).append(str); } return sb.toString(); } public static void main(String[] args) throws Exception { // List<Class<?>> list = scan("cn.qingtianr.controller"); // System.out.println(list.size()); // for (Class<?> cla : list) { // System.out.println(cla.getName()); // } // Class clazz = Class.forName("cn.qingtianr.controller.YangHomeController"); // YangController yangController = (YangController) clazz.getAnnotation(YangController.class); // YangRequestMapping yangRequestMapping = (YangRequestMapping) clazz.getAnnotation(YangRequestMapping.class); // System.out.println("123"); URL url = ClassLoader.getSystemResource("cn/qingtianr/controller"); System.out.println(url.getPath()); } }
UTF-8
Java
2,658
java
ScanPackage.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by ding on 2017/4/1.\n */\npublic class ScanPackage {\n\n ", "end": 271, "score": 0.998606264591217, "start": 267, "tag": "USERNAME", "value": "ding" } ]
null
[]
package cn.qingtianr.util; import cn.qingtianr.Annotation.YangController; import cn.qingtianr.Annotation.YangRequestMapping; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by ding on 2017/4/1. */ public class ScanPackage { //输入 public static List<Class<?>> scan(String packageName) throws ClassNotFoundException, IOException { // String path= getSrcPath()+packageToDir(packageName); String path = "D:\\Documents\\IdeaProjects\\base\\YangMvc\\src\\main\\java" + packageToDir(packageName); ClassLoader cl = ScanPackage.class.getClassLoader(); File dir = new File(path); List<Class<?>> list = new ArrayList<>(); //f.getName()的值是HomeController.java for (File f : dir.listFiles()) { //将下面的名字拼接名字的给优化掉 String s = packageName + "." + f.getName().split("\\.")[0]; Class clazz = Class.forName(s); //判断有没有下面的该目录下面的java文件有没有被YangController注解着 //只获取被YangController注释着的Controller if (clazz.getAnnotation(YangController.class) != null) { list.add(clazz); } } return list; } /** * 获取当前路径 */ public static String getSrcPath() throws IOException { File file = new File(""); String path = file.getCanonicalPath() + File.separator + "src"; return path; } /** * package转换为路径格式 */ public static String packageToDir(String packageName) { String[] array = packageName.split("\\."); StringBuffer sb = new StringBuffer(); for (String str : array) { sb.append(File.separator).append(str); } return sb.toString(); } public static void main(String[] args) throws Exception { // List<Class<?>> list = scan("cn.qingtianr.controller"); // System.out.println(list.size()); // for (Class<?> cla : list) { // System.out.println(cla.getName()); // } // Class clazz = Class.forName("cn.qingtianr.controller.YangHomeController"); // YangController yangController = (YangController) clazz.getAnnotation(YangController.class); // YangRequestMapping yangRequestMapping = (YangRequestMapping) clazz.getAnnotation(YangRequestMapping.class); // System.out.println("123"); URL url = ClassLoader.getSystemResource("cn/qingtianr/controller"); System.out.println(url.getPath()); } }
2,658
0.623715
0.619763
76
32.302631
28.862659
117
false
false
0
0
0
0
0
0
0.447368
false
false
7
c9034c522d33ff9f8de2dde979b421a6931cd12b
12,103,217,876,442
2769b90b7982f1eb9c8b5e920a3c76b7f810674c
/Day16-eclipse-ListSon&JDK_NEW/src/com/xiahu/ArrayList/ArrayListDemo.java
18421eca0d47fb121dfb937dedc97a0e329926a0
[]
no_license
xiahuya/javaSE
https://github.com/xiahuya/javaSE
14e82e30f900ed26ac04cfff438b24b6cb76472e
bf40a659f9c69aaa8fe2299998866601ee922edc
refs/heads/master
2022-07-14T01:43:53.903000
2020-05-17T05:13:36
2020-05-17T05:13:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiahu.ArrayList; import java.util.ArrayList; import java.util.Iterator; /* * List的子类特点: * ArrayList: * 底层数据是数组,查询快,增删慢 * 线程不安全,效率高 * Vector: * 底层数据是数组,查询快,增删慢 * 线程安全,效率低 * LinkedList: * 底层数据是链表,查询慢,增删快 * 线程不安全,效率高 * * ArrayList的使用: * 存储字符块并遍历 */ public class ArrayListDemo { public static void main(String[] args) { //创建ArrayList集合 ArrayList al=new ArrayList(); //添加集合对象 al.add("hello"); al.add("java"); al.add("javaEE"); //遍历集合 //Iterator方式遍历 Iterator it=al.iterator(); while(it.hasNext()){ String s=(String)it.next(); System.out.println(s); } System.out.println("--------"); //用for循环 for(int x=0;x<al.size();x++){ String ss=(String)al.get(x); System.out.println(ss); } } }
GB18030
Java
1,052
java
ArrayListDemo.java
Java
[]
null
[]
package com.xiahu.ArrayList; import java.util.ArrayList; import java.util.Iterator; /* * List的子类特点: * ArrayList: * 底层数据是数组,查询快,增删慢 * 线程不安全,效率高 * Vector: * 底层数据是数组,查询快,增删慢 * 线程安全,效率低 * LinkedList: * 底层数据是链表,查询慢,增删快 * 线程不安全,效率高 * * ArrayList的使用: * 存储字符块并遍历 */ public class ArrayListDemo { public static void main(String[] args) { //创建ArrayList集合 ArrayList al=new ArrayList(); //添加集合对象 al.add("hello"); al.add("java"); al.add("javaEE"); //遍历集合 //Iterator方式遍历 Iterator it=al.iterator(); while(it.hasNext()){ String s=(String)it.next(); System.out.println(s); } System.out.println("--------"); //用for循环 for(int x=0;x<al.size();x++){ String ss=(String)al.get(x); System.out.println(ss); } } }
1,052
0.565789
0.564593
49
16.061224
11.123442
41
false
false
0
0
0
0
0
0
1.428571
false
false
7